blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9fd0574ae06a3aa4c704702dbc741b977a4341cb | FlowerbeanAnsh/python_problems_2 | /func.calculate.py | 570 | 4.1875 | 4 | def calculate(a,b):
if op=='+':
c=a+b
return c
elif op=='-':
d=a-b
return d
elif op=='*':
e=a*b
return e
elif op=='/':
f=a/b
return f
elif op=='%':
g=a%b
return g
else:
return False
f=float(input("enter the first value:"))
s=float(input("enter the second value:"))
op=input("enter the operation:")
result=calculate(f,s)
if result==False:
print("your entered operation is not valid,please try again!!!")
else:
print("your result is",result)
| false |
9080fdd3d9bc764d2e48e34b8ad3282f8fcf13d6 | Nihilnia/reset | /Day 3 - list Comprehension.py | 1,032 | 4.25 | 4 | # LIST COMPREHENSION
listem = [1, 2, 3, 4, 5]
yeniListem = []
for f in listem:
yeniListem.append(f)
# print("Eski liste:", listem)
# print("Yeni liste:", yeniListem)
#ListComp.
nihilList = [f for f in listem]
print("Nihil list:", nihilList)
listeDemet = [(1, 2), (3, 4), (5, 6)]
recepList = [f[0] * f[1] for f in listeDemet]
print("Recep list:", recepList)
#List in List?
listemXYZ = [[1, 2], [3, 4], [5, 6]]
ayniSey = [x + y for x, y in listemXYZ]
print("Ayni Şey:", ayniSey)
#other way?
listemASUS = [[1, 2], [3, 4], [5, 6]]
altList = [f[0] + f[1] for f in listemASUS]
print("En yeni listem:", altList)
#another example?
listemNVIDIA = [[1, 2, 3], [3, 4, 5], [5, 6, 7]]
#[1, 2, 3, 3, 4, 5, 5, 6, 7]
yepisyeniListem = [elemanlar for listeler in listemNVIDIA for elemanlar in listeler]
print("Yepisyeni Lİste:", yepisyeniListem)
#and the another one?
eyyo = [["nihil", "python", 24], ["recep", "python", 25]]
yoyo = [y for x in eyyo for y in x]
print("Eyyo:", yoyo) | false |
2de9437f4bb2df0f0928ac1928e62efb8e1eaafa | Nihilnia/reset | /Day 16 - Simple Game_Number Guessing.py | 1,782 | 4.21875 | 4 | # Simple Game - Number Guessing
from time import sleep
from random import randint
rights = 5
number = randint(1, 20)
hintForUser = list()
userChoices = list()
for f in range(number - 3, number + 3):
hintForUser.append(f)
print("Welcome to BASIC Number Guessing Game!")
while rights != 0:
print("You have {} rights for find the number!".format(rights))
userChoice = int(input("What's your choice?\n"))
if userChoice in range(1, 21):
if rights == 1:
if userChoice != number:
print("Let me check..")
sleep(2)
rights -= 1
userChoices.append(userChoice)
print("Game is Over baby. Number was", number)
print("And your choices was:", userChoices)
else:
print("Let me check..")
userChoices.append(userChoice)
sleep(2)
print("Well done! Number was", number)
print("Your choices was:", userChoices)
break
elif userChoice == number:
print("Let me check..")
userChoices.append(userChoice)
sleep(2)
print("Well done! Number was", number)
break
elif userChoice in hintForUser:
print("Let me check..")
userChoices.append(userChoice)
sleep(2)
print("\nClose! Try again!\n")
rights -= 1
else:
print("Let me check..")
userChoices.append(userChoice)
sleep(2)
print("\nNot even close!.. Try again!\n")
rights -= 1
else:
print("Mate.. You should give me a number between 1 - 20!") | true |
622934e84d6a56e6a1b627272ff1b4eaf1b62e12 | Nihilnia/reset | /Day 14 - Parameters at Functions.py | 685 | 4.21875 | 4 | # Parameters at Functions
# if we wanna give any parameters to a Function
#we should insert a value while using.
def EvilBoy(a, b):
print("Function 'EvilBoy' Worked!")
return a + b
print(EvilBoy(2, 3))
# that was a classic function as we know.
# But we can make it some default parameters.
def DoosDronk(a = 2, b = 3):
print("Function 'DoosDrunk' Worked!")
return a + b
# Now we have deafult values of parameters.
#If we don't give values while using that function
#Our default values works.
# Using without parameters:
print("Without Parameters:", DoosDronk())
#Using With Parameters:
print("With Parameteres:", DoosDronk(4, 8)) | true |
7cd318ccc78e1cf79b698818518639ea10ab78b5 | VitalShimanski/Study_Python | /Dictionaries_DZ9.py | 748 | 4.21875 | 4 | favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
peoples = ['adam', 'sergey', 'jen', 'sarah', 'edward', 'lesly', 'amanda', 'phil', 'ivan']
for name in peoples:
if name in peoples and name not in favorite_languages:
print(f"{name.title()} please take our pool!")
else:
print(f"{name.title()} thanks for taking part in the pool!")
print("\n")
rivers = {
'Nile': 'Egipt',
'Amazonka': 'Brazil',
'Yantzy': 'China',
'Missisipy': 'USA',
'Enisey': 'Russia',
'Huanhe': 'China',
'Chambeshi': 'Kongo',
'Amur': 'Russia',
'Lena': 'Russia',
'Niger': 'Nigeria'
}
for key, value in rivers.items():
print(f"{key} runs through {value}") | false |
4e9f13a8c7ecab8c17168286a77e91f07b0c9d73 | favour-22/holbertonschool-higher_level_programming | /0x06-python-classes/5-square.py | 1,124 | 4.34375 | 4 | #!/usr/bin/python3
"""Module containing the Square class"""
class Square:
"""The Square class"""
def __init__(self, size=0):
"""Initializing an instance of Square
Args:
size (int): The size of the Square instance. Default value is 0.
"""
self.size = size
@property
def size(self):
"""int: Value of 'size'"""
return self.__size
@size.setter
def size(self, size):
if not isinstance(size, int):
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
self.__size = size
def area(self):
"""Returns the current square area of the instance
Returns:
int: Value of 'size'
"""
return self.__size ** 2
def my_print(self):
"""Prints a square with hashtags using the 'size'"""
if self.__size is not 0:
for i in range(self.__size):
for j in range(self.__size):
print("#", end="")
print("")
else:
print("")
| true |
867215b59920586cda5067058b049d1373502c6a | skm2000/OOPS- | /Python/Assignment 2/Exercise20/controller.py | 1,907 | 4.25 | 4 | '''
@author: < add your name here >
'''
from tkinter import *
from quiz import Quiz
class Controller:
''' Drive an interactive quiz GUI '''
def __init__(self, window):
''' Create a quiz and GUI frontend for that quiz '''
self.quiz = Quiz()
self.question_text = Text(window, font="arial 16", width = 40, height = 4, wrap = WORD)
self.question_text.insert(1.0, self.quiz.ask_current_question())
self.question_text.pack()
self.answer = StringVar()
self.answerEntry = Entry (window, textvariable = self.answer)
self.answerEntry.pack(side = LEFT)
self.answerEntry.focus_set()
self.answerEntry.bind("<Return>", self.check_answer)
self.instructions = StringVar()
self.instructions.set('\u21D0 Enter your answer here')
self.instrLabel = Label(window, textvariable = self.instructions)
self.instrLabel.pack(side = LEFT)
def check_answer(self, event):
''' Check if the user's current answer is correct '''
if self.quiz.check_current_answer(self.answer.get()):
#Got it right!!
self.instructions.set("Good job! Next question ...")
else:
self.instructions.set("Sorry, the answer was " + self.quiz.get_current_answer())
self.answer.set('')
#Go to the next question if it exists
self.question_text.delete(1.0, END)
if (self.quiz.has_next()):
self.quiz.next()
self.question_text.insert(1.0, self.quiz.ask_current_question())
else:
self.question_text.insert(1.0, 'Sorry, there are no more questions.')
self.answerEntry.configure(state='disabled')
if __name__ == '__main__':
root = Tk()
root.title('Simple Quiz')
app = Controller(root)
root.mainloop()
| true |
6a658a044bee82ceaf20b137cd32ffdc110d1a6b | Aabha-Shukla/Programs | /Aabha_programs/9.py | 300 | 4.34375 | 4 | #Write a program that accepts sequence of lines as input and prints the
#lines after making all characters in the sentence capitalized.
#Suppose the following input is supplied to the program:
str=input('Enter a string:')
if str.lower():
print(str.upper())
else:
print(str.upper())
| true |
691ce469febbe5b4404a3e0fb6e0d65681ab0e2c | Khokavim/Python-Advanced | /PythonNumpy/numpy_matrix_format.py | 497 | 4.53125 | 5 | import numpy as np
matrix_arr =np.array([[3,4,5],[6,7,8],[9,5,1]])
print("The original matrix {}:".format(matrix_arr))
print("slices the first two rows:{}".format(matrix_arr[:2])) # similar to list slicing. returns first two rows of the array
print("Slices the first two rows and two columns:{}".format(matrix_arr[:2, 1:]))
print("returns 6 and 7: {}".format(matrix_arr[1,:2]))
print("Returns first column: {}".format(matrix_arr[:,:1])) #Note that a colon by itself means to take the entire axis
| true |
8801ca4c2ab7197cb3982477f37ed8f743ccac3c | MaineKuehn/workshop-advanced-python-hpc | /solutions/021_argparse.py | 715 | 4.25 | 4 | # /usr/bin/env python3
import argparse
import itertools
import random
CLI = argparse.ArgumentParser(description="Generate Fibonacci Numbers")
CLI.add_argument('--count', type=int, default=random.randint(20, 50), help="Count of generated Numbers")
CLI.add_argument('--start', type=int, default=0, help="Index of first generated Numbers")
def fibonacci():
"""Generate Fibonacci numbers"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def main(): # ask me about __main__!
options = CLI.parse_args()
start, count = options.start, options.cout
for value in itertools.islice(fibonacci(), start, start + count):
print(value)
if __name__ == "__main__":
main()
| true |
08f5b82ba5051d45de9dee198e9e50cdd2b47e0a | sadath-ms/ip_questions | /unique_char.py | 523 | 4.15625 | 4 | """
UNIQUE CHARCTER IN A STRING
Given a string determines, if it is compresied of all unique characters,for example
the string 'abcde' has all unique characters it retrun True else False
"""
def unique_char(st):
return len(set(st)) == len(st)
def unique_char_v2(st):
chars = set()
for u in st:
if u in chars:
return False
else:
chars.add(u)
return True
if __name__ == '__main__':
st = "sadath"
result = unique_char_v2(st)
print(result)
| true |
97f80fb49430024d4d1e7d5742ad5f2ba5e73e59 | rishabhworking/python | /takingInputs.py | 293 | 4.34375 | 4 | # Python Inputs
print('Enter the number: ')
num1 = int(input()) # This is how to take an input
print('Enter the power: ')
num2 = int(input())
power=num1**num2
print(num2,'th power of',num1,'is:',power) # This is how you print vars with strs
# int(input())
# float(input())
# str(input())
| true |
dab9df4b39ba0b10328ea214191edd108e8a3aa1 | ja-vu/SeleniumPythonClass | /Class1/venv/sec4.py | 705 | 4.1875 | 4 | """
Sec 4 - 22
"""
cars = ["bmw", "audi", "lexus"]
empty_list = []
print(cars)
print(empty_list)
print("*#" * 20)
print(cars[0])
num_list = [1, 2, 3]
sum_num = num_list[0] + num_list[1]
print(sum_num)
more_cars = ["honda", "toyota", "KIA"]
print(more_cars[1])
more_cars[1] = "Benz"
print(more_cars[1])
print(more_cars)
"""
Lecture 13
"""
cars_2 = ["bmw", "honda", "audi"]
length = len(cars_2)
print(length)
cars_2.append("Benz")
print(cars_2)
cars_2.insert(1, "Jeep")
print(cars_2)
x = cars_2.index("honda")
print(x)
y = cars_2.pop()
print(y)
print(cars_2)
cars_2.remove("Jeep")
print(cars_2)
slicing = cars_2[1:]
print(slicing)
print("*#" * 20)
print(cars_2)
cars_2.sort()
print(cars_2) | false |
5273a16984fb7298dc231b4cdff161d4529ab76b | ja-vu/SeleniumPythonClass | /Class1/onlineExercises/Q6/StringList.py | 537 | 4.40625 | 4 | """
Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)
https://www.practicepython.org/exercise/2014/03/12/06-string-lists.html
"""
word = input("Give me a word and I will check if this is a palindrome or not: ")
#laval
isPalindrome = False
if word == word[::-1]:
isPalindrome = True
print(word + " is a Palindrome")
else:
print(word + " is not a Palindrome")
print(word + " in reverse order is: " + word[::-1])
| true |
e0d350abd7dc0c984321314ecc148c6b48b4becd | jbhowsthisstuffwork/python_automateeverything | /Practice Projects/theCollatzSequence.py | 968 | 4.375 | 4 | # Create a program that allows a user to input an integer that calls a collatz()
# function on that number until the function returns the value 1.
import time,
userInput = ''
stepsToComplete = 0
def collatz(number):
global userInput
evaluateNumber = number % 2
if evaluateNumber == 0:
userInput = number // 2
print(number)
elif evaluateNumber == 1:
userInput = 3 * number + 1
print(number)
while userInput == '':
try:
userInput = int(input('Enter an integer other than 1.'))
except ValueError:
print('Not a valid integer. Please enter an integer other than 1.')
while userInput != 1:
collatz(userInput)
stepsToComplete = stepsToComplete + 1
# time.sleep(.25) #Pause for .25 seconds
else:
print('You reached', userInput,'and it took',stepsToComplete,'steps to complete.')
#if number = even, then print number // 2
#if number = odd, then print 3 * number + 1
| true |
4ae8f3a983da434c15c25f8da5df8cfb000789f1 | prasoonsoni/Python-Questions-1st-Semester | /EXERCISES/find no of small spheres.py | 533 | 4.25 | 4 | # OPERATORS
""" Q.1 --- TO FIND NO OF SMALL SPHERES OF RADIUS 'r' THAT CAN BE STORED IN
THE LARGE SPHERE OF RADIUS 'R' """
R = float(input("ENTER RADIUS OF LARGE SPHERE(in cm) : "))
r = float(input("ENTER RADIUS OF SMALL SPHERE(in cm) : "))
V = (4/3)*3.14*R*R*R # V = VOLUME OF LARGE SPHERE!!
v = (4/3)*3.14*r*r*r # v = volume of small sphere!!
n = V/v # n = NO OF SMALL SPHERES THAT CAN BE STORED IN LARGE SPHERE
print("NUMBER OF SMALL SPHERES : ", (n))
## MY FIRST PYTHON PROGRAM ##
| false |
e7c927f7a0dc6d4b8fedc95b86665744f50c2d2e | prasoonsoni/Python-Questions-1st-Semester | /EXERCISES/how to use elif.py | 295 | 4.21875 | 4 | """ how to use elif
if condition:
statements
elif condition:
statements """
# largest of three numbers #
a = int(input())
b = int(input())
c = int(input())
if a>b and a>c:
print (a, "is greatest")
elif b>c:
print (b, "is greatest")
else:
print (c, "is greatest") | false |
892c6518f5cd2648b1279998c02168a4c1a00214 | parkjungkwan/telaviv-python-basic | /intro/_12_iter.py | 848 | 4.3125 | 4 | # ***********************
# -- 이터
# ***********************
'''
list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
print (x, end=" ")
or using next() function
while True:
try:
print (next(it))
except StopIteration:
sys.exit() #you have to import sys module for this
'''
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ") # 0 1 1 2 3 5
except StopIteration:
sys.exit() | true |
c6453dc21a3783d471a24360a8f96b9f64c89e6e | Edinburgh-Genome-Foundry/DnaFeaturesViewer | /dna_features_viewer/compute_features_levels.py | 2,402 | 4.28125 | 4 | """Implements the method used for deciding which feature goes to which level
when plotting."""
import itertools
import math
class Graph:
"""Minimal implementation of non-directional graphs.
Parameters
----------
nodes
A list of objects. They must be hashable.
edges
A list of the form [(n1,n2), (n3,n4)...] where (n1, n2) represents
an edge between nodes n1 and n2.
"""
def __init__(self, nodes, edges):
self.nodes = nodes
self.neighbors = {n: [] for n in nodes}
for n1, n2 in edges:
self.neighbors[n1].append(n2)
self.neighbors[n2].append(n1)
def compute_features_levels(features):
"""Compute the vertical levels on which the features should be displayed
in order to avoid collisions.
`features` must be a list of `dna_features_viewer.GraphicFeature`.
The method used is basically a graph coloring:
- The nodes of the graph are features and they will be colored with a level.
- Two nodes are neighbors if and only if their features's locations overlap.
- Levels are attributed to nodes iteratively starting with the nodes
corresponding to the largest features.
- A node receives the lowest level (starting at 0) that is not already
the level of one of its neighbors.
"""
edges = [
(f1, f2)
for f1, f2 in itertools.combinations(features, 2)
if f1.overlaps_with(f2)
]
graph = Graph(features, edges)
levels = {n: n.data.get("fixed_level", None) for n in graph.nodes}
def collision(node, level):
"""Return whether the node placed at base_level collides with its
neighbors in the graph."""
line_factor = 0.5
nlines = node.data.get("nlines", 1)
for neighbor in graph.neighbors[node]:
neighbor_level = levels[neighbor]
if neighbor_level is None:
continue
neighbor_lines = neighbor.data.get("nlines", 1)
min_distance = line_factor * (nlines + neighbor_lines)
if abs(level - neighbor_level) < min_distance:
return True
return False
for node in sorted(graph.nodes, key=lambda f: -f.length):
if levels[node] is None:
level = 0
while collision(node, level):
level += 0.5
levels[node] = level
return levels
| true |
26be85957e8f376c3c24c368451c3b5676a75faa | sanketsoni/practice | /practice/even_first_array.py | 685 | 4.46875 | 4 | """ Reorder array entries so that even entries appear first
Do this without allocating additional storage
example-
a = 3 2 4 5 3 1 6 7 4 5 8 9 0
output = [0, 2, 4, 8, 4, 6, 7, 1, 5, 3, 9, 5, 3]
time complexity is O(n), Space complexity is O(1)
"""
def even_first_array(a):
next_even, next_odd = 0, len(a) - 1
while next_even < next_odd:
if a[next_even] % 2 == 0:
next_even += 1
else:
a[next_even], a[next_odd] = a[next_odd], a[next_even]
next_odd -= 1
print(a)
if __name__ == '__main__':
my_array = [int(x) for x in input("Enter Numbers: ").split()]
even_first_array(my_array)
| true |
778862869cc7e90380b8953d186d59de6b49c950 | Banehowl/MayDailyCode2021 | /DailyCode05102021.py | 950 | 4.3125 | 4 | # ------------------------------------------------
# # Daily Code 05/10/2021
# "Basic Calculator (again)" Lesson from edabit.com
# Coded by: Banehowl
# ------------------------------------------------
# Create a function that takes two numbers and a mathematical operator + - / * and will perform a
# calculation with the given numbers.
# calculator(2, "+", 2) -> 4
# calculator(2, "*", 2) -> 4
# calculator(4, "/", 2) -> 2
def calculator(num, operator, num2):
solution = 0
if operator == "+":
solution = num + num2
elif operator == "-":
solution = num - num2
elif operator == "*":
solution = num * num2
elif operator == "/":
if num2 == 0:
return "Can't Divide by 0!"
else:
solution = num / num2
return solution
print calculator(2, "+", 2)
print calculator(2, "*", 2)
print calculator(4, "/", 2)
print calculator(4, "/", 0) | true |
3d8eaebda59ce03927c28a1b41d44248e2885614 | BerilBBJ/scraperwiki-scraper-vault | /Users/1/1019987/threecirclesunderneath-each-otherpy.py | 838 | 4.28125 | 4 | """ This program draw three circles underneath each other"""
import turtle
turtle.color('Red')
turtle.circle (50,360)
turtle.right(90)
turtle.up()
turtle.forward(10)
turtle.forward(50)
turtle.forward(50)
turtle.left(90)
turtle.color('yellow')
turtle.circle(50,360)
turtle.up()
turtle.down()
turtle.right(90)
turtle.up()
turtle.forward(110)
turtle.down()
turtle.color('green')
turtle.left(90)
turtle.circle(50,360)
""" This program draw three circles underneath each other"""
import turtle
turtle.color('Red')
turtle.circle (50,360)
turtle.right(90)
turtle.up()
turtle.forward(10)
turtle.forward(50)
turtle.forward(50)
turtle.left(90)
turtle.color('yellow')
turtle.circle(50,360)
turtle.up()
turtle.down()
turtle.right(90)
turtle.up()
turtle.forward(110)
turtle.down()
turtle.color('green')
turtle.left(90)
turtle.circle(50,360)
| false |
8f872ae832a6b0a8c3296c46581eb390fca1c4e4 | expelledboy/dabes-py-ddd-example | /domain/common/constraints.py | 701 | 4.15625 | 4 |
def create_string(field_name: str, constructor: function, max_len: int, value: str):
"""
Creates a string field with a maximum length.
:param field_name: The name of the field.
:param constructor: The constructor function.
:param max_len: The maximum length of the string.
:param value: The value of the field.
:return: The constructed field.
"""
# check if the value is not empty
if value is None or value == '':
raise ValueError(f'{field_name} cannot be empty.')
# check if the value is not too long
if len(value) > max_len:
raise ValueError(f"{field_name} must be at most {max_len} characters long.")
return constructor(value) | true |
b763671aa6e2edab48338ca9250b4ec7d1039944 | NFellenor/AINT357_Content | /P3_Recursion_Dynamic_Programming/P3_Recursion_Dynamic_Programming/P3_Recursion_Dynamic_Programming.py | 729 | 4.25 | 4 | #Practical 3: Recursion and dynamic programming:
#Recursivley compute numbers 1-N:
def sumOf(n):
if (n <= 1):
return 1
return n + sumOf(n - 1) #Recursive line
print("Input value for n.")
n = int(input()) #Set value for n by user
print("Sum of values from 1 - n:")
print(sumOf(n))
#Recursively compute largest value in array:
def arraySearch(arrayInp, arrayLength):
if (arrayLength == 1):
return arrayInp[0]
return max(arrayInp[arrayLength - 1], arraySearch(arrayInp, arrayLength - 1)) #Tail recursion
arrayInp = [1, 5, 15, 22, 13, 17]
print("Largest value in array:")
print(arraySearch(arrayInp, 6)) #Pass array length as int. BE CAREFUL it MUST be same as actual array's length
| true |
22dc7651851f3296a2eac7d6d7e035a212ad885a | Nishad00/Python-Practice-Solved-Programs | /Validating_Roman_Numerals.py | 588 | 4.1875 | 4 | # You are given a string, and you have to validate whether it's a valid Roman numeral. If it is valid, print True. Otherwise, print False. Try to create a regular expression for a valid Roman numeral.
# Input Format
# A single line of input containing a string of Roman characters.
# Output Format
# Output a single line containing True or False according to the instructions above.
# Constraints
# The number will be between
# and
# (both included).
# Sample Input
# CDXXI
# Sample Output
# True
regex_pattern = r"^M{0,3}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[VX]|V?I{0,3})$"
| true |
35f10ea897580ce47d4fd020aa9bb9781b1a87e4 | Trent-Farley/All-Code | /Python1/Train Ride/yourturn.py | 621 | 4.40625 | 4 | #Create a trapezoid Calculator-- Here is the formula ((a+b)/2)*h
#USER input
#Create a test to see if an in is even use % (mod) to test
#divisible by zero. USER INPUT
#Find the remainder of a number -- Number can be your choice
#Find the volume and area of a circle from user input
#volume = 4/3 *pi*r^3
#Area = 4 * pi * r^2
bill = "Starter"
while type(bill) != int:
try:
bill = input("What is the bill?\n\n ::")
bill = int(bill)
except:
print("Sorry, wrong data type")
def tip(bill):
tip = bill * .15
return tip
print(f"The tip for a bill of ${bill} is {tip(bill)}")
| true |
9a7a7be1657ff95c6ad6eba58bb1bce27adce8c5 | Trent-Farley/All-Code | /Python1/Old stuff/Assignemt2.py | 671 | 4.375 | 4 | # Farley, Trent
# Assignemt 2
# Problem Analysis: Write a program to calculate the volume
# and surface area of a sphere.
# Program specifications: use the formualas to create a program
# that asked for a radius and outputs the dimensions.
# Design:
# I need to create a float input value. Once that value is calculated,
# I will use the math function to input the radius into the formulat
# Testing:
# if input is 2, the output should be 33 for volume and 50 for area
r=float(input("What is the radius?"))
import math
pi=math.pi
rv=r**3
volume= 4/3 * pi * rv
print(f"This is the volume {volume}")
ra= r ** 2
area= 4* pi* ra
print(f"This is the area {area}") | true |
2b8eb76b4162442da56ba1aaf0ff755e076e7501 | Menda0/pratical-python-2021 | /7_data_structures_exercises.py | 1,228 | 4.40625 | 4 | # 1. Create a list with 5 people names
# 2. Create a tuple with 5 people names
'''
1. Create 6 variables containing animals
(Example: Salmon, Eagle, Bear, Fox, Turtle)
2. Every animal must have the following information
2.1 Name, Color, Sound
3. Create 3 variables for animal families
(Example: Bird, Mamals, Reptiles, Fish)
4. Print on the screen the 3 family animals
5. Print on the screen all the animals
6. Print on the screen 3 equal animals
(Example: 3 Eagles, 3 Bears, 3 Foxes)
'''
# Diogo
salmon = {
"name":"Salmon",
"color":"salmon",
"sound":"gurrp"
}
eagle = {
"name":"eagle",
"color":"brown",
"sound":"pii"
}
bear = {
"name":"bear",
"color":"brown",
"sound":"uaaah"
}
fox = {
"name":"fox",
"color":"orange",
"sound":"lol"
}
whale = {
"name":"Whale",
"color":"Blue",
"sound":"mmmmmmmm"
}
tiger ={
"name":"Tiger",
"color":"Orange",
"sound":"sneaky"
}
mammals = [tiger,bear,whale,fox]
bird = [eagle]
fish = [salmon]
#animals=[salmon,eagle,bear,fox,whale,tiger]
animals=mammals+bird+fish
print("Animals: ", animals)
bears=[bear]*3
print(bears)
list_bear=[bear,bear,bear]
print(list_bear) | true |
7404f874819261a132afccf8937de39a39860cf7 | stahura/school-projects | /CS1400/Projects/rabbits_JRS.py | 2,774 | 4.28125 | 4 | '''
Jeffrey Riley Stahura
CS1400
Project: Rabbits, Rabbits, Rabbits
Due March 10th 2018
Scientists are doing research that requires the breeding of rabbits.
They start with 2 rabbits, 1 male, 1 female.
Every pair reproduces one pair, male and female.
Offspring cannot reproduce until after a month.
Offspring cannot have babies until the following month.
Steps:
Everything must print in a formatted table.
1.Print the following.
A. Months that have passed.
B. Adult rabbit PAIRS(not individuals)(An adult is over 1 month old)
C. Baby rabbit pairs produced in given month(Always a male and female)
D. Total number of rabbit pairs(Adult pairs + baby pairs)
2. Calculate how many months it takes until there are too many rabbits for cages
(There are 500 cages)
3. Don't print any more rows when rabbits exceed cages
4. Print how many months it will take to run out of cages.
* I was stumped on how to remove babies from the baby counter while still adding it to adults
* The solution was creating another variable "lastmonthbabies" and adding that to adults while
* subtracting latmonthbabies from adults to keep the babies variable at the number it should be.
*
*
'''
def main():
print("-----------------------\nRabbits Rabbits Rabbits \n-----------------------")
print("Month Adults Babies Total")
#initialize variables for adults, babies, total, month and last monthbabies
adults = 1
babies = 0
total = adults + babies
month = 1
lastmonthbabies = 0
while total <= 500:
#Print out rows
#Go to next month
#Lastmonth babies needs to be added to adults as part of the new month before babies
# are added to again in the for loop
print("%3d " % month," ", adults," ", babies," ", total, "\n")
month = month + 1
lastmonthbabies = babies
adults = adults + lastmonthbabies
#After the first month, add 1 more baby to babies PER Adult
#Since a baby is no longer a baby after a a month, subtract last months babies
# from adults to get the correct number of babies after each month
#Tally the total amount so that the while loop can stop once it reaches 500
for each in range(1, adults +1):
babies = babies +1
babies = adults - lastmonthbabies
total = adults + babies
#Exited While Loop, print final row and tell user how many months they have.
print("%3d " % month," ", adults," ", babies," ", total, "\n")
print("\nYou will have more rabbits than cages in", month, "months")
main()
| true |
e99e3544eed9a000f67f50aac98fb08c6519c64d | johnsogg/cs1300 | /code/py/lists.py | 482 | 4.125 | 4 | my_empty_list = []
print type(my_empty_list)
my_list = [ 1, 7, 10, 2, 5 ]
my_stringy_list = [ "one", "three", "monkey", "foo"]
my_mixed_list = [ 42, "forty two", True, 61.933, False, None ]
for thing in my_list:
print "My thing is:" + str(thing)
print ""
for thing in my_stringy_list:
print "My stringy thing is: " + thing
squares = []
for num in my_list:
print "num squared is: " + str(num * num)
square = num * num
squares.append(square)
print squares
| true |
12183c6d111eed9b38757e939c3e28ba0051cd01 | tannerbender/E01a-Control-Structues | /main10.py | 1,789 | 4.21875 | 4 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') #printing the word "greetings"
colors = ['red','orange','yellow','green','blue','violet','purple'] #creates a list of colors
play_again = ''
best_count = sys.maxsize # the biggest number
while (play_again != 'n' and play_again != 'no'): #will play again if not correct
match_color = random.choice(colors) #program runs a random color within
count = 0 #creating count
color = '' #allowing user to input a color
while (color != match_color): #color equals match_color
color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line
color = color.lower().strip() #color is lower case and strip eliminates space issues before and after word
count += 1 # each time the game is played it will ad one to the count prior to getting it correct
if (color == match_color): #if color is correct
print('Correct!')#will print correct
else:
print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count))#otherwise it will print try again and tell you how many times you guessed
print('\nYou guessed it in {0} tries!'.format(count))
if (count < best_count): #if it was the best guess
print('This was your best guess so far!') #will print this if it is your best and closest guess
best_count = count
play_again = input("\nWould you like to play again? ").lower().strip()#typing play_again will allow you to restart game
print('Thanks for playing!')#ends by saying "thanks for playing" | true |
36cc2b81e8c17f789d8c1271e9edb497fb9b3b28 | FilipposDe/algorithms-structures-class | /Problems vs. Algorithms/problem_2.py | 2,625 | 4.3125 | 4 | def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
if len(input_list) == 0:
return -1
return search(input_list, 0, len(input_list) - 1, number)
def search(arr, left_index, right_index, target):
if left_index > right_index:
return -1
mid_index = (left_index + right_index) // 2
mid_element = arr[mid_index]
if mid_element == target:
return mid_index
if arr[left_index] <= mid_element:
# Leftmost item is smaller than middle element,
# pivot cannot be in left part, so it is sorted
# (equality: there is no left part)
if arr[left_index] <= target and target < mid_element:
# Target is located in the left part
return search(arr, left_index, mid_index - 1, target)
else:
# Target is located in the right part
return search(arr, mid_index + 1, right_index, target)
elif mid_element <= arr[right_index]:
# Rightmost item is bigger than middle element,
# pivot cannot be in right part, so it is sorted
# (equality: there is no right part)
if mid_element <= target and target < arr[right_index]:
# Target is located in the right part
return search(arr, mid_index + 1, right_index, target)
else:
# Target is located in the right part
return search(arr, left_index, mid_index - 1, target)
return -1
print('\n\n___________ TEST 1 ___________')
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
print(f'Returned: {linear_search(input_list, number)}, Expected: {rotated_array_search(input_list, number)}')
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
print('\n\n___________ TEST 2 ___________')
print(rotated_array_search([], 5))
# Expected: -1
print('\n\n___________ TEST 3 ___________')
print(rotated_array_search([2, 3, 4, 1], 1))
# Expected: 3
| true |
0c6bd0800bf3c1dd2700d50fc7f64de1996ecb5b | Rashi876/python-tasks | /Task 7.py | 369 | 4.125 | 4 | a=float(input("Enter the first number"))
b=float(input("Enter the second number"))
c=float(input("Enter the third number"))
if(a>b):
if(a<c):
median=a
elif(b>c):
median=b
else:
median=c
else:
if(b<c):
median=b
elif(a>c):
median=a
else:
median=c
print("Median equals=",median)
| false |
0244029696dae8f62056f5a9ec987e027a5f9ecb | AH-Toby/PythonBasic | /code/9.python面向对象(二)/demo03.py | 1,152 | 4.15625 | 4 | # 老猫将自己的一身本领传给小猫,同时狗狗也将自己看家的本事传给了小猫
# 定一个父类
class Cat(object):
def __init__(self):
self.kongfu = "厉害的捉鱼本领"
def make_fish(self):
print("利用%s抓鱼" % self.kongfu)
# 定义第二个父类
class Dog(object):
def __init__(self):
self.kongfu = "厉害的看家本领"
def kanmen(self):
print("利用%s看家" % self.kongfu)
# MinCat,继承了Cat、Dog,Cat、Dog是父类。
class MinCat(Cat, Dog):
def __init__(self):
self.kongfu = "厉害的黏人本领"
def make_fish(self):
print("利用自己的新的技术抓鱼")
def kanmen(self):
print("利用自己本领看门")
def makehappy(self):
print("利用%s讨主人开心" % self.kongfu)
xiaohua = MinCat()
print(xiaohua.kongfu) # 子类和父类有同名属性,则默认使用子类的
xiaohua.make_fish() # 子类和父类有同名方法,则默认使用子类的
xiaohua.kanmen()
xiaohua.makehappy()
# 子类的魔法属性__mro__决定了属性和方法的查找顺序
print(MinCat.__mro__) | false |
4258ee738af904684f7d8037c4a5fd2c3a84f7ff | Jesussilverioe/Python-Adventures | /Classes.py | 475 | 4.15625 | 4 | class Dog:
"""Class to create a dog object"""
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(f"{self.name} is sitting...")
print(f"{self.name} is sit.")
def roll(self):
print(f"{self.name} is rolling...")
print(f"{self.name} finish rolling.")
def Get_Age(self):
print(f"{self.name} is {self.age} years old.")
my_dog = Dog('sussie', 10)
my_dog.roll() | false |
94c6d0c3e3b41e61e93a07bff3efb13f19864891 | StefanFischer/Deep-Learning-Framework | /Exercise 3/src_to_implement/Layers/ReLU.py | 1,211 | 4.5 | 4 | """
@description
The Rectified Linear Unit is the standard activation function in Deep Learning nowadays.
It has revolutionized Neural Networks because it reduces the effect of the "vanishing gradient" problem.
@version
python 3
@author
Stefan Fischer
Sebastian Doerrich
"""
import numpy as np
class ReLU:
def __init__(self):
"""
Construct a ReLU-function object.
"""
self.input_tensor = None
def forward(self, input_tensor):
"""
Forward pass for using the ReLU(Rectified Linear Unit)-function.
:param input_tensor: Input tensor for the current layer.
:return: Input tensor for the next layer.
"""
self.input_tensor = input_tensor
relu_passed_input_tensor = np.maximum(0, input_tensor)
return relu_passed_input_tensor
def backward(self, error_tensor):
"""
Backward pass for using the ReLU(Rectified Linear Unit)-function.
:param error_tensor: Error tensor of the current layer.
:return: Error tensor of the previous layer.
"""
relu_passed_error_tensor = np.where(self.input_tensor > 0, error_tensor, [0])
return relu_passed_error_tensor
| true |
4460227115e90388f6b97735aff31ee75e45dc5b | marymarine/sem5 | /hometask2/task2.py | 824 | 4.1875 | 4 | """Task 2: The most popular word"""
def get_list_of_words():
"""return list of input words"""
list_of_words = []
while True:
new_string = input()
if not new_string:
break
list_of_words.extend(new_string.split())
return(list_of_words)
#transform text to list of words
text = get_list_of_words()
#create the dictionary
dictionary = {}
for word in text:
count = dictionary.get(word, 0)
dictionary[word] = count + 1
#find the most popular word
max_count = 0
is_popular = 1
for word in dictionary:
if max_count < dictionary[word]:
max_count = dictionary[word]
popular_word = word
is_popular = 1
elif max_count == dictionary[word]:
is_popular = 0
#print the answer
if is_popular:
print(popular_word)
else:
print("-")
| true |
d38b6f8261f2631f0495bd84160bb6cf1c65400b | julElliot/python | /04.05.2020.py | 517 | 4.125 | 4 | # Программа высчитывает Индекс Массы Тела по введённым параметрам: вес и рост.
print('Введите Ваш вес в килограммах: ')
weight = int(input())
print('Введите Ваш рост в сантиметрах: ')
hight = int(input())
bmi = weight/(hight/100)**2
print('Ваш индекс массы тела:', bmi)
STEPS = 40
scale = '10' + "=" * (round(bmi) - 10) + '|' + "="*(STEPS - (round(bmi) - 10)) + '50'
print(scale) | false |
ada2fab713a61884211b9f9ebf5fa68d37c8ade1 | coopwilliams/Intro-Python-I | /src/is_prime.py | 785 | 4.21875 | 4 | def is_prime(n):
"""Returns True if number is prime."""
if n is not abs(int(n)):
return False #test n a positive number.
if n < 2: #0 and 1 are not primes
return False
if n == 2: #2 is the only even prime
return True
if n % 2 == 0:
return False
for i in range(3, int(n/2) + 1, 2):
if n % i == 0:
print (n, i, (n % i))
return False
return True
primes = [4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993]
non_primes = [4, 459, 98, 999999, 8, 0]
print("some primes:")
for i in primes:
print(i, "\t", is_prime(i))
print("\nsome non-primes:")
for i in non_primes:
print(i, "\t", is_prime(i))
| false |
36b62323bcec79e9690b95b77543581a22af6bd6 | Oscar1305/Python | /Python/Calculadoras.py | 478 | 4.125 | 4 | """
Crea una calculadora que haga las siguientes operaciones con dos números:
suma +
resta -
producto *
división /
módulo %
"""
#variables globales: Acceda a elas desde cualquier parte de mi programa
num1 = 5
num2 = 6
num3 = 7
print ("suma:" + str(num1 + num2 + num3))
print ("suma:" + str(num2 + num1))
print ("resta:" + str(num1 - num2))
print ("producto:" + str(num1 * num2))
print ("división:" + str(num1 / num2))
print ("módulo:" + str(num1 % num2))
| false |
2cd1ed48f5ae3a42ed397974fd56366d82cc733f | zingpython/kungFuShifu | /day_four/23.py | 1,289 | 4.28125 | 4 |
#Convert an interger to a binary in the form of a string
def intToBinary(number):
#Create empty string to hold our new binary number
binary_number = ""
#While our number is greater than 0 Keep dividing by 2 and adding the remainder to binary_number
while number > 0:
#Divmod divindes the 1st number by the 2nd number and returns a tuple with the format (quotient, remainder)
temp_number = divmod(number, 2)
#Set number equal to the quotient from divmod
number = temp_number[0]
#Next add the remainder to the front of binary_number
binary_number = str( temp_number[1] )+ binary_number
#return binary_number
return binary_number
#Convert a binary string to an integer
def binaryToInteger(binary):
#Create a total that will be returned at the end
total = 0
#Increase is the number to increase the total by if the digit of the binary string is a 1
increase = 1
#For each digit in the binary string we will iterate over it backwards
for index in range(len(binary)-1, -1 ,-1 ):
#If the current digit is a 1 then we need to increase total by the variable increase
if binary[index] == "1":
total = total + increase
#Double increase
increase = increase * 2
#return total
return total
print( intToBinary(2000) )
print( binaryToInteger("11111010000") ) | true |
a37cee394a218707cb0ed3b273b2b37316d7aad1 | zingpython/kungFuShifu | /day_four/7.py | 1,651 | 4.28125 | 4 | import math
class SpaceShip:
target = [] #2 values, X and then Y
coordinate = [] #2 values X and then Y
speed = float()
name = ""
def __init__(self, coordinate, target, speed, name):
self.coordinate = coordinate
self.target = target
self.speed = speed
self.name = name
#To find the distence calculate the hypotenuse and divide by the speed
def calculateSteps(self):
#Get the two sides of out "triangle"
difference_x = self.target[0] - self.coordinate[0]
difference_y = self.target[1] - self.coordinate[1]
#Find the hypotenuse
hypotenuse = math.sqrt( (difference_x ** 2) + (difference_y ** 2) )
#Divide by speed and return the result
return hypotenuse / self.speed
def moveSpeed(self):
#Get the two sides of our "triangle"
difference_x = self.target[0] - self.coordinate[0]
difference_y = self.target[1] - self.coordinate[1]
#Find the hypotenuse
hypotenuse = math.sqrt( (difference_x ** 2) + (difference_y ** 2) )
#Find the angle of our new triangle
angle = math.asin( difference_y / hypotenuse )
#using the angle and speed as out hypotenuse calculate the opposite side of the new triangle
change_y = math.sin(angle) * self.speed
#using the angle and speed as our hypotenuse caclute the adjacent sisde of the new triable
change_x = math.cos(angle) * self.speed
#Add the sides of the new triangle to our x and y coordinates to get our new location
self.coordinate[0] = self.coordinate[0] + change_x
self.coordinate[1] = self.coordinate[1] + change_y
my_ship = SpaceShip([1,1], [5,5], 3, "Enterprise")
print( my_ship.calculateSteps() )
my_ship.moveSpeed()
print(my_ship.coordinate) | true |
ff7553d909f1de5f201c5967b9b0a3a4ba62196f | annanymaus/babysteps | /fibrec.py | 952 | 4.375 | 4 | #!/usr/bin/env python3
#program to find the nth fibonacci number using recursion (and no for loops)
import sys
#function definition
def fib(p):
if (p == 0):
return 0
elif (p == 1):
return 1
else:
#recursive equation
c = fib(p-1) + fib(p-2)
return c
#take an input
print ("Enter a number : ")
n = input()
print() #print empty line
print("˜˜˜˜˜˜˜˜˜˜˜") #aesthetic element
print() #print empty line
#if the input is a negative integer
try:
if (int(n) < 0):
print("i don't need this kind of negativity in my life.")
sys.exit(2) #program ends
#if the input is any other character apart from numbers
except SystemExit: #to handle SystemExit exception thrown by sys.exit() in try
sys.exit(2)
except:
print("input is clearly not a number -___- ")
sys.exit(3) #program ends
#printing the final result
print(fib(int(n)))
sys.exit(4)
| true |
cbbd52a5f99ae5018930bbaa3adf865f6e54fefd | prabhatcodes/Python-Problems | /Placement-Tests/Interview-Prep-Astrea/DS.py | 585 | 4.15625 | 4 | # Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None # Null
class LinkedList:
def __init__(self):
self.head = None
if __name__=="__main__":
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second # link first node with second
second.next = third # Link second node with the third node
# Linked List traversal
def __init__(self):
temp = self.head
while (temp):
print (temp.data)
temp = temp.next | true |
2762945abefafb8b1bd35f556a8a313c174dad99 | prabhatcodes/Python-Problems | /Data_Structures/Queues/ArrayQueue.py | 1,182 | 4.125 | 4 | class ArrayQueue:
"""FIFO queue implementation using a Python list as underlying
storage"""
DEFAULT_CAPACITY = 10 # moderate capacity for all new queues
def __init__(self):
"""Create an empty queue"""
self._data = [None]*ArrayQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
"""Return the number of elements in the queue"""
return self._size
def is_empty(self):
"""Return True if the queue is empty"""
return self._size == 0
def first(self):
"""Return (but do not remove) the element from the front
Raise Empty Exception if the Queue is empty"""
if self.is_empty():
raise Empty('Queue is empty')
return self._data[self._front]
def dequeue(self):
"""Remove & Return the first element of the queue(ie FIFO
Raise Empty Exception if the queue is empty"""
if self.is_empty():
raise Empty("Queue is empty")
answer = self._data[self._front]
self._data[self._front]
self._data = (self._front+1)%len(self._data)
self._size-=1
return answer | true |
b94e21fffffeede85942ca87aab41a1ce47a0dfc | sjaney/PDX-Code-Guild---Python-Fullstack-Solution | /python/lab9v2.py | 409 | 4.125 | 4 | # Lab 9v2 ROT Cipher
import string
print('Encrypt your word into a ROT Cipher.')
user = input('Enter a word(s) you would like to encrypt: ')
move = int(input('Enter an amount for rotation: '))
alphabet = string.ascii_lowercase
encryption = ''
for char in user:
if char in alphabet:
new_encrypt = alphabet.index(char) + move
encryption += alphabet[new_encrypt % 26]
print(encryption) | true |
03d19cf620451f9f7d2da74b76cacb689846bdad | holmanapril/Assessment_Quiz | /how_many_questions_v1.py | 456 | 4.1875 | 4 | # Asks how many questions user would like to play
question_amount = int(input("How many questions would you like to play? 10, 15 or 20?"))
# If questions_amount is equal to 10, 15 or 20 it print it
if question_amount == 10 or question_amount == 15 or question_amount == 20:
print("You chose {} rounds".format(question_amount))
# If questions_amount it not one of the choices print please enter 10, 15 or 20
else:
print("Please enter 10, 15 or 20")
| true |
5c4e35cc40030d343bc1cd5504da985827569aa7 | XUMO-97/lpthw | /ex15/ex15.py | 1,610 | 4.375 | 4 | # use argv to get a filename
from sys import argv
# defines script and filename to argv
script, filename = argv
# get the contents of the txt file
txt = open(filename)
# print a string with format characters
print "Here's your file %r:" % filename
# print the contents of the txt file
print txt.read()
txt.close()
# print a sentence
print "Type the filename again:"
# assigns the variable file_again with user's input
file_again = raw_input("> ")
# assigns the variable txt_again with the contents of the txt file
txt_again = open(file_again)
# print the contents of txt_again
print txt_again.read()
txt_again.close()
# study drills 1:Above each line, write out in English what that line does.
# study drills 4:Get rid of the part from lines 10- 15 where you use raw_input and try the script then.
# just print the txt once
# study drills 5:Use only raw_input and try the script that way. Think of why one way of getting the filename would be better than another.
# print "Type the filename again:"
# file_again = raw_input("> ")
# txt_again = open(file_again)
# print txt_again.read()
# if don't use raw_input I needn't to print the filename in python just in command line.
# study drills 7:Start python again and use open from the prompt. Notice how you can open fi les and run read on them right there?
# read=open("C:/Users/18402/lpthw/ex15/ex15_sample.txt")
# read.read()
# read.close()
# study drills 8:Have your script also do a close() on the txt and txt_again variables. It’s important to close fi les when you are done with them.
# ok | true |
457605325a3338e41c9e802600e7b1788b26d476 | ketkiambekar/data-structures-from-scratch | /BFS.py | 728 | 4.3125 | 4 | # Using a Python dictionary to act as an adjacency list
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set() # Set to keep track of visited nodes of graph.
queue=[]
def bfs(visited, graph, node):
visited.add(node)
queue.append(node)
while queue:
m = queue.pop(0)
print(m)
for neighbour in graph[m]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
#OUTPUT
# Following is the Breadth-First Search
# 5
# 3
# 7
# 2
# 4
# 8
| true |
e358ecfabb655068f2fb70954677d220ad1104cd | cwalker4/youtube-recommendations | /youtube_follower/db_utils.py | 2,024 | 4.15625 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_path):
"""
Creates the sqlite3 connection
INTPUT:
db_path: (str) relative path to sqlite db
OUTPUT:
conn: sqlite3 connection
"""
try:
conn = sqlite3.connect(db_path)
except Error as e:
print(e)
return conn
def create_record(conn, table, data):
"""
Inserts "data" into "table"
INTPUT:
conn: sqlite3 connection
table: (str) table name
data: (str) string or iterable of strings containing data
OUTPUT:
search_id: (int) returns iff table == "searches", id of newly created record
"""
cur = conn.cursor()
if table == "searches":
sql = '''
INSERT INTO searches
(root_video, n_splits, depth, date, sample, const_depth)
VALUES (?,?,?,?,?,?)'''
cur.execute(sql, data)
# return the id of the newly created record
sql = 'SELECT max(search_id) FROM searches'
search_id = cur.execute(sql).fetchone()[0]
return search_id
elif table == "videos":
sql = '''
INSERT INTO videos
(video_id, search_id, title, postdate, description, category,
channel_id, likes, dislikes, views, n_comments)
VALUES (?,?,?,?,?,?,?,?,?,?,?)'''
elif table == "channels":
sql = '''
INSERT INTO channels
(channel_id, search_id, name, country, date_created,
n_subscribers, n_videos, n_views)
VALUES (?,?,?,?,?,?,?,?)
'''
elif table == "recommendations":
sql = '''
INSERT INTO recommendations
(video_id, search_id, recommendation, depth)
VALUES (?,?,?,?)
'''
elif table == "channel_categories":
sql = '''
INSERT INTO channel_categories
(channel_id, search_id, category)
VALUES (?,?,?)
'''
cur.executemany(sql, data)
def record_exists(conn, table, col, val):
"""
Checks whether 'col':'val" exists in 'table'
INPUT:
conn: sqlite3 connection
table: (str) table name
col: (str) column name
val: value
OUTPUT:
bool for whether record exsits
"""
sql = ("SELECT * FROM {} WHERE {} = {}"
.format(table, col, val))
cur = conn.cursor()
return bool(cur.execute(sql).fetchall())
| true |
79cc3350735b4fa849f7b9d48a10d7f02f24b057 | ArthurCisotto/insper.dessoft | /Aula 05. Laço/calcula_soma.py | 267 | 4.125 | 4 | soma = 0
num = float(input('Digite o número que você deseja somar ou digite 0 para concluir a soma'))
while num != 0:
soma = soma + num
num = float(input('Digite o número que você deseja somar ou digite 0 para concluir a soma'))
print('A soma é:', soma)
| false |
e37406cab1e981fa6fac68b16cdd9dba407020dd | FrauBoes/PythonMITx | /midterm/midterm str without vowels.py | 621 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 7 14:30:50 2017
@author: thelma
"""
def print_without_vowels(s):
'''
s: the string to convert
Finds a version of s without vowels and whose characters appear in the
same order they appear in s. Prints this version of s.
Does not return anything
'''
s = 'a'
answer = ''
for x in s:
if x != 'a' and x != 'e' and x != 'i' and x != 'o' and x != 'u' and x != 'A' and x != 'E' and x != 'I' and x != 'O' and x != 'U':
answer += x
print(answer)
print_without_vowels("Julia ist klasse bombe") | true |
9888442f8b0c95a2076f5da795ca2e9773a55bd5 | FrauBoes/PythonMITx | /list largest int odd times.py | 583 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 26 15:42:29 2017
@author: thelma
"""
def largest_odd_times(L):
""" Assumes L is a non-empty list of ints
Returns the largest element of L that occurs an odd number
of times in L. If no such element exists, returns None """
L_work = sorted(L)
while len(L_work) > 0 and L_work.count(max(L_work)) % 2 == 0:
del L_work[-(L_work.count(max(L_work))):]
if len(L_work) == 0:
return None
else:
return max(L_work)
print(largest_odd_times([3, 3, 2, 0]))
| true |
213c8884c28e68a3786eecb730f0d4672b031a32 | FrauBoes/PythonMITx | /max value tuple.py | 662 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 31 10:12:33 2017
@author: thelma
"""
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t """
max_int = 0
for element in t:
if type(element) == int:
if element > max_int:
max_int = element
else:
if max_val(element) > max_int:
max_int = max_val(element)
return max_int
print(max_val(([[2, 1, 5], [4, 2], 6], ([2, 1], (7, 7, 5), 6)))) | true |
8bd6ed86b4ea0f992b531f5b229b7026525125c4 | shovals/PythonExercises | /max of 3.py | 307 | 4.34375 | 4 | # max of 3 show the largest number from 3 numbers
One = input('Enter first number: ')
Two = input('Enter second number: ')
Third = input('Enter third number: ')
if One > Third and One > Two:
print 'Max is ', One
elif Two > One and Two > Third:
print 'Max is ', Two
else:
print 'Max is', Third | true |
d5336239b5db506f80269d85f8b0b4bb6ca9f4ab | dcragusa/LeetCode | /1-99/70-79/75.py | 2,062 | 4.34375 | 4 | """
Given an array with n objects colored red, white or blue (represented by integers 0, 1, and 2), sort them in-place so
that objects of the same color are adjacent, with the colors in the order red, white and blue.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Input: [2, 0, 2, 1, 1, 0], Output: [0, 0, 1, 1, 2, 2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate over the array counting the number of 0's, 1's, and 2's, then overwrite the array.
Could you come up with a one-pass algorithm using only constant space?
"""
"""
This is a one-pass algorithm with constant space: we iterate over the array, keeping two indices to the front and back
of the array respectively. We make a loop for each element, swapping 0s to the front of the array and 2s to the back,
breaking if we find a 1 or we are moving to the current index. We can stop iterating when we reach the index to the
back of the array, as we know the rest consists of 2s.
"""
def sort_colors(nums):
idx, low, high = 0, 0, len(nums) - 1
while idx <= high:
while True:
val = nums[idx]
if val == 0:
if idx == low:
break
nums[idx], nums[low] = nums[low], nums[idx]
low += 1
elif val == 2:
if idx == high:
break
nums[idx], nums[high] = nums[high], nums[idx]
high -= 1
else:
break
idx += 1
return nums
assert sort_colors([0]) == [0]
assert sort_colors([0, 0]) == [0, 0]
assert sort_colors([0, 1]) == [0, 1]
assert sort_colors([0, 2]) == [0, 2]
assert sort_colors([1, 2]) == [1, 2]
assert sort_colors([2, 1]) == [1, 2]
assert sort_colors([2, 0, 1]) == [0, 1, 2]
assert sort_colors([2, 2, 1, 1, 0, 0]) == [0, 0, 1, 1, 2, 2]
assert sort_colors([2, 0, 2, 1, 1, 0]) == [0, 0, 1, 1, 2, 2]
assert sort_colors([1, 2, 2, 2, 2, 0, 0, 0, 1, 1]) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
| true |
bd42aae37e10dd6af40b2f9deaef942a5bfa4218 | dcragusa/LeetCode | /100-199/110-119/112.py | 1,419 | 4.1875 | 4 | """
Given the root of a binary tree and an integer `target_sum`, return `True` if the tree has a root-to-leaf path
such that adding up all the values along the path equals `target_sum`. A leaf is a node with no children.
Example 1:
Input: root = [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1], target_sum = 22, Output: true (5 + 4 + 11 + 2)
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
Example 2:
Input: root = [1, 2, 3], target_sum = 5, Output: false
1
/ \
2 3
Example 3:
Input: root = [1, 2], target_sum = 0, Output: false
1
/
2
"""
"""
We decrement target_sum as we recur down the list. If we find a leaf node equal to target_sum, then there is a path.
"""
from shared import list_to_tree
def has_path_sum(root, target_sum):
if root is None:
return False
if root.left is None and root.right is None and root.val == target_sum:
return True
return has_path_sum(root.left, target_sum - root.val) or has_path_sum(root.right, target_sum - root.val)
assert has_path_sum(list_to_tree([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1]), 22) is True
assert has_path_sum(list_to_tree([1, 2, 3]), 5) is False
assert has_path_sum(list_to_tree([1, 2]), 0) is False
assert has_path_sum(list_to_tree([-2, None, -3]), -5) is True
assert has_path_sum(list_to_tree([8, 9, -6, None, None, 5, 9]), 7) is True
| true |
6b1914ee8aab2ad9a6d4dacc0ade2581acaf5894 | dcragusa/LeetCode | /1-99/90-99/98.py | 1,908 | 4.3125 | 4 | """
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
2
/ \
1 3
Input: [2, 1, 3], Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5, 1, 4, None, None, 3, 6], Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
"""
"""
For each node, we obtain the min and max of the left and right side values respectively. If the left max is larger or
the right min is smaller than the node, the tree is invalid. We then propagate the min and max of the node val and the
previously obtained min/maxes upwards. We take when returning the result that a tuple evaluates to True.
"""
from shared import list_to_tree
def is_valid_bst(root):
if root is None or root.val is None:
return True
def recur(node):
vals = [node.val]
if node.left:
recur_left = recur(node.left)
if not recur_left or recur_left[1] >= node.val:
return False
vals.extend(recur_left)
if node.right:
recur_right = recur(node.right)
if not recur_right or recur_right[0] <= node.val:
return False
vals.extend(recur_right)
return min(vals), max(vals)
return bool(recur(root))
assert is_valid_bst(None) is True
assert is_valid_bst(list_to_tree([None])) is True
assert is_valid_bst(list_to_tree([2, 1, 3])) is True
assert is_valid_bst(list_to_tree([5, 1, 4, None, None, 3, 6])) is False
# 10
# / \
# 5 15
# / \
# 6 20
assert is_valid_bst(list_to_tree([10, 5, 15, None, None, 6, 20])) is False
| true |
ab4cde1297d67e70cf920c2288309e179085cdf8 | dcragusa/LeetCode | /1-99/20-29/24.py | 1,823 | 4.34375 | 4 | """
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
"""
Firstly we swap the first two elements. We then iterate across the list, copying the nodes into temporary variables
so as not to mess the order, and reassigning the next params as needed.
From current -> current.next -> current.next.next -> current.next.next.next, we need to swap the central two elements.
We end up with current -> current.next.next -> current.next -> current.next.next.next, then we just move current
two elements along and repeat.
"""
from shared import python_list_to_linked_list, linked_list_to_python_list
def swap_pairs(head):
if not head or not head.next:
return head
current = head
head = head.next
current.next = current.next.next
head.next = current
while current and current.next and current.next.next:
n = current.next
n_n = n.next
n_n_n = n_n.next
n.next = n_n_n
n_n.next = n
current.next = n_n
current = current.next.next
return head
assert linked_list_to_python_list(swap_pairs(None)) == []
head = python_list_to_linked_list([1])
assert linked_list_to_python_list(swap_pairs(head)) == [1]
head = python_list_to_linked_list([1, 2])
assert linked_list_to_python_list(swap_pairs(head)) == [2, 1]
head = python_list_to_linked_list([1, 2, 3])
assert linked_list_to_python_list(swap_pairs(head)) == [2, 1, 3]
head = python_list_to_linked_list([1, 2, 3, 4, 5, 6])
assert linked_list_to_python_list(swap_pairs(head)) == [2, 1, 4, 3, 6, 5]
head = python_list_to_linked_list([1, 2, 3, 4])
assert linked_list_to_python_list(swap_pairs(head)) == [2, 1, 4, 3]
| true |
efd2f12aa8c7ab9bc45d150e747852c70010529f | dcragusa/LeetCode | /1-99/70-79/70.py | 2,026 | 4.28125 | 4 | """
You are climbing a staircase with n steps. Each time you can either climb 1 or 2 steps.
In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2, Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3, Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
"""
"""
We can either set up the base cases for 1 and 2 steps, then recur downwards, adding and memoizing as we go.
Alternatively, we can realise that this is the number of unique permutations of a multiset of varying quantities
of 1s and 2s. For example, for n=6 we must find the unique permutations of the multisets {1, 1, 1, 1, 1, 1},
{2, 1, 1, 1, 1}, {2, 2, 1, 1}, and {2, 2, 2}. The number of unique permutations of a multiset is, as we examined in
problem 62, the multinomial coefficient (n_a + n_b + ... )! / n_a! * n_b! * ... Therefore we just have to calculate
the multinomial coefficients of the multisets with the number of 2s varying from 0 to n // 2.
"""
from math import factorial
from functools import lru_cache
@lru_cache()
def climb_stairs_slow(n):
if n == 1:
return 1
elif n == 2:
return 2
else:
return climb_stairs_slow(n-1) + climb_stairs_slow(n-2)
def climb_stairs_fast(n):
combinations = 1
twos = 1
while twos * 2 <= n:
ones = n - 2*twos
combinations += factorial(twos + ones) // (factorial(twos) * factorial(ones))
twos += 1
return combinations
assert climb_stairs_slow(2) == climb_stairs_fast(2) == 2
assert climb_stairs_slow(3) == climb_stairs_fast(3) == 3
assert climb_stairs_slow(4) == climb_stairs_fast(4) == 5
assert climb_stairs_slow(5) == climb_stairs_fast(5) == 8
assert climb_stairs_slow(6) == climb_stairs_fast(6) == 13
assert climb_stairs_slow(10) == climb_stairs_fast(10) == 89
assert climb_stairs_slow(38) == climb_stairs_fast(38) == 63245986
| true |
1e941dff165827fd643b735fb82593730409c85b | dcragusa/LeetCode | /100-199/110-119/113.py | 1,532 | 4.125 | 4 | """
Given the root of a binary tree and an integer `target_sum`, return `True` if the tree has a root-to-leaf path
such that adding up all the values along the path equals `target_sum`. A leaf is a node with no children.
Example 1:
Input: root = [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1], target_sum = 22
Output: [[5, 4, 11, 2], [5, 8, 4, 5]]
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Example 2:
Input: root = [1, 2, 3], target_sum = 5, Output: []
1
/ \
2 3
Example 3:
Input: root = [1, 2], target_sum = 0, Output: []
1
/
2
"""
"""
Similar to 112, except we keep track of the path as we recur down the tree, and append it to a list of results
when we find a matching leaf node.
"""
from shared import list_to_tree
def path_sum(root, target_sum):
results = []
def helper(node, path, target_sum):
if node is None:
return
if node.left is None and node.right is None and node.val == target_sum:
results.append(path + [node.val])
if node.left:
helper(node.left, path + [node.val], target_sum - node.val)
if node.right:
helper(node.right, path + [node.val], target_sum - node.val)
helper(root, [], target_sum)
return results
assert path_sum(list_to_tree([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1]), 22) == [[5, 4, 11, 2], [5, 8, 4, 5]]
assert path_sum(list_to_tree([1, 2, 3]), 5) == []
assert path_sum(list_to_tree([1, 2]), 0) == []
| true |
9fbc99a4530e82bbeb3d7e3b378e840ad23a5662 | dcragusa/LeetCode | /100-199/140-149/144.py | 1,042 | 4.15625 | 4 | """
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1, None, 2, 3], Output: [1, 2, 3]
1
\
2
/
3
Example 2:
Input: root = [], Output: []
Example 3:
Input: root = [1], Output: [1]
Example 4:
Input: root = [1, 2], Output: [1, 2]
1
/
2
Example 5:
Input: root = [1, None, 2], Output: [1, 2]
1
\
2
"""
"""
For preorder traversal, do value, left child, right child.
"""
from shared import list_to_tree
def preorder_traversal(root):
results = []
def helper(node):
if node is None:
return
results.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
return results
assert preorder_traversal(list_to_tree([1, None, 2, 3])) == [1, 2, 3]
assert preorder_traversal(list_to_tree([])) == []
assert preorder_traversal(list_to_tree([1])) == [1]
assert preorder_traversal(list_to_tree([1, 2])) == [1, 2]
assert preorder_traversal(list_to_tree([1, None, 2])) == [1, 2]
| true |
7e6d0cac3b718470e86944b508f19fda5343da79 | dcragusa/LeetCode | /1-99/40-49/43.py | 958 | 4.5625 | 5 | """
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2,
also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3", Output: "6"
Example 2:
Input: num1 = "123", num2 = "456", Output: "56088"
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
"""
"""
Fairly trivial to convert strings to numbers indirectly using ord(), also helpful is Python's infinite integers.
"""
def str_to_num(s):
num = 0
for pow_10, digit in enumerate(reversed(s)):
num += (ord(digit) - ord('0')) * 10**pow_10
return num
def multiply(num1, num2):
return str(str_to_num(num1) * str_to_num(num2))
assert multiply('2', '3') == '6'
assert multiply('123', '456') == '56088'
| true |
58df73678cbd095fea3ed3c477f05cbe81eebf9d | dcragusa/LeetCode | /1-99/60-69/67.py | 528 | 4.1875 | 4 | """
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1", Output: "100"
Example 2:
Input: a = "1010", b = "1011", Output: "10101"
"""
"""
This is fairly trivial to do by converting the arguments into integers and the result back into a string.
"""
def add_binary(a, b):
return bin(int(a, 2) + int(b, 2))[2:]
assert add_binary('11', '1') == '100'
assert add_binary('1010', '1011') == '10101'
| true |
c1b6ad529f2be7716814c1a16d4afd51c4aeeddb | dcragusa/LeetCode | /1-99/20-29/22.py | 1,998 | 4.3125 | 4 | """
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
['((()))', '(()())', '(())()', '()(())', '()()()']
"""
"""
We start with one pair of parentheses, which can only be (). For each additional pair, we add an open bracket
to the front [(()], then iterate across the solutions inserting a close bracket after every available open
bracket [()(), (())]. Via recursion we can apply this method to any number of parentheses.
"""
def generate_parentheses(n):
if n == 0:
return set()
if n == 1:
return {'()'}
else:
solutions = set()
for solution in generate_parentheses(n-1):
for idx, char in enumerate(solution := '(' + solution):
if char == '(':
solutions.add(solution[:idx+1]+')'+solution[idx+1:])
return solutions
assert generate_parentheses(0) == set()
assert generate_parentheses(1) == {'()'}
assert generate_parentheses(2) == {'()()', '(())'}
assert generate_parentheses(3) == {'((()))', '(()())', '(())()', '()(())', '()()()'}
assert generate_parentheses(4) == {
'(((())))', '((()()))', '((())())', '((()))()', '(()(()))', '(()()())', '(()())()',
'(())(())', '(())()()', '()((()))', '()(()())', '()(())()', '()()(())', '()()()()'
}
assert generate_parentheses(5) == {
'((((()))))', '(((()())))', '(((())()))', '(((()))())', '(((())))()', '((()(())))', '((()()()))', '((()())())',
'((()()))()', '((())(()))', '((())()())', '((())())()', '((()))(())', '((()))()()', '(()((())))', '(()(()()))',
'(()(())())', '(()(()))()', '(()()(()))', '(()()()())', '(()()())()', '(()())(())', '(()())()()', '(())((()))',
'(())(()())', '(())(())()', '(())()(())', '(())()()()', '()(((())))', '()((()()))', '()((())())', '()((()))()',
'()(()(()))', '()(()()())', '()(()())()', '()(())(())', '()(())()()', '()()((()))', '()()(()())', '()()(())()',
'()()()(())', '()()()()()'
}
| true |
27419cc9188daaf8cf78d2be008f21ce35b4d98c | dcragusa/LeetCode | /1-99/30-39/38.py | 1,668 | 4.28125 | 4 | """
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively,
in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1, Output: "1"
Explanation: This is the base case.
Example 2:
Input: 4, Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1",
"2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11",
so the answer is the concatenation of "12" and "11" which is "1211".
"""
"""
We can avoid expensive function calls by simply copying over the list with the next iteration of the sequence.
"""
def count_and_say(n):
digits = [1]
for i in range(2, n+1):
new_digits = []
count = 0
last_digit = None
for digit in digits:
if last_digit and digit != last_digit:
new_digits.extend([count, last_digit])
count = 0
count += 1
last_digit = digit
new_digits.extend([count, last_digit])
digits = new_digits
return ''.join(map(str, digits))
assert count_and_say(1) == '1'
assert count_and_say(4) == '1211'
assert count_and_say(12) == '3113112221232112111312211312113211'
| true |
a7642a80d728d5c5ed8b717e02f31973c13c997d | dcragusa/LeetCode | /1-99/90-99/92.py | 1,845 | 4.21875 | 4 | """
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4, Output: 1->4->3->2->5->NULL
"""
"""
We obtain the first node we are reversing (current), along with the node before that (reversal_head). Then we iterate
along the nodes we are reversing, adding them to a stack. Finally, we go back down the stack, adding the last node to
reversal_head and advancing reversal_head. (If m is 1, that means the head itself is being reversed, so reversal_head
is the first node popped off the stack). Finally, we set the next node to be the continuation of the original list.
"""
from shared import python_list_to_linked_list, linked_list_to_python_list
def reverse_between(head, m, n):
current = head
if m == 1:
reversal_head = None
else:
for _ in range(m-2):
current = current.next
reversal_head = current
current = current.next
stack = []
for _ in range(n-m+1):
stack.append(current)
current = current.next
while stack:
if reversal_head:
reversal_head.next = stack.pop()
reversal_head = reversal_head.next
else:
reversal_head = stack.pop()
head = reversal_head
reversal_head.next = current
return head
assert linked_list_to_python_list(reverse_between(python_list_to_linked_list([1, 2, 3, 4, 5]), 4, 5)) == [1, 2, 3, 5, 4]
assert linked_list_to_python_list(reverse_between(python_list_to_linked_list([1, 2, 3, 4, 5]), 1, 5)) == [5, 4, 3, 2, 1]
assert linked_list_to_python_list(reverse_between(python_list_to_linked_list([1, 2, 3, 4, 5]), 1, 2)) == [2, 1, 3, 4, 5]
assert linked_list_to_python_list(reverse_between(python_list_to_linked_list([1, 2, 3, 4, 5]), 2, 4)) == [1, 4, 3, 2, 5]
| true |
1f30fbf51386a7dff9fdf22a6032fb0f554578e2 | dcragusa/LeetCode | /1-99/50-59/50.py | 1,934 | 4.1875 | 4 | """
Implement pow(x, n), which calculates x raised to the power n (x^n).
Example 1:
Input: 2.00000, 10, Output: 1024.00000
Example 2:
Input: 2.10000, 3, Output: 9.26100
Example 3:
Input: 2.00000, -2, Output: 0.25000, Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0, n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
"""
"""
Of course this is batteries included with Python. An alternative implementation is provided below. We cannot keep
multiplying in a range over n as n can be huge. Instead we realise that we can use binary decomposition but
representing powers instead of integers. For example bin(13)=b1101. We go through the binary representation backwards,
representing a power of 13 as powers of 1, 4, 8 multiplied together. The next power in the sequence can be trivially
calculated from the previous one (e.g. power of 8 = power by 4 * power by 4). We just have to watch out for
float precision constraints. Floats generally round out at 17dp so we check this after every iteration of the power
sequence and terminate early if appropriate. We also have to watch out for the negative sign if present.
"""
def my_pow(x, n):
if n < 0:
x = 1/x
sign = -1 if (x < 0 and n % 2) else 1
res, last_power = 1, 0
for pow_2, bit in enumerate(reversed(bin(abs(n))[2:])):
power = abs(x) if not pow_2 else last_power * last_power
last_power = power
if bit == '1':
res *= power
if 0 < last_power < 10**-17:
return 0
elif last_power > 10**17:
return float('inf') * sign
return res * sign
assert my_pow(10.0, 0) == 1
assert my_pow(10.0, 5) == 100000
assert my_pow(10.0, -1) == 0.1
assert my_pow(2.00000, 10) == 1024.00000
assert my_pow(2.10000, 3) == 9.261000000000001
assert my_pow(2.00000, -2) == 0.25000
assert my_pow(-2.0, 2) == 4.0
assert my_pow(-13.62608, 3) == -2529.9550389278597
| true |
9e13c18fc3efdb57e2b52a035f8449b1288e312e | dcragusa/LeetCode | /1-99/70-79/71.py | 2,137 | 4.25 | 4 | """
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the
directory up a level. Note that the returned canonical path must always begin with a slash /, and there must be only
a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /.
Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: '/home/', Output: '/home'
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: '/../', Output: '/'
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: '/home//foo/', Output: '/home/foo'
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: '/a/./b/../../c/', Output: '/c'
Example 5:
Input: '/a/../../b/../c//.//', Output: '/c'
Example 6:
Input: '/a//b////c/d//././/..', Output: '/a/b/c'
"""
"""
Fairly simple, we just split on / and ignore any . or empty spaces as these are repeated slashes or the same directory.
We append any directories to a stack and if there are any .. we pop an item off the stack, if present. Then at the end
we merely join the items from the stack back up again to form the canonical path.
"""
def simplify_path(path):
stack = []
for item in path.split('/'):
if item in ['', '.']:
continue
elif item == '..':
if stack:
stack.pop()
else:
stack.append(item)
return '/' + '/'.join(stack)
assert simplify_path('/home/') == '/home'
assert simplify_path('../../') == '/'
assert simplify_path('') == '/'
assert simplify_path('/a/./.') == '/a'
assert simplify_path('/home//foo/') == '/home/foo'
assert simplify_path('/a/./b/../../c/') == '/c'
assert simplify_path('/a/../../b/../c//.//') == '/c'
assert simplify_path('/a//b////c/d//././/..') == '/a/b/c'
| true |
5f5faa9ed086ea1741a7ac316ecc196fb6ebe763 | dcragusa/LeetCode | /100-199/120-129/129.py | 1,552 | 4.21875 | 4 | """
You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree
represents a number. For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total
sum of all root-to-leaf numbers. A leaf node is a node with no children.
Example 1:
Input: root = [1, 2, 3], Output: 25
Explanation: 1->2 represents the number 12. 1->3 represents the number 13. sum = 12 + 13 = 25.
1
/ \
2 3
Example 2:
Input: root = [4, 9, 0, 5, 1], Output: 1026
Explanation: 4->9->5 = 495. 4->9->1 = 491. 4->0 represents the number 40. sum = 495 + 491 + 40 = 1026.
4
/ \
9 0
/ \
5 1
"""
"""
A naive solution might be to pass the path taken down until reaching a leaf node, but a better solution is to realise
that since going down a level shifts the number left, it is equivalent to multiplying by 10. Hence we just have to keep
multiplying by 10 as we go down the path, summing to the total when we reach a leaf node.
"""
from shared import list_to_tree
def sum_numbers(root):
total_sum = 0
def helper(node, path_sum):
nonlocal total_sum
if node is None:
return
path_sum += node.val
if not node.left and not node.right:
total_sum += path_sum
return
helper(node.left, path_sum * 10)
helper(node.right, path_sum * 10)
helper(root, 0)
return total_sum
assert sum_numbers(list_to_tree([1, 2, 3])) == 25
assert sum_numbers(list_to_tree([4, 9, 0, 5, 1])) == 1026
| true |
2016b3800a0096045b21c9268298c6ebdd011527 | dcragusa/LeetCode | /1-99/40-49/49.py | 886 | 4.375 | 4 | """
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]]
Note:
All inputs will be in lowercase. The order of your output does not matter.
"""
"""
Firstly we sort each string in the given array - this will allow us to make direct comparisons for anagrams. We then
append each string to a defaultdict with the key being the sorted string. Finally, we return the values of the dict.
"""
from collections import defaultdict
def group_anagrams(strs):
anagrams = defaultdict(list)
for idx, sorted_strs in enumerate(map(lambda x: ''.join(sorted(x)), strs)):
anagrams[sorted_strs].append(strs[idx])
return list(anagrams.values())
assert group_anagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']) == [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
| true |
efdb099231e847d9da3cf288a40ed527b7dd6060 | Gowrishankarvv/Hacktoberfest21-letshack | /C Programs/reverseNo.py | 263 | 4.28125 | 4 | def ReverseNo():
num=int(input("Enter the number to reverse:"))
reversed_num=0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))
ReverseNo()
| false |
881e3c309d3efcbe76537c5bea6454795674d692 | dargen3/matematika-a-programovani | /1-lesson/games_with_number/collatz_sequence.py | 573 | 4.21875 | 4 | def collatz_sequence(n): # return number of steps of collatz sequence for n
count = 0
while n != 1:
if n % 2 == 0:
n = n / 2
else:
n = n * 3 + 1
count += 1
return count
def largest_sequence(max): # print number from interval (2, max) which have highest number of collatz steps
num_of_steps = 0
number = 0
for x in range(2, max):
count = collatz_sequence(x)
if count > num_of_steps:
num_of_steps = count
number = x
print(number)
largest_sequence(10000)
| true |
6c2d06066c0e0fcf57ed491e3638a3d56bb92d07 | Swarnabh3131/sipPython | /sip/sipF05_DFsortcreate.py | 413 | 4.15625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
#https://thispointer.com/pandas-sort-rows-or-columns-in-dataframe-based-on-values-using-dataframe-sort_values/
#df creation
matrix = [(222, 16, 23),(333, 31, 11)(444, 34, 11), ]
matrix
# Create a DataFrame object of 3X3 Matrix
dfObj = pd.DataFrame(matrix, index=list('abc'))
dfObj
dfObj.sort_values(by='b', axis=1)
dfObj.sort_values(by='b', axis=1, ascending=False)
| true |
fd721bc36a9bce2cea562e277cb8ba50a2d155d1 | sewayan/Study_Python | /ex25.py | 1,620 | 4.28125 | 4 | # function will be imported & executed in python
# """ Insert comment text """ -> 'documentation comment'
#if code is run in interpreter, documentation comment = help txt
def break_words(stuff):
"""This func will break up words for us."""
"""put a space between the sperators -> '' """
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off,"""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and the last words of the sentence"""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first & the last one"""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
# below the python-lines
# import ex25
#sentence = "All good things come to those who wait."
#words = ex25.break_words(sentence)
#words
#sorted_words = ex25.sort_words(words)
#sorted_words
#ex25.print_first_word(words)
#ex25.print_last_word(words)
#words
#ex25.print_first_word(sorted_words)
#ex25.print_last_word(sorted_words)
#sorted_words
#sorted_words = ex25.sort_sentence(sentence)
#sorted_words
#ex25.print_first_and_last(sentence)
#ex25.print_first_and_last_sorted(sentence) | true |
b9aa29a971fcda956d7544ff022ba955b1a3a866 | Igr1k001/Programming | /Practice/07/Python/07 PY/07 PY/_07_PY.py | 2,130 | 4.125 | 4 | import math
print('Введите число 1 или 2:')
print('1-ввод параметров треугольника через длины сторон.')
print('2-ввод параметров через координаты вершин или другое целое число по модулю.')
d = float(input())
while d != 1 and d != 2:
print('Ошибочный ввод')
print('Введите число 1 или 2:')
print('1-ввод параметров треугольника через длины сторон.')
print('2-ввод параметров через координаты вершин или другое целое число по модулю.')
d = float(input())
if d == 1:
a = float(input())
while a <= 0:
print('Вы ввели отрицательное число, введите положительное значение числа!')
a = float(input())
b = float(input())
while b <= 0:
print('Вы ввели отрицательное число, введите положительное значение числа!')
b = float(input())
c = float(input())
while c <= 0:
print('Вы ввели отрицательное число, введите положительное значение числа!')
c = float(input())
if a <= 0 or b <= 0 or c <= 0:
print('Некорректные данные, т.к. вы ввели отрицательное число!')
exit(0)
if a + b <= c or a + c <= b or b + c <= a:
print('Некорректные данные, т.к. при этих значениях треугольник не будет существовать.')
exit(0)
p = (a + b + c) / 2
s = math.sqrt(p * (p - a) * (p - b) * (p - c))
print('S =', s)
exit(0)
if d == 2:
x1 , y1 = map(float, input().split())
x2 , y2 = map(float, input().split())
x3 , y3 = map(float, input().split())
s = math.fabs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2
print('S =', s)
exit(0)
| false |
45ddd16506befea1a06a2b46f73abd88461a4a1f | shiv-konar/Python-GUI-Development | /FocusingandDisablingWidgets.py | 1,211 | 4.3125 | 4 | import tkinter as tk
from tkinter import ttk # For creating themed widgets
win = tk.Tk() # Create an instance of the Tk class
win.title("Python GUI") # Set the title of the window
win.resizable(0, 0) # Disable resizing the GUI
aLabel = ttk.Label(win, text='Enter a name:') # Create a named Label instance to be used later
aLabel.grid(column=0, row=0) # Create a Label object and pass the win instance
def clickMe(): # Called when the button is clicked
ttk.Label(text='Hello ' + aTextBox.get()).grid(column=0, row=2)
aButton = ttk.Button(win, text='Click Me!',
command=clickMe) # Creates a button and binds an event handler to handle the click
aButton.configure(state='disabled') # Disables the button
aButton.grid(column=1, row=1)
aTextBox = tk.StringVar() # Create a placeholder to hold the value being entered in the textbox
textEntered = ttk.Entry(win,
textvariable=aTextBox) # Create a textbox and set the variable name which will hold the value
textEntered.focus() # Focuses on the textbox i.e. adds a blinking cursor to add focus
textEntered.grid(column=0, row=1)
win.mainloop() # The event which makes the window appear on screen
| true |
155c1b1e0fc521c3940f254975c58764777bc127 | ankit1997/Computer-Graphics-Programs-in-Python | /dda_line.py | 999 | 4.28125 | 4 | import turtle
print("DDA line drawing algorithm implementation.")
x1 = int(input("Enter x1: "))
y1 = int(input("Enter y1: "))
x2 = int(input("Enter x2: "))
y2 = int(input("Enter y2: "))
window = turtle.Screen()
pointer = turtle.Turtle()
pointer.shape("arrow")
pointer.hideturtle()
pointer.pensize(4)
def setPixel(x, y):
x = round(x)
y = round(y)
print("Plotting : (%s, %s)" % (x, y))
try:
pointer.penup()
pointer.setx(x)
pointer.sety(y)
pointer.pendown()
pointer.goto(x, y)
except:
pass
def dda_line(x1, y1, x2, y2):
dx = x2-x1
dy = y2-y1
x = x1
y = y1
steps = 0
if abs(dx) > abs(dy):
steps = abs(dx)
else:
steps = abs(dy)
xIncr = dx/(float)(steps)
yIncr = dy/(float)(steps)
setPixel(x, y)
for i in range(0, steps):
x += xIncr
y += yIncr
setPixel(x, y)
dda_line(x1, y1, x2, y2)
try:
window.mainloop()
except:
pass
| false |
5d1ffec6bcee9bedbccf214e2bd79c8eab7eb0a0 | Sayalikajale/python | /unions.py | 939 | 4.15625 | 4 | def union1(l1, l2):
l3 = []
for element in l1:
if element not in l3:
print element, 'element'
count = 0
a = l1.count(element)
print a, 'value of a'
b = l2.count(element)
print b, 'value of b'
if a >= b:
count1 = a
else:
count1 = b
print count1, 'count'
while count1 > 0:
l3.append(element)
print l3, 'l3 is'
count1 -= 1
for element in l2:
if element not in l3:
print element, 'element'
count = 0
a = l1.count(element)
print a, 'value of a'
b = l2.count(element)
print b, 'value of b'
if a >= b:
count1 = a
else:
count1 = b
print count1, 'count'
while count1 > 0:
l3.append(element)
print l3, 'l3 is'
count1 -= 1
print l3
def getlist():
l = []
n = input('Enter the number of elements int he list')
for i in range(1, n+1):
a = input('Enter the number')
l.append(a)
return l
l1 = getlist()
l2 = getlist()
union1(l1, l2)
| false |
b315920c07eed5a3baa4c35ce5d583dac0e1ac23 | Chetali-3/python-coding-bootcamp | /session-9/Strings/hello.py | 450 | 4.34375 | 4 | #Types of functions
"""
# finding out length
name = input("Enter your name")
length = len(name)
print(length)
"""
"""
# capitalising
name = input("Enter your name")
new_name = name.capitalize()
print(new_name)
"""
"""
#finding out a letter
name = input("Enter your name")
new_name = name.find(input("enter the word you wanna find"))
print(new_name)
"""
#replacing
name = input("Enter your name")
new_name = name.replace("li", "na")
print (new_name)
| true |
9ea5dee621ccdce9117e4c3cb15b9be5a414c876 | mallikarjuna-sharma/PythonWeb | /MyPy.py | 1,888 | 4.15625 | 4 | import sqlite3
from EmployeeClass import Employee
conn = sqlite3.connect('MyDataBase.db')
cur = conn.cursor()
# cur.execute("""CREATE TABLE employees (
# first text,
# last text,
# pay integer )""")
def insert(emp):
with conn:
cur.execute("INSERT INTO employees VALUES (:first,:last,:pay)",
{'first': emp.fname, 'last': emp.lname, 'pay': emp.pay})
def select(first):
cur.execute("SELECT * FROM employees WHERE first=:first",{'first':first})
return cur.fetchall()
def update(emp,pay):
with conn:
cur.execute("""UPDATE employees SET pay =:pay WHERE first=:first AND last=:last""",{'pay':pay,'first':emp.fname,'last':emp.lname})
def delete(emp):
with conn:
conn.execute("""DELETE from employees WHERE first=:first AND last = :last""",{'first':emp.fname,'last':emp.lname})
emp1 = Employee('Sharma','Mallik','19000')
emp2 = Employee('Sharma','Rajagopal','19000')
#print(emp1.lname)
#insert(emp1)
# insert(emp2)
#
# update(emp2,19000)
#delete(emp2)
#cur.execute("DELETE FROM employees")
# values = select("Sharma")
# print(values)
# cur.execute("INSERT INTO employees VALUES ('Kedar','Eas','10000')")
#
# e1 = Employee("akila","deswari","9000")
# e2 = Employee("kannan","deswari","8000")
# e3 = Employee("kedar","sharma","7000")
#
# #print(e1.fname)
# cur.execute("INSERT INTO employees VALUES (:first,:last,:pay)",{'first':e1.fname,'last':e1.lname,'pay':e1.pay})
# cur.execute("INSERT INTO employees VALUES (:first,:last,:pay)",{'first':e2.fname,'last':e2.lname,'pay':e2.pay})
# cur.execute("INSERT INTO employees VALUES (:first,:last,:pay)",{'first':e3.fname,'last':e3.lname,'pay':e3.pay})
#
#
#
#
#
#cur.execute("DELETE FROM employees WHERE first='Sharma'")
cur.execute("SELECT * FROM employees")
print(cur.fetchall())
# conn.commit()
conn.close() | false |
59bf443228d622dfe3cab82e3d1498ffbfba5dd9 | moses-mugoya/Interview-Practical | /second_largest_number.py | 802 | 4.1875 | 4 | def find_second_largest():
n = input("Enter the value of n: ")
if (int(n) > 10 or int(n) < 2):
print("The value of n should be between 2 and 10")
return
else:
numbers = input("Enter {} numbers separated by a space: ".format(n))
num_list = numbers.split(" ")
num_list = num_list[:int(n)] #slice according to the value of n
largest = num_list[0]
runners_up = num_list[0]
for i in range(len(num_list)):
if num_list[i] > largest:
largest = num_list[i]
for i in range(len(num_list)):
if(num_list[i] > runners_up) and num_list[i] != largest:
runners_up = num_list[i]
return runners_up
runnners_up = find_second_largest()
print("\n")
print(runnners_up) | true |
06be15bbdc3c50376550b8f9b3b049da1e5e5849 | anmol/algorithm_python | /leetcode/arrays/rotate_k_elems.py | 411 | 4.125 | 4 | #!/usr/bin/env python3
# reverse array subset in place
def rev(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
def rotate(nums, k):
k %= len(nums)
rev(nums, 0, len(nums) - 1)
rev(nums, 0, k - 1)
rev(nums, k, len(nums) - 1)
if __name__ == '__main__':
a = [1,2,3,4,5,6,7]
rotate(a, 3)
print(a)
| false |
681c43fe57b36e028dbf4cb231acd076186bd207 | anmol/algorithm_python | /random_problems/counting_mins.py | 1,678 | 4.125 | 4 | """
count mins between the string having a
time interval
"""
def count_mins(s):
# split two times
t1_raw = s.split('-')[0]
t2_raw = s.split('-')[1]
t1_12 = get_time_tuple(t1_raw)
t2_12 = get_time_tuple(t2_raw)
t1 = convert24(t1_12)
t2 = convert24(t2_12)
# if t2[0] >= t1[0] and t2[1] >= t1[1]:
if t2[0] >= t1[0]:
mins = (t2[1] - t1[1])
hr_mins = (t2[0] - t1[0]) * 60
total = mins + hr_mins
# elif t2[0] < t1[0]:
else:
mins = (t2[1] - t1[1])
hr_mins = (24 + t2[0] - t1[0]) * 60
total = mins + hr_mins
return total
def get_time_tuple(t):
period = t[-2:]
hr = t[:-2].split(':')[0]
min = t[:-2].split(':')[1]
return hr, min, period
def convert24(t):
# Checking if last two elements of time
# is AM and first two elements are 12
if t[2] == "am" and t[0] == "12":
return 0, int(t[1])
# remove the am
elif t[2] == "am":
return int(t[0]), int(t[1])
# Checking if last two elements of time
# is PM and first two elements are 12
elif t[2] == "pm" and t[0] == "12":
return int(t[0]), int(t[1])
else:
# add 12 to hours and remove PM
return int(t[0]) + 12, int(t[1])
if __name__ == '__main__':
ti_1 = '9:00am-10:00am'
ti_2 = '1:00pm-11:00am'
ti_3 = '1:12pm-11:06am'
ti_4 = '9:12am-10:06am'
print count_mins(ti_1)
print count_mins(ti_2)
print count_mins(ti_3)
print count_mins(ti_4)
# print convert24(('9', '00', 'pm'))
# print convert24(('9', '00', 'am'))
# print convert24(('12', '00', 'pm'))
# print convert24(('12', '00', 'am'))
| false |
45aa263197f2257470a192294cce88680e8c839d | Aishwarya-11/Python-learnings | /program2.py | 454 | 4.15625 | 4 | def list() :
print ("Creating a list and performing insertion and deletion operations\n ")
print ("Enter the length :")
length = int(input())
print("Enter the values :")
list1 = []
for i in range(length) :
value = input()
list1.append(value)
print (list1)
print ("Enter the value to insert :")
num1 = input()
list1.insert(0,num)
print (list1)
print (list1.pop())
del list1[-1]
print (list1)
list1.insert(3,list1.pop(2))
print (list1)
| true |
be7e215bc2b40ae1920246fdf584fffc8d785ee4 | cleversonmuller/cleversonmuller | /atividade4.py | 1,116 | 4.25 | 4 | #Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
#"Telefonou para a vítima?"
#"Esteve no local do crime?"
#"Mora perto da vítima?"
#"Devia para a vítima?"
#"Já trabalhou com a vítima?"
# O programa deve no final emitir uma classificação sobre a participação
# da pessoa no crime.Se a pessoa responder positivamente a 2 questões ela deve ser classificada como
#"Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino".
# Caso contrário, ele será classificado como "Inocente".
print('indicador de suspeito')
v1= input('Telefonou para a vítima?')
v2= input('Esteve no local do crime?')
v3= input('Mora perto da vítima?')
v4= input('Devia para a vítima?')
v5= input('Já trabalhou com a vítima?')
funcao = input('se as resposta for (2*pessoa no crime) (3* ou 4* cumplice) (5* assasino) ')
resultado = [v1, v2, v3, v4, v5]
if resultado == v1:
print('inocente ')
if resultado == v2:
print('pessoa no crime')
if resultado == v3:
print('cumplice')
if resultado == v4:
print('cumplice')
if resultado == v5:
print ('assasino')
| false |
b8ce9abe820e5e2d1640a4928f51de93ac1b30e1 | patilvikas0205/python-Exercise | /type_casting_hex_octa_bin_to_int.py | 1,104 | 4.4375 | 4 | #type casting in python convert datatypes explicitely
#this program convert binary, octal, hexadecimal object type to int
#octal to int
octal_num=0O17
print("Type of Octal_num before: ",type(octal_num))
ocatl_to_int=int(octal_num)
print("Octal to int: ",ocatl_to_int)
print("Type of Octal_num after: ",type(ocatl_to_int),"\n")
#binary to int
binary_num=0B1010
print("Type of Octal_num before: ",type(binary_num))
binary_to_int=int(binary_num)
print("binary to ineger: ",binary_to_int)
print("Type of binary_num after: ",type(binary_to_int),"\n")
#hex to int
hex_num=0X1C2
print("Type of hex_num before: ",type(hex_num))
hex_to_int=int(hex_num)
print("binary to ineger: ",hex_to_int)
print("Type of binary_num after: ",type(hex_to_int),"\n")
'''
Type of Octal_num before: <class 'int'>
Octal to int: 15
Type of Octal_num after: <class 'int'>
Type of Octal_num before: <class 'int'>
binary to ineger: 10
Type of binary_num after: <class 'int'>
Type of hex_num before: <class 'int'>
binary to ineger: 450
Type of binary_num after: <class 'int'>
'''
| false |
e0d5492aa7d98d9e968aacbdcb6b36d8a057d91b | patilvikas0205/python-Exercise | /Assignment_No_15.py | 568 | 4.4375 | 4 | '''
15. Define a class named Shape and its subclass Square.
The Square class has an init function which takes a length as argument.
Both classes have a area function which can print the area of the shape
where Shape's area is 0 by default.
'''
class Shape:
def area(self):
print("Area Of Shape is: ",0)
class Square(Shape):
def __init__(self,l):
self.length=l
print("Length is: ",self.length)
def area(self):
print("Area of Square is: ",self.length*self.length)
sh=Shape()
sq=Square(5)
sq.area() | true |
6f6ed62f8f510fa72eaaf6120570334ceed1c78c | patilvikas0205/python-Exercise | /Assignment_No_11.py | 853 | 4.28125 | 4 | '''
11. Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output should be:
2 :2
3. :1
3? :1
New :1
Python :5
Read :1
and :1
between :1
choosing :1
or :2
to :1
'''
def summary(text):
count=dict()
words = text.split()
words.sort()
#words.sort(key=str)
for word in words:
if word in count:
count[word]+=1
else:
count[word]=1
return count
text="New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3."
word_fre=summary(text)
#print(word_fre)
for x,y in word_fre.items():
print(x,":",y)
| true |
8fa31985dd13ea2f6607f2ed993ae71238fd254c | cassieeric/Python-Exercises_Interview_questions | /简单算法题/排序算法/选择排序/选择排序.py | 418 | 4.15625 | 4 | # -*- coding: utf-8 -*-
def selection_sort(list):
for i in range(len(list)):
min_index = i
for j in range(i + 1, len(list)):
if list[j] < list[min_index]:
min_index = j
list[i], list[min_index] = list[min_index], list[i]
if __name__ == '__main__':
list = [2, 5, 4, 8, 9, 6, 12, 18]
print(list)
selection_sort(list)
print(list)
| false |
fd174f0aee0488cd3be6a50bd2da5990fe2fa0c8 | tuanphandeveloper/practicepython.org | /divisors.py | 459 | 4.3125 | 4 |
# Create a program that asks the user for a number and then prints out a list of all the divisors
# of that number. (If you don’t know what a divisor is, it is a number that divides evenly into another
# number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
number = int(input("Please enter a number "))
x = range(1, number)
for num in x:
if (number % num) == 0:
print(str(num) + " is a divisor of " + str(number))
| true |
c2497c1c1f430f290d1eee2c230a26abcd6ab338 | tuanphandeveloper/practicepython.org | /listEnds.py | 356 | 4.15625 | 4 |
# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
# and makes a new list of only the first and last elements of the given list. For practice,
# write this code inside a function.
import random
a = [5, 10, 15, 20, 25]
b = random.sample(range(100), 20)
print(b)
c = []
c.append(b[0])
c.append(b[len(b)-1])
print(c) | true |
df951ef9a7474d2b2ad0a29469e4dd68702e8bab | Ananya31-tkm/PROGRAMMING_LAB_PYTHON | /lab_s1/CO1-Q17,Q18.py | 291 | 4.21875 | 4 | dict ={'Swathi':67,'Anu':98,'Riya':66,'Vismaya':88,'Neema':75,'Reshma':89}
import operator
dict1=sorted(dict.items(),key=operator.itemgetter(1),reverse=True)
print("Descending order:",dict1)
dict1=sorted(dict.items(),key=operator.itemgetter(1),reverse=False)
print("Ascending order:",dict1)
| false |
51bcb2204eedf71f3a7cf0c7c5ec7c9612919904 | Genius98/HackerrankContestProblem | /Football Points.py | 356 | 4.28125 | 4 | #Create a program that takes the number of wins, draws and losses and calculates the number of points a football team has obtained so far.
WIN = int(input("Enter win match: "))
DRAWS = int(input("Enter draws match: "))
LOSSES = int(input("Enter losses match: "))
points = WIN * 3 + DRAWS * 1 + LOSSES * 0
print("Final pints is = {0}".format(points)) | true |
f8e095325f58a1aa00b659cf173c623738f51014 | Gautam-MG/SL-lab | /pgm6.py | 581 | 4.5625 | 5 | #Concept: Use of del function to delete attributes of an object and an object itself
class Person:
def __init__(self,name,age):#This is the constructor of the class Person
self.name = name;
self.age = age;
p1 = Person("Suppandi",14)
print("\n Name of Person #1 is",p1.name)
print("\n age of a Person #1 is",p1.age)
print("\n *** Printing after deleting age attribute for p1*** ")
del p1.age # Deleting the age attribute for p1 object
print("\n Name of Person #1 is",p1.name)
print("\n*** Printing after Deleting p1***")
del p1
print("\n Name of Person #1 is",p1.name)
| true |
122ce533b91ca38868f0c31ec49c17162500453d | ProgressBG-Python-Course/ProgressBG-VMware-Python-Code | /lab3/comparison_operators.py | 1,306 | 4.21875 | 4 | """
Notes:
Lexicographical Comparison:
First the first two items are compared, and if they differ this determines the outcome of the comparison.If they are equal, the next two items are compared, and so on, until either sequence is exhausted
Comparison operator Chaining:
https://docs.python.org/3/reference/expressions.html#comparisons
"""
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# example 1
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print('"9" > "10000" = {}'.format("9" > "10000") )
# what Python is doing is like:
# print(ord("9") > ord("1"))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# example 2
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print('"12" > "1000" = {}'.format("12" > "1000"))
# what Python is doing is like:
# print(ord("2") > ord("0")),
# as the first symbols are the same
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# example 3
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print('1<5<10 = {}'.format(1<5<10))
# equivalent to: 1<5 and 5<10
print('1<5>10 = {}'.format(1<5>10))
# equivalent to: 1<5 and 5>10
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# example 4
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# next will throw a TypeError, as Python3
# will not compare "oranges" with "apples"
# Python2 will be ok with that
print('"3" > 2 = {}'.format("3" > 2)) | true |
8443ae90b2b72e1f1a91c6fdc098df29528dd82d | USussman/rambots-a19 | /Classes/driver.py | 2,514 | 4.125 | 4 | #!/usr/bin/env python3
"""
Driver class module
Classes
-------
Driver
interface with wheels for holonomic drive
"""
from .motor import Motor
import math
class Driver:
"""
A class for driving the robot.
Methods
-------
drive(x, y, r)
drive with directional components and rotation.
rDrive(a, v, r)
wrapper on drive for angle, velocity, rotation
spin(r)
wrapper to rotate at given speed
halt()
drive wrapper to stop robot
"""
def __init__(self, *pins):
"""
Creates motor object attributes.
"""
self.motors = tuple(Motor(*pin_set) for pin_set in pins)
def drive(self, x, y, r):
"""
Drive the robot with direction components.
:param x: x velocity
:param y: y velocity
:param r: rotation
"""
mpowers = [0, 0, 0, 0]
x = min(max(x, -100), 100)
y = min(max(y, -100), 100)
mpowers[0] = y + x + r
mpowers[1] = -y + x + r
mpowers[2] = -y - x + r
mpowers[3] = y - x + r
max_power = max(abs(m) for m in mpowers)
if max_power > 0:
scale = 100 / max_power
else:
scale = 0
mpowers = tuple(m * scale for m in mpowers)
for i in range(4):
self.motors[i].run(mpowers[i])
def drive_angle(self, a, v, r=0):
"""
Wrapper for driving in direction at speed.
:param a: angle relative to robot's front, 0-360 degrees
:param v: velocity, 0-100% of full speed
:param r: clockwise rotation, 0-100% of full speed
"""
rad = (a - 90) * math.pi / 180
x = v * math.cos(rad)
y = v * math.sin(rad) * -1
self.drive(int(x), int(y), r)
def spin(self, r):
"""
Spin the robot on spot
:param r: clockwise rotation, 0-100% of full speed
"""
self.drive(0, 0, r)
def halt(self):
"""
Stops all wheels.
"""
self.drive(0, 0, 0)
def drive_angle2(self, a, v, r, offset):
"""
Wrapper for rotating while driving in a straight line
:param a: angle relative to forward direction, 0-360 degrees
:param v: velocity, 0-100% of full speed
:param r: clockwise rotation, 0-100% of full speed
:param offset: offset from forward from compass
"""
self.drive_angle((a + offset) % 360, v, r)
| true |
d3075a86a63b8fa4b649aefaacee1ff999cd6138 | HakujouRyu/School | /Lab 5/nextMeeting.py | 1,084 | 4.3125 | 4 | todaysInt = 8
while todaysInt < 0 or todaysInt > 7:
try:
todaysDay = input("Assuming Sunday = 0, and Saturday = 6, please enter the day of the week: ")
todaysInt = int(todaysDay)
except ValueError:
if todaysDay == "help":
print("Monday 0")
print("Tuesday 1")
print("Wednesday 3")
print("Thursday 4")
print("Friday 5")
print("Saturday 6")
todaysInt = 8
else:
print("Error: Please enter valid day code.")
print("Type 'help' to see day codes.")
todaysInt = 8
daysLeft = int(input("How many more days until your next meeting? "))
meetingDay = ((todaysInt + daysLeft) % 7)
dict = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday"
}
todaysInt = dict[todaysInt]
meetingDay = dict[meetingDay]
print("Today is ", todaysInt, ".", sep='')
print("You have ", daysLeft, " until your next meeting. ", sep= '')
print("Meeting Day is ", meetingDay, ".", sep='')
| true |
34ca930f77410dfda01dddb101f95ef5c9b83719 | bigcat2014/Intro_to_Graduate_Algorithms | /fib.py | 617 | 4.3125 | 4 | #!/usr/bin/python3
# Calculates the nth fibonacci number recursively
# Inputs: n >= 0
# Outputs: The nth fibonacci number
# Running Time O(n^2)
def FIB1(n):
if n == 0: # O(1)
return 0
elif n == 1: # O(1)
return 1
else:
# O(n^2)
return FIB1(n - 1) + FIB1(n - 2) # O((n-1)^2) + O((n-2)^2)
# Calculates the nth fibonacci number using dynamic programming
# Inputs: n >= 0
# Outputs: The nth fibonacci number
# Running Time O(n)
def FIB2(n):
F = [0, 1]
# O(n)
for i in range(2, n + 1): # O(n)
F.append(F[i - 1] + F[i - 2]) # O(1)
return F[n]
| false |
7d0df7467a4dc36f0ec5833cef30002d5935d660 | vthorat1986/python-programs | /Regular_Expressions.py | 1,182 | 4.21875 | 4 | #!/usr/bin/python
import re
# ========== Search & Replace ==============
phoneNum = '8149-13-80-26 # This is a phone number'
num = re.sub(r'#.*$', '', phoneNum)
print('Phone number after commet removal : ', num)
num = re.sub(r'\D', '', phoneNum)
print('Phone number ater removal of all non-digits : ', num)
# ========= Search , Match ============
matchObj = ''
searchObj = ''
def printObject(obj):
if(obj == matchObj):
print('Printing matchObj result : ')
elif(obj == searchObj):
print('Printing searchObj result : ')
else:
print('Invalid object...')
if(obj):
print('obj.group() : ', obj.group())
print('obj.group(1) : ', obj.group(1))
print('obj.group(2) : ', obj.group(2))
else:
print('No string matched!!')
line = 'Cats are smarter than dogs'
matchObj = re.match(r'(.*) are (.*?) .*', line, re.M|re.I)
searchObj = re.search(r'(.*) are (.*?) .*', line, re.M|re.I)
printObject(matchObj)
printObject(searchObj)
matchObj = re.match(r'dogs', line, re.M|re.I)
searchObj = re.search(r'dogs', line, re.M|re.I)
printObject(matchObj)
printObject(searchObj) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.