blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
11e9ffd96d03f93f2fef9a9a06e37d10bdc5ed79 | jorgefpont/CSF021A | /csf021aWork/module10/myFrame.py | 2,352 | 4.40625 | 4 | """
We need to add three things to class MyFrame:
i) a counter that starts at 0, gets incremented every time the user clicks
the incrementButton and whose current value is displayed in the labelForOutput.
ii) code that will be executed when the user clicks the incrementButton.
This is called an event handler or a callback method.
iii) code that will be executed when the user clicks the quitButton.
The following version of class MyFrame contains all three of these things:
"""
import tkinter
class MyFrame(tkinter.Frame):
"""
class MyFrame is the VIEW for a simple program that exemplifies the
Model/View/Controller architecture. This View class is a tkinter.Frame
that contains two Buttons and a Label. One Button increments a counter
and the other Button quits. The Label displays the current value of the counter.
Notice that the View never contains a reference to the Model,
but it does contain a reference to the Controller.
"""
def __init__(self, controller):
"""
Places the controls onto the Frame.
"""
tkinter.Frame.__init__(self)
self.pack()
self.controller = controller
# line above ...
# saves a reference to the controller so that we can call methods
# on the controller object when the user generates events
#set up the increment Button
self.incrementButton = tkinter.Button(self)
self.incrementButton["text"] = "Increment"
self.incrementButton["command"] = self.controller.incButtonPressed
self.incrementButton.pack({"side": "left"})
#set up the decrement Button
self.decrementButton = tkinter.Button(self)
self.decrementButton["text"] = "Decrement"
self.decrementButton["command"] = self.controller.decButtonPressed
self.decrementButton.pack({"side": "left"})
#set up the quit Button
self.quitButton = tkinter.Button(self)
self.quitButton["text"] = "Quit"
self.quitButton["command"] = self.quit
# the statement above attaches the event handler self.quit() to the quitButton
self.quitButton.pack({"side": "left"})
#set up the Label
self.labelForOutput = tkinter.Label(self)
self.labelForOutput["text"] = 0
self.labelForOutput.pack({"side": "left"}) | true |
b3fda9f20557d2b0067f4ce2f2d063c48a08aa57 | jorgefpont/CSF021A | /csf021aWork/module2/2_6_exercise.py | 744 | 4.21875 | 4 | """ Reads a number from the user and prints out the names of each digit
"""
number = int(input ("Please type a number "))
digitNames = ('zero','one','two','three','four','five','six','seven','eight','nine')
result = []
while number >0:
currentDigit = number % 10
# modulus operator gives remainder after integer division
# in this case it is the rightmost digit
result.append( digitNames[currentDigit])
number = number // 10
# integer division throws away the remainder
# my code
result.reverse()
for n in result:
print (n)
'''
Modify the program above so that:
- the names of the digits are printed in the correct order, and
- the names of the digits are printed without the list notation around them.
'''
| true |
55619b6fb48423f82308f92f16fab47e225a2b96 | amisolanki/assignments_python | /assignment2/pro6.py | 539 | 4.40625 | 4 | print("This program is to check whether the given planet is inner or outer...")
Planet_Name=['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Neptune']
print(Planet_Name)
planet=input("Enter planet name:")
if planet!=Planet_Name[0:8]:
print("Please provide acceptable input value...")
else:
if planet in Planet_Name[0:2]:
print("Inner planet is chosen by you")
elif planet==Planet_Name[2]:
print("You are on Earth")
else:
print("It's an outer planet")
| true |
a4a8a63843eb20810f467d581885bc5724275498 | gogomillan/holbertonschool-higher_level_programming | /0x0B-python-input_output/14-pascal_triangle.py | 661 | 4.125 | 4 | #!/usr/bin/python3
"""
Module for the function: pascal_triangle(n)
"""
def pascal_triangle(n):
"""
function that returns a list of lists of integers representing the Pascals
triangle of size n
Args:
n (int): How many lists
Returns:
List of lists with the integer values according to the Pascal Triangle.
"""
tri = list()
if n <= 0:
return tri
tri.append([1])
if n == 1:
return tri
for i in range(1, n):
tri.append(list())
tri[i].append(1)
for j in range(1, i):
tri[i].append(tri[i-1][j-1] + tri[i-1][j])
tri[i].append(1)
return tri
| true |
ecc2e811a9fc7169c5163561d7417838379950a7 | Anderson1201/Anderson-Salazar-Guevara | /impresion_boleta20.py | 718 | 4.125 | 4 | #INPUT
alumno=input("Nombre del alumno: ")
facultad=input("Nombre de facultad: ")
ciclo=str(input("Ingrese ciclo academico: "))
anio=int(input("Ingrese numero del año: "))
nrocursos=int(input("Ingrese numero de cursos: "))
puntaje=float(input("Ingrese numero del puntaje total: "))
#PROCESSING
ponderado=(puntaje)/(nrocursos)
#OUTPUT
print ("#################################")
print ("#### CALCULAR EL PONDERADO ####")
print ("# ALUMNO:", alumno)
print ("# FACULTAD:", facultad)
print ("# CICLO ACADEMICO", ciclo)
print ("# AÑO:", anio)
print ("# NUMERO DE CURSOS:", nrocursos)
print ("# PUNTAJE FINAL:", puntaje)
print ("# PONDERADO:", ponderado)
print ("##################################")
| false |
e34f117a783cb50922fe64993eec48ab2a4e3a4b | jgarrow/cs-module-project-iterative-sorting | /src/iterative_sorting/iterative_sorting.py | 2,835 | 4.34375 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# Your code here
for j in range(cur_index + 1, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
# TO-DO: swap
# Your code here
temp = arr[cur_index]
arr[cur_index] = arr[smallest_index]
arr[smallest_index] = temp
print('arr: ', arr)
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# Your code here
# if there are less than 2 elements, there's nothing to swap
if len(arr) < 2:
return arr
curr_index = 0
swapped = True
while swapped is True:
# reset the index to zero after going through the whole list
curr_index = 0
# will still finish this whole block of code
# if swapped is still False at the end, it will exit this while loop
swapped = False
# check if the curr_index and it's next increment both exist in the list
while curr_index < len(arr) and curr_index + 1 < len(arr):
# if the next element is smaller than the current one, swap them
if arr[curr_index + 1] < arr[curr_index]:
# temporary variable to hold on to what the current next element is
curr_next = arr[curr_index + 1]
# set the next element to our current index's element
arr[curr_index + 1] = arr[curr_index]
# set the current index value to the next element that we held onto
arr[curr_index] = curr_next
swapped = True
# move onto the next pair
curr_index += 1
# print('arr: ', arr)
return arr
'''
STRETCH: implement the Counting Sort function below
Counting sort is a sorting algorithm that works on a set of data where
we specifically know the maximum value that can exist in that set of
data. The idea behind this algorithm then is that we can create "buckets"
from 0 up to the max value. This is most easily done by initializing an
array of 0s whose length is the max value + 1 (why do we need this "+ 1"?).
Each buckets[i] then is responsible for keeping track of how many times
we've seen `i` in the input set of data as we iterate through it.
Once we know exactly how many times each piece of data in the input set
showed up, we can construct a sorted set of the input data from the
buckets.
What is the time and space complexity of the counting sort algorithm?
'''
def counting_sort(arr, maximum=None):
# Your code here
return arr
| true |
8ee1236efc804ede6e84c92fde7cbea25f091b72 | luvitchumber/Capstone | /wrapper/dict_bin_search.py | 737 | 4.25 | 4 | """This module implements a binary search through the method search(). Given a
key, the method will search through a previously sorted list of dictionaries
and return the index of the first matching value.
Author: Luvit Chumber
Date: 2020-03-23
"""
from dict_quad_sorts import insertion_sort
def search(data, key, search_val):
"""Searches through a particular key from a list of dictionaries."""
insertion_sort(data, key)
low = 0
high = len(data) - 1
while low <= high:
mid = (high + low) // 2
mid_dict = data[mid]
if mid_dict[key] == search_val:
return mid
elif search_val < mid_dict[key]:
high = mid - 1
else:
low = mid + 1
return None
| true |
bbe78df72e81f7392acebc10591aa6231b3af88a | Wsmith61/python-hoon | /complete-python-developer-zero-to-mastery/3 Python Basics/17. Numbers.py | 539 | 4.1875 | 4 | # Simple math operations
print('--------- simple math operations ---------')
print(2 + 4)
print(2 - 4)
print(2 * 4)
print(2 / 4)
# Type action
print('--------- type action ---------')
print(type(2 / 4))
# Power of
print('--------- power of ---------')
print(2 ** 6)
# Devide rounded down
# Will cast the result to an int
print('--------- devide rounded down ---------')
print(2 // 4) # returns 0
print(5 // 4) # returns 1
# Modulo
# Calculates the remainder of this division
print('--------- modus ---------')
print(5 % 2) # returns 1
| true |
38d205eb2db3f03a1fbc1709e8927ad533249249 | HarshitShirsat/Python-Problems | /16.py | 264 | 4.125 | 4 | def indexofsmall(l):
small=min(l)
a=l.index(small)
return a
n=int(input("Enter number of elements - "))
l=[]
for i in range(n):
x=int(input("Enter element : "))
l.append(x)
z=indexofsmall(l)
print("Index of smallest element - ",z)
| true |
99e97035e8ac9185e1df99ba6614ba5eb8f2cdbc | ajaymd/ikk | /Recursion/double_power/double_power.py | 506 | 4.1875 | 4 | def pow(base, exp):
absexp = abs(exp)
# recursive function to calculate base ^ positive exponent
def _pow(exp):
if exp == 0:
return 1
elif exp == 1:
return base
if exp % 2 == 0:
temp = _pow(exp / 2)
return temp * temp
else:
temp = _pow((exp - 1) / 2)
return temp * base * base
result = _pow(absexp)
if exp < 0:
return 1.0 / result
return result
print pow(2, -3)
| false |
265d6c97d38973a3b1c4332667baa768548ad7c3 | bosea/tensorflow_learning | /basics/regression.py | 1,521 | 4.125 | 4 | """
Example of solving a basic linear regression problem
"""
import numpy as np
import tensorflow as tf
__author__ = 'Abhijit Bose'
__email__ = 'boseae@gmail.com'
__version__ = '1.0.0'
__status__ = 'Research'
# generate input points (npoints) and define the linear equation.
npoints = 100
a = tf.constant(0.5)
b = tf.constant(0.8)
# Note: The value of a feed_dict cannot be a tf.Tensor object. So if
# we create x points as a tf.random_normal as in:
# xp = tf.random_normal([npoints], mean=0.0, stddev=0.5)
# we will not be able to feed it later in the graph.
# Acceptable feed values include Python scalars, strings, lists, or
# numpy ndarrays. Therefore, we will define x points as np arrays.
xp = np.random.normal(loc=0.0, scale=0.5, size=npoints)
yp = a * xp + b
# define cost function and parameters to calculate
a1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b1 = tf.Variable(tf.zeros([1]))
xs = tf.placeholder(tf.float32, shape=(npoints))
ys = a1 * xs + b1
cost = tf.reduce_mean(tf.square(yp - ys))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(cost)
init = tf.initialize_all_variables()
# execute the graph in a session and perform niter gradient descent
# iterations
niter = 25
with tf.Session() as sess:
sess.run(init)
for step in range(0, niter):
[stepCost, _] = sess.run([cost, train], feed_dict={xs:xp})
if (step % 5 == 0):
print('step = ', step)
print(' cost = ', stepCost)
print(' a1 = ', sess.run(a1))
print(' b1 = ', sess.run(b1))
| true |
5d8ed55ccaf5efa47e72ca2af61ca99cf888f61a | suhasgumma/State-Space-Search-With-and-Without-Heuristics | /EightPuzzle_heuristic_manhattanDistance1.py | 2,157 | 4.25 | 4 | import math
#Priority Queue using Heaps
class PriorityQueue():
def __init__(self):
self.data = []
def swap(self, present, parent):
temp = self.data[present]
self.data[present] = self.data[parent]
self.data[parent] = temp
def isEmpty(self):
return len(self.data) == 0
def enqueue(self, path, manhattanDistance):
self.data.append({"path": path, "manhattanDistance": manhattanDistance})
self.bubbleUp()
def dequeue(self):
self.swap(0, len(self.data)-1)
popped = self.data.pop()
self.sinkDown()
return popped
def bubbleUp(self):
present = (len(self.data))-1
parent = math.floor((present-1)/2)
if(parent < 0):
return
while self.data[parent]["manhattanDistance"] > self.data[present]["manhattanDistance"]:
self.swap(present, parent)
present = parent
parent = math.floor((present-1)/2)
if parent < 0:
break
def sinkDown(self):
minimum = 0
present = 0
if len(self.data) < 2:
return
if len(self.data) == 2:
if self.data[0]["manhattanDistance"] > self.data[1]["manhattanDistance"]:
self.swap(0,1)
return
left = (2 * present) + 1
right = (2 * present) + 2
while self.data[present]["manhattanDistance"] > self.data[left]["manhattanDistance"] or self.data[present]["manhattanDistance"] > self.data[right]["manhattanDistance"]:
if self.data[left]["manhattanDistance"] == min(self.data[left]["manhattanDistance"], self.data[right]["manhattanDistance"]):
minimum = left
else:
minimum = right
self.swap(present, minimum)
present = minimum
left = (2 * present) + 1
right = (2 * present) + 2
if left >= len(self.data):
return
if right >= len(self.data):
if self.data[present]["manhattanDistance"] > self.data[left]["manhattanDistance"]:
self.swap(present, left)
return
# Pqueue = PriorityQueue()
# Pqueue.enqueue(23,11)
# Pqueue.enqueue(12,12)
# Pqueue.enqueue(2,4)
# Pqueue.enqueue(24,6)
# print(Pqueue.data)
# print(Pqueue.dequeue())
# print(Pqueue.dequeue())
# print(Pqueue.dequeue())
# print(Pqueue.dequeue())
| false |
9e56b0c1d086192730b26a6d9c0610fbe8015e1d | timhuttonco/tip-calculator | /main.py | 699 | 4.28125 | 4 | print("Welcome to the tip calculator")
# Start with bill total
bill_total = float(input("What was the total bill? £"))
# Get tip total
percent_tip = int(input("What percentage tip would you like to give?"))
# Number of people splitting
people = int(input("How many people to split the bill?"))
# Add tip amount (percent number divided by 100 and multiplied by the bill total) to the bill total
final_total = percent_tip / 100 * bill_total + bill_total
# Divide the total of the bill by number of people
bill_per_person = final_total / people
# Format string to two decimal places
final_amount = "{:.2f}".format(bill_per_person)
# Print final amount
print(f"Each person should pay £{final_amount}") | true |
b77c5af4ec738fc67ada39e8c877b90039dfb6c7 | manoharthakur-oss/just_for_u | /Python/Socket/server.py | 1,571 | 4.21875 | 4 | # coding the server
import socket
'''
socket function of socket module is used to create
sockets it takes 2 parameters
1 type of socket:
IPv4
IPv6
2. type of Network:
TCP
UDP
by default these parameters are set to IPv4 and TCP.
'''
s = socket.socket()
print('socket created')
# bind the socket with a IP address and port number
## remember bind() takes tuple as an argument
port=input('choose a Port number : ')
if port == '':
port_number = 9999
else:
port_number = int(port)
s.bind(('localhost',port_number))
print('local host bound with port : '+str(port_number))
'''
port number range (0 to 65535)
is usually all the port number in 1000s are busy..
'''
number_of_clients=3
# waiting for clients to request
s.listen(1)
print('waiting for the clients')
counter = 0
while True:
counter += 1
'''
accept() function accepts request by the client
and return 2 things
1. connection
2. address of client
'''
c, address= s.accept()
# recieving Data from client
client_s_name = c.recv(1024).decode()
print(str(counter)+'. connected to '+str(address),client_s_name)
# send()bfunction to send message to clients:
# bytes() function convert string to bytes form.
# we can only send message in byte form.
# and we also have to mention the format i.e. (utf-8) format
c.send(bytes('welcome to server '+client_s_name,'utf-8'))
print(' welcome message sent to the ',client_s_name)
# finally it is important
# to close socket after all stuff
# using close() function.
c.close()
# Port number of client will be generated automatically.
| true |
3cb1bd04e2236c30ecb8e8b6b71fd4f3a2fc2fef | Nathalia1234/Python | /Python_38_class_list_II/class_list_II.py | 474 | 4.125 | 4 | lista = [1,2,3,4]
print(lista)
lista = lista + [5, 6]
print(lista)
lista = [0] + lista
print(lista)
lista.append(11) #acrescenta um elemento a lista
print(lista)
lista.append([12]) #acrescenta um sub-lista dentro da minha lista
print(lista)
lista = ['a', 3]
print(lista)
ls = [['a', 'b', 'c'], [5,8,2], []]
print(ls)
print(ls[0])
print(ls [1])
print(ls [2])
print(ls[0][0])
print(ls[0][1])
print(ls[0][2])
lista = [1,2,3,]
print(lista)
lista += 10*[0]
print(lista) | false |
4193487dcb0b2a7116b3d4303e71de41b08977ed | Nathalia1234/Python | /Python_41_incluindo_alterando_excluindo/incluindo_alterando_excluindo_elementos.py | 668 | 4.125 | 4 | lista = ['aaa', 'bbb', 'ccc', 'ddd', 'eee',]
print(lista[0])
lista.append('fff')
print(lista)
#inseri elementos na listas informando seu index
lista.insert(1, 'aa')
print(lista)
print(lista[2])
#exclui todos os elementos da lista
lista.clear()
print(lista)
lista = ['aaa', 'bbb', 'ccc', 'ddd', 'eee',]
print(lista)
#exclui os elementos selecionados da lista
lista.pop()
print(lista)
lista.pop()
print(lista)
lista.pop(0)
print(lista)
lista = ['aaa', 'bbb', 'ccc', 'ddd', 'eee',]
#deletando elementos da lista por index
del(lista[2:4])
print(lista)
lista = ['aaa', 'bbb', 'ccc', 'ddd', 'eee',]
#deletando elementos de dois em dois
del(lista[::2])
print(lista)
| false |
a0b119496c5f4da4502d67a7c0e716a1b3ba2129 | Nathalia1234/Python | /Python_45_ordenadores_in_not_in/ordenadores_in_not_in.py | 350 | 4.125 | 4 | print("====in - not in=====")
#verificando condições
print(2 in (1,2,3,4,5))
print()
print(6 not in (1,2,3,4,5))
print()
print(6 in (1,2,3,4,5))
print()
print(1 in range(1,6)) #verificando com range
print()
print(1 in range(2,6))
print()
print(list(range(1,9)))
print()
x = range(1,6)
if 3 in x:
print("Contido")
else:
print("Não contido") | false |
1906916574a659f1a75f1b716a6cd4addb41336b | Casady-ComSci/fam-assignment-mylesandersson | /arith.py | 535 | 4.3125 | 4 | # Write the python code to print 2*3
x=2
y=3
print(x*y)
# Write the python code to assign the integer 3 to x, the string "yes" to y, and
# the integer 5 to z.
x=3
y=yes
z=5
# Write the python code to print the type of y.
type(y)
# Write the python code to assign x+z to sum, and then print the sum.
sum=(x+z)
print(x+z)
# Store 2.5 in the variable x, 3.7 in the variable y, and their product in the
# variable z. Now try to divide by zero and store in the variable a.
>>> x=2.5
>>> y=3.7
>>> z=(x+y)
>>> print(z)
>>> a=(z/0)
| true |
39dd4c872c3cb62d9a6b096368c0b48c618dbc6e | jestemrodeo/Info2020 | /Listas, Tuplas y Diccionarios/Desafios_Grupo5/g5_challenges.py | 913 | 4.3125 | 4 | '''
Ejercicio 1:
Escribir un programa que pregunte por una muestra de números,
separados por comas, los guarde en una lista y muestre por pantalla
su promedio y desviación estándar.
'''
lista = input()
print(lista)
lista2 = list(lista.split(","))
suma=0
lista2 = [int(i) for i in lista2]
for num in lista2:
suma+=int(num)
print(f"El promedio es: {suma/len(lista2)}")
'''
Ejercicio 2:
Escriba un programa que permita crear una lista de palabras y que,
a continuación, elimine los elementos repetidos (dejando únicamente el primero de los
elementos repetidos).
'''
# Coloque la resolución del Ejercicio debajo de esta línea
c = int(input("Cuantas palabras quiere ingresar? :"))
lista = []
for i in range(c):
p = input("Ingrese palabra: ")
lista.append(p)
lista.reverse()
for i in lista:
for j in range(lista.count(i)-1):
lista.remove(i)
lista.reverse()
print(lista)
| false |
967f59b9cad759ff4631e71233c2fab8b11cba43 | alanaalfeche/python-sandbox | /facebook/leetcode/algorithms/269.py | 1,107 | 4.15625 | 4 | """269. Alien Dictionary
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings words from the alien language's dictionary, where the strings in words are sorted lexicographically by the rules of this new language.
Return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules.
If there is no solution, return "".
If there are multiple solutions, return any of them.
A string s is lexicographically smaller than a string t if at the first letter where they differ, the letter in s comes before the letter in t in the alien language. If the first min(s.length, t.length) letters are the same, then s is smaller if and only if s.length < t.length.
Example 1:
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Example 2:
Input: words = ["z","x"]
Output: "zx"
Example 3:
Input: words = ["z","x","z"]
Output: ""
Explanation: The order is invalid, so return "".
"""
def alienOrder(self, words: List[str]) -> str:
pass | true |
9d710387a075fff49c4a28359c27e67aa029ef6b | alexandre146/avaliar | /media/codigos/39/39sol46.py | 254 | 4.125 | 4 | numero1 = float(input())
numero2 = float(input())
numero3 = float(input())
media = (numero1 + numero2 + numero3) / 3
if media >= 7:
print("aprovado")
elif media < 3:
print("reprovado")
elif (3 <= media < 7) :
print("prova final") | false |
084ef8c16ea0302c800b4bf51d2e685fd7cf8512 | anica87/Python-Project | /GameGuessMyNumber/MultipleFunctionArguments.py | 1,761 | 4.34375 | 4 | '''
Created on Dec 22, 2014
@author: anicam
'''
def foo (first, second, third, *therset):
print "First: %s" % first
print "Second: %s" % second
print "Third: % s" % third
print "And all the rest ... %s" % list(therset)
''' The "therset" variable is a list of variables, which receives all arguments which were to the "foo" function after the first 3 arguments.
'''
foo(1, 2, 3, 4, 5)
''' It is also possible to send functions arguments by keyword, so that the order of the argument does not matter, using the following syntax:
'''
def bar(first, second, third, **options):
if options.get("action") == "sum":
print "The sum is: %d" % (first + second + third)
if options.get("number") == "first":
return first
if options.get("number") == "second":
return 100
result = bar(1, 2, 3, action = "sum", number = "second")
print "Result: %d" %result
''' Fill in the foo and bar functions so they can receive a variable amount of arguments(3 or more). The foo function must return the amount of
extra arguments received. The bar function must return true if the argument with the keyword magic number is worth 7 and False otherwise
'''
def foo_example(a, b, c, *args):
return len(args)
def bar_example(a, b, c, **magic_number):
if magic_number.get("argument") == 7:
return True
# return False
else:
False
''' Za ovo sam glupa, proveriti '''
if foo_example(1,2,3,4) == 1:
print "Good"
if foo_example(1,2,3,4, 5) == 2:
print "Better"
if bar_example(1,2,3, argument = 7) == True:
print "Great"
if bar_example(1,2,3,argument = 256) == False:
print "Awesome"
if bar_example(1,2,3, argument = "string") == False:
print "Awesome"
| true |
d126c48f07ae3cb0160abb619d13894c9efbeb15 | whitej9406/cti110 | /P2HW2_MaleFemale_Percentage_JacobWhite.py | 645 | 4.375 | 4 | # Find percentage of males and females in a class
# 9/22/2018
# CTI-110 P2HW2 - Male Female Percentage
# Jacob White
# Pseudocode - Input number of males and females, calculate percentage of males and females, display percentage.
males = float( input( 'Enter number of males in the class: '))
females = float( input( 'Enter number of females in the class: '))
totalStudents = males + females
malePercentage = ( males / totalStudents ) * 100
femalePercentage = ( females / totalStudents ) * 100
print( 'The male percentage is: ' + format( malePercentage ) + '%')
print( 'The female percentage is: ' + format( femalePercentage ) + '%')
| true |
8a1942cda8a15280f8911823ae0af4cc424a28b7 | RajnishAdhikari/Pythonfiles | /8tuples_in_python.py | 419 | 4.21875 | 4 | #list and tuples are exactly same but in one condition
#in list we can add values but in tuple we cannot
#list is mutable but tuples are immutable
#tuples are always in parenthesis or small bracket()
#note that there is no single value tuple if needed
#then we need to add comma ,
t = (35,56,43.3, True)
print(type(t))
print(t[0])
print(t[0:3])
# using loop and printing one by one
for i in t:
print(i) | true |
3ddf6bfa2259a69130225bc2872d72f19171d82a | msomi22/jenkinsdemo | /docs/ml/brain/sum.py | 1,092 | 4.1875 | 4 | # Import the Linear Regression module from sklearn
from sklearn.linear_model import LinearRegression
import numpy as np
# Need a training dataset, the model will learn how to add numbers from these data
# We only need 3 training examples:
# 2+3=5 # 1+5=6 # 6+5=11
X = [[2,3],[1,5],[5,6]]
Y = [5,6,11]
# Fit the linear regression model with the training data
model = LinearRegression()
model.fit(X,Y)
# Done! Now we can use predict to sum two numbers
# Sum 6 and 6
print "6 + 6 = %d" %model.predict([[6,6]]) # array.reshape(6, 6)
# Sum 25 and 50
print "25 + 50 = %d" %model.predict([[25,50]])
print "1 + 50 = %d" %model.predict([[1,50]])
print "600 + 50 = %d" %model.predict([[600,50]])
print "333 + 111 = %d" %model.predict([[333,111]])
print "502 + 8 = %d" %model.predict([[502,8]])
print "600 + 400 = %d" %model.predict([[600,400]])
print "1500 + 27 = %d" %model.predict([[1500,27]])
# Use this to get rid of Warnings at execution
#print "6 + 6 = %d" %model.predict(np.array([6,6]).reshape(1,-1))
#print "25 + 50 = %d" %model.predict(np.array([25,50]).reshape(1,-1)) | true |
b516df2207535b96601d971e9bd2dac425f68c3b | MrRuban/lectures_devops2 | /Python/samples3/modules/copy_time_random/4.1.3.py | 419 | 4.125 | 4 | #!/usr/bin/env python3
"""
Текущее время
"""
import time
from datetime import date
today = date.today()
print(today)
print(date(2007, 12, 5))
print(today == date.fromtimestamp(time.time()))
my_birthday = date(today.year, 6, 24)
if my_birthday < today:
my_birthday = my_birthday.replace(year=today.year + 1)
print(my_birthday)
time_to_birthday = abs(my_birthday - today)
print(time_to_birthday.days)
| false |
dba6d8e345ab8651070ebf4c1bf47f4037689b16 | MrRuban/lectures_devops2 | /Python/samples3/modules/sqlite3/4.7.py | 783 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Файловая база данных sqlite3
"""
import sqlite3
conn = sqlite3.connect("example.sqlite3")
c = conn.cursor()
# Create table
c.execute("""create table stocks
(date text, trans text, symbol text, qty real, price real)""")
# Insert a row of data
c.execute("""insert into stocks
values ("2006-01-05","BUY","RHAT",100,35.14)""")
# Save (commit) the changes
conn.commit()
for t in [
("2006-03-28", "BUY", "IBM", 1000, 45.00),
("2006-04-05", "BUY", "MSOFT", 1000, 72.00),
("2006-04-06", "SELL", "IBM", 500, 53.00),
]:
c.execute("insert into stocks values (?,?,?,?,?)", t)
c.execute("select * from stocks order by price")
for row in c:
print(row)
# We can also close the cursor if we are done with it
c.close()
| true |
cdb7590eb33962fe4ffdecb764658fe0d3c72db6 | donghankim/Algorithms-with-Python | /Recursion/reverse_string.py | 312 | 4.34375 | 4 | # reverse a given string using recursion
def reverse_string(string: str) -> str:
if len(string) == 0:
return ""
else:
return string[-1] + reverse_string(string[:-1])
# test cases
print(reverse_string("abc"))
print(reverse_string("nun"))
print(reverse_string("hello"))
| true |
b62bec565d856394f5422478bdadb0aeda8ca290 | kesslerej/Iteration | /iteration.py | 1,759 | 4.15625 | 4 | # iteration pattern
# doing the same thing once for each member of a list
# [1, 5, 7 ,8 , 4, 3]
# Make a change
# Make a new change
def print_list(list):
# standard for loop with range
# for i in range(0, len(list)):
# print list[i]
# for each loop
for item in list:
print item
def add_one(list):
# standard for loop with range
for i in range(0, len(list)):
list[i] += 1
return list
def print_scores(names, scores):
for i in range(0, len(names)):
print names[i] , " scored " , scores[i]
# filter pattern - a type of iteration
# exclude a calculation from list members
def congratulations(names, scores):
for i in range(0, len(names)):
if (scores[i] == 100):
print "Congrats", names[i], "! You got a perfect score!"
# accumulation pattern - a type of iteration
# keep track of other data as we go
def sum(numbers):
total = 0
for n in numbers:
total += n
return total
def max(numbers):
current_max = numbers[0]
for n in numbers:
if n > current_max:
current_max = n
return current_max
# homework ->
# a) write a function that finds the average of the scores
# b) write a second function that also finds the average,
# but drops the lowest 2 scores
def average(scores):
print (float(sum(scores)) / len(scores))
def drop(scores):
current_min = scores[0]
for s in scores:
if s < current_min:
current_min = s
current_min2 = scores[2]
for s in scores:
if s < current_min2 and not current_min:
current_min2 = s
return (float(sum(scores)-current_min-current_min2) / (len(scores) - 2))
def fizz_buzz(numbers):
for n in numbers:
if n % 3 == 0 and n % 5 == 0:
n = 'FizzBuzz'
elif n % 3 == 0:
n = 'Fizz'
elif n % 5 == 0:
n = 'Buzz'
else:
n = 'Bazz'
return numbers
| true |
fe103d0823ef1f6bde607d193300903d1c448ec8 | Echowwlwz123/learn7 | /Python脚本编写与实战作业/hero.py | 1,338 | 4.21875 | 4 | """
使用简单工厂方法, 实现timo 和 police 两个英雄
一个回合制游戏,有两个英雄,分别以两个类进行定义。分别是timo和police。每个英雄都有 hp 属性和 power属性,hp 代表血量,power 代表攻击力
每个英雄都有一个 fight 方法:
my_hp = hp - enemy_power
enemy_final_hp = enemy_hp - my_power
两个 hp 进行对比,血量剩余多的人获胜
每个英雄都一个speak_lines方法
调用speak_lines方法,不同的角色会打印(讲出)不同的台词
timo : 提莫队长正在待命
police: 见识一下法律的子弹
"""
class Hero:
hp = 0
power = 0
name = ""
def fight(self, enemy_hp, enemy_power):
"""
:param enemy_hp: 敌人的血量
:param enemy_power: 敌人的攻击力
:return:
"""
my_final_hp = self.hp - enemy_power
enemy_final_hp = enemy_hp - self.power
if my_final_hp > enemy_final_hp:
print(f"{self.name}的剩余血量是{my_final_hp},{self.name}赢了")
elif my_final_hp < enemy_final_hp:
print(f"{self.name}的剩余血量是{my_final_hp},敌人赢了")
else:
print(f"{self.name}的剩余血量是{my_final_hp},双方打平手")
def speak_lines(self, words):
print(f"{self.name}:{words}")
| false |
97544039a86e5cfc22c0ba04706eb357da01d660 | Echowwlwz123/learn7 | /python_practice/create_class.py | 843 | 4.21875 | 4 | """
创建一个人类
"""
class person:
name = 'default'
age = 12
gender = 'male'
weight = 0
def __init__(self, name, age, gender, weight):
self.name = name
self.age = age
self.gender = gender
self.weight = weight
print("init section")
def eat(self):
print(f"{self.name} eating")
def jump(self):
print(f"{self.name} jumping")
def sleep(self):
print(f"{self.name} sleeping")
zs = person('zhangsan', 20, 'female', 120)
print(f"zhangsan 的名字是:{zs.name},zhangsan 的年龄是{zs.age},zhangsna 的性别是{zs.gender},zhangsand的体重是{zs.weight}")
zs.eat();
ls = person('lisi', 25, 'male', 110)
print(f"lisi 的名字是:{zs.name},lisi 的年龄是{zs.age},lisi 的性别是{zs.gender},lisi 的体重是{zs.weight}")
ls.jump()
| false |
fdd54247e862cdf8f72bda4240664e74219f4cf4 | Awright919/Data-Programming-1 | /Assignment_4/Assign4_2.py | 731 | 4.15625 | 4 | try:
def calc_bmi(height, weight):
bmi = (weight / height ** 2) * 703
return bmi
def getCategory(bmi):
if bmi >= 30:
print("obese")
elif 25 <= bmi < 30:
print("overweight")
elif 18.5 <= bmi < 25:
print("normal")
else:
print("underweight")
def main():
height, weight = [float(x) for x in input("Enter your height and weight? ").split()]
bmi = calc_bmi(height, weight)
print("BMI: {}".format(bmi))
getCategory(bmi)
if __name__ == "__main__":
main()
except ValueError:
print("This program only takes numeric input. Program terminated")
| true |
bcf33a05400861006563638dca8409fbe598e865 | Ugtan/Project-Euler | /PycharmProjects/PROJECTEULER/1st.py | 722 | 4.3125 | 4 | """PROJECT EULER
FIRST PROBLEM
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multipl
es is 23.
Find the sum of all the multiples of 3 or 5 below 1000"""
def sum_multiple(): # A Function sum multiple to check if the multiples of 3 or 5 from from 1 to 1000 and
summ = 0 # find sum of multiple
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0: # To check for multiples of three and five
summ = summ + i
return summ
def main():
print(sum_multiple()) # To print the sum of all the multiples of 3 or 5 from 1 to 1000
if __name__ == '__main__':
main()
| true |
42fde8fea9d4073226f40af828e6477c4cf5baa1 | stuycs-softdev/classcode | /7/regex/regtest.py | 652 | 4.1875 | 4 | import re
def find_phone(s):
"""Return a list of valid phone numbers given a string of text
Arguments:
s: A string of text
Returns:
An empty list or a list of strings each one being a phone number
>>> find_phone("")
[]
>>> find_phone("111-111-1111")
['111-111-1111']
>>> find_phone("stuff 222-222-2222 stuff")
['222-222-2222']
>>> find_phone("111-111-1111 and 222-222-22252")
['111-111-1111', '222-222-2225']
"""
pattern = "[0-9]{3}-[0-9]{3}-[0-9]{4}"
result = re.findall(pattern,s)
return result
if __name__=="__main__":
import doctest
doctest.testmod()
| true |
69837e71cbaa2977cded2e3f416572939d3cc7c5 | arnabs542/interview-notes | /notes/algo-ds-practice/problems/array/circular_tour_petrol.py | 1,747 | 4.34375 | 4 | """
Suppose there is a circle. There are N petrol pumps on that circle.
You will be given two sets of data.
1. The amount of petrol that every petrol pump has.
2. Distance from that petrol pump to the next petrol pump.
Return the index of the first petrol pump which can be the starting point of the tour such that truck can cover all the pumps.
Note : Assume for 1 litre petrol, the truck can go 1 unit of distance.
For example, let there be 4 petrol pumps with amount of petrol and distance to next petrol pump value pairs as
{4, 6}, {6, 5}, {7, 3} and {4, 5}.
The first point from where the truck can make a circular tour is 2nd petrol pump.
Output should be “start = 1” (index of 2nd petrol pump).
"""
def circular_tour_petrol(petrols, distances):
# CAREFUL: Tricky implementation!
# Just remember this by heart!
start = 0
end = 1
size = len(petrols)
current_petrol = petrols[start] - distances[start]
if size == 1:
if current_petrol >= 0:
return 0
else:
return -1
while start != end:
if current_petrol < 0:
# Just bring the start to end and current petrol to 0.
# Note that we are doing this directly as it cannot happen that
# new start will come somewhere before old_start and end.
# If we reach a point where current_petrol is negative, that means
# no index between start and end can be the new start ever.
current_petrol = 0
if end > start:
start = end
else:
return -1
current_petrol += petrols[end] - distances[end]
end = (end + 1) % size
if current_petrol < 0:
return -1
return start
| true |
50e48ce54f44c5cbb6a45dd3fbca1221cf634ff7 | arnabs542/interview-notes | /notes/algo-ds-practice/problems/greedy/interval_scheduling.py | 1,198 | 4.125 | 4 | # Verified on https://www.spoj.com/problems/BUSYMAN/
'''
Given a list of activities `(st, et)`, where `st` and `et` are the start time and end time of an activity, return the maximum number of activities that can happen.
OR
We have just a single lecture hall. Among all the classes, make a schedule such that max number of classes can happen.
Also called as the `Activity selection`.
Example:
events = [(1, 2), (3, 4), (0, 6), (5, 7), (8, 9), (5, 9)]
Answer = 4 (Activities 0, 1, 3, 4)
'''
def interval_scheduling(activities):
'''
Sort the events by their end times.
Then starting from the beginning, keep including the events whose
start time >= end time of last included event.
'''
activities = sorted(activities, key=lambda event: (event[1], event[0]))
previous_end_time = 0
result = []
for activity in activities:
start_time = activity[0]
if start_time >= previous_end_time:
result.append(activity)
previous_end_time = activity[1]
return result
def main():
activities = [(1, 2), (3, 4), (0, 6), (5, 7), (8, 9), (5, 9)]
print(interval_scheduling(activities))
if __name__ == "__main__":
main()
| true |
0b9afdf02637868ef11f107944c4e16a413de0ff | arnabs542/interview-notes | /notes/algo-ds-practice/problems/dp/rod_cut/max_rod_cut_product.py | 934 | 4.1875 | 4 | """
Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts.
You must make at least one cut. Assume that the length of rope is more than 2 meters.
Examples:
Input: n = 2
Output: 1 (Maximum obtainable product is 1*1)
Input: n = 3
Output: 2 (Maximum obtainable product is 1*2)
Input: n = 4
Output: 4 (Maximum obtainable product is 2*2)
Input: n = 5
Output: 6 (Maximum obtainable product is 2*3)
Input: n = 10
Output: 36 (Maximum obtainable product is 3*3*4)
"""
from functools import lru_cache
@lru_cache(maxsize=None)
def max_rod_product(size):
'''
O(n*n)
'''
if size < 2:
return 0
ans = 0
for i in range(1, size):
# CAREFUL: Tricky!
ans = max(ans, i * (size - i), i * max_rod_product(size - i))
return ans
def main():
size = 10
ans = max_rod_product(size)
print(ans)
main()
| true |
0fe98e8feba337852644c97f313efb904b9b51a9 | arnabs542/interview-notes | /notes/algo-ds-practice/problems/list/reverse_linked_list.py | 1,266 | 4.40625 | 4 | from ds.linked_list.linked_list import LinkedList
def reverse_list_recurse(head):
if head is None or head.next is None:
return head
reverse_head = reverse_list_recurse(head.next)
# head.next will now be pointing to null since its the tail of the reverse now.
head.next.next = head
# Making this node as the tail now.
head.next = None
return reverse_head
def reverse_list_iterative(ll):
prev = None
current = ll.head
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
ll.head = prev
def reverse_doubly_ll(ll):
current = ll.head
original_head = ll.head
head = None
while current is not None:
head = current
next = current.next
previous = current.prev
current.next = previous
current.prev = next
current = next
ll.head = head
ll.tail = original_head
def main():
ll = LinkedList()
ll.insert_at_tail(2)
ll.insert_at_tail(3)
ll.insert_at_tail(4)
ll.insert_at_head(1)
ll.insert_at_head(0)
print(ll)
# reverse_list(ll)
# reverse_list_iterative(ll)
reverse_doubly_ll(ll)
print(ll)
if __name__ == "__main__":
main()
| true |
5b2387ae0f362957b2085a3cec0f530a1968f4f5 | arnabs542/interview-notes | /notes/algo-ds-practice/problems/array/arr_frequency_inplace.py | 2,276 | 4.15625 | 4 | """
Given an unsorted array of n integers which can contain integers from 1 to n.
Some elements can be repeated multiple times and some other elements can be absent from the array.
Count frequency of all elements that are present and print the missing elements.
Examples:
Input: arr[] = {2, 3, 3, 2, 5}
Output: Below are frequencies of all elements
1 -> 0
2 -> 2
3 -> 2
4 -> 0
5 -> 1
Input: arr[] = {4, 4, 4, 4}
Output: Below are frequencies of all elements
1 -> 0
2 -> 0
3 -> 0
4 -> 4
SOLUTION 1:
The idea is to traverse the given array, use elements as index and store their counts at the index.
For example, when we see element 7, we go to index 6 and store the count.
There are few problems to handle, one is the counts can get mixed with the elements; this is handled by storing the counts as negative.
Other problem is loosing the element which is replaced by count, this is handled by first storing the element to be replaced at current index.
SOLUTION 2:
First decrement every arr[i] by 1 to bring the element range from [0, n-1] from [1, n]
Use every element arr[i] as index and add 'n' to element present at arr[i]%n to keep track of count of occurrences of arr[i]
for (int i=0; i < n; i++):
arr[arr[i]%n] = arr[arr[i]%n] + n;
This way we are able to keep both the things; the frequency of i as well as the original arr[i] for every i.
"""
def solution1(arr):
for i in range(0, len(arr)):
arr[i] -= 1
print(arr)
i = 0
while i < len(arr):
idx = arr[i]
if idx < 0:
pass
elif arr[idx] < 0:
arr[idx] -= 1
arr[i] = 0
else:
arr[i] = arr[idx]
arr[idx] = -1
i -= 1
i += 1
for i in range(0, len(arr)):
arr[i] = -arr[i]
print(f'{i+1} -> {arr[i]}')
def solution2(arr):
for i in range(0, len(arr)):
arr[i] -= 1
for i in range(0, len(arr)):
idx = arr[i] % len(arr)
arr[idx] += len(arr)
for i in range(0, len(arr)):
arr[i] = arr[i] // len(arr)
print(f'{i+1} -> {arr[i]}')
def main():
arr = [2, 3, 3, 2, 5]
solution1(arr)
arr = [2, 3, 3, 2, 5]
solution2(arr)
main()
| true |
5eca4ab4a7922ffa96649dff561a1946e0ed6906 | Nburkhal/mit-cs250 | /week2/problems/problem2.py | 2,846 | 4.65625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Now write a program that calculates the minimum fixed monthly payment needed
in order pay off a credit card balance within 12 months.
By a fixed monthly payment, we mean a single number which does not change each month,
but instead is a constant amount that will be paid each month.
In this problem, we will not be dealing with a minimum monthly payment rate.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
The program should print out one line: the lowest monthly payment
that will pay off all debt in under 1 year, for example:
Lowest Payment: 180
Assume that the interest is compounded monthly according to
the balance at the end of the month (after the payment for that month is made).
The monthly payment must be a multiple of $10 and is the same for all months.
Notice that it is possible for the balance to become negative
using this payment scheme, which is okay. A summary of the required math is found below:
Monthly interest rate = (Annual interest rate) / 12.0
Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
Test Case 1:
balance = 3329
annualInterestRate = 0.2
Result Your Code Should Generate:
-------------------
Lowest Payment: 310
Test Case 2:
balance = 4773
annualInterestRate = 0.2
Result Your Code Should Generate:
-------------------
Lowest Payment: 440
Test Case 3:
balance = 3926
annualInterestRate = 0.2
Result Your Code Should Generate:
-------------------
Lowest Payment: 360
"""
# Establish variables that we know / needed for the evaluation.
# Counter optional
balance = 3329
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12
monthlyPayment = 0
updatedBalance = balance
counter = 0
# Will loop through everything until we find a rate that will reduce updatedBalance to 0.
while updatedBalance > 0:
# Was stated that payments needed to happen in increments of $10
monthlyPayment += 10
# To reset balance back to actual balance when loop inevitably fails.
updatedBalance = balance
month = 1
# For 12 months and while balance is not 0...
while month <= 12 and updatedBalance > 0:
# Subtract the ($10*n) amount
updatedBalance -= monthlyPayment
# Compound the interest AFTER making monthly payment
interest = monthlyInterestRate * updatedBalance
updatedBalance += interest
# Increase month counter
month += 1
counter += 1
print("Lowest Payment: ", monthlyPayment)
print("Number of iterations: ", counter)
| true |
20415ecf355899174066d5787719ae91627a5e69 | Nburkhal/mit-cs250 | /week2/exercises/isin.py | 1,292 | 4.5 | 4 | """
We can use the idea of bisection search to determine if a character is in a string, so long as the string is sorted in alphabetical order.
First, test the middle character of a string against the character you're looking for (the "test character"). If they are the same, we are done - we've found the character we're looking for!
If they're not the same, check if the test character is "smaller" than the middle character. If so, we need only consider the lower half of the string; otherwise, we only consider the upper half of the string. (Note that you can compare characters using Python's < function.)
Implement the function isIn(char, aStr) which implements the above idea recursively to test if char is in aStr. char will be a single character and aStr will be a string that is in alphabetical order. The function should return a boolean value.
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
lo, hi = 0, len(aStr)
if len(aStr) == 0:
return False
m = lo + (hi - lo) // 2
if char < aStr[m]:
return isIn(char, aStr[:m])
elif char > aStr[m]:
return isIn(char, aStr[m + 1:])
else:
return char == aStr[m]
| true |
b453a134bf928e2d1fa91594b7573016c949cafd | victorcocuz/DSAN-Problems_Vs_Algorithms | /problem_03-rearange_array_digits.py | 2,269 | 4.21875 | 4 | def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
# Edge case
if len(input_list) == 0:
return [0, 0]
if len(input_list) == 1:
return [input_list[0], 0]
return get_largest_sum(rearrange_digits_recursive(input_list))
# Helper method to return the largest sum of an ordered array
def get_largest_sum(arr):
first, second = 0, 0
# Alternatively appends digits to two different numbers in a descending order
for i in range(len(arr)-1, -1, -2):
if i >= 0:
first *= 10
first += arr[i]
if i - 1 >= 0:
second *= 10
second += arr[i-1]
return [first, second]
# Recursive method that decomposes an array and sorts it by using Divide and Conquer
def rearrange_digits_recursive(input_list):
if len(input_list) == 1:
return input_list
mid = len(input_list) // 2
left = rearrange_digits_recursive(input_list[:mid])
right = rearrange_digits_recursive(input_list[mid:])
return sort(left, right)
# Helper method to merge-sort two arrays
def sort(left, right):
l = []
left_index, right_index = 0, 0
left_len, right_len = len(left), len(right)
while left_index < left_len and right_index < right_len:
if left[left_index] <= right[right_index]:
l.append(left[left_index])
left_index += 1
else:
l.append(right[right_index])
right_index += 1
if left_index >= left_len:
l.extend(right[right_index:])
else:
l.extend(left[left_index:])
return l
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
# Tests
test_function([[1, 2, 3, 4, 5], [542, 31]])
test_function([[4, 6, 2, 5, 9, 8], [964, 852]])
test_function([[4, 6, 2, 5, 9, 8, 3], [9642, 853]])
test_function([[4, 6, 2, 5, 9, 8, 3], [9642, 853]])
# Edge cases
test_function([[], [0]])
test_function([[1], [1]])
test_function([[1, 2], [2, 1]])
| true |
fd258044a082da9c39f935545a0814f0f96b4335 | tayal1989/PythonLearning | /python_02listdict/22_KeyFunctionAndDiffBWSortFunctionAndSorted.py | 1,628 | 4.40625 | 4 | studs = [
'arun-CSE-67',
'hari-CSE-74',
'john-ISE-65',
'ajit-CSE-54',
'manu-ISE-76',
'elan-CSE-65',
'balu-ISE-85',
'amar-CSE-87'
]
#Sort them
studs.sort()
print(studs)
print("\n".join(studs)) #Sort on basis of names, first ajit will come and at last manu will come
print("\n")
#Sort them in reverse
studs.sort(reverse=True)
print("\n".join(studs)) #Reverse Sort on basis of names, first manu will come and at last ajit will come
print("\n")
#Key is based on what parameter, sort operation needs to be performed
studs.sort(key = lambda x:x.split("-")[1],reverse=False)
print("\n".join(studs)) #Sort on basis of branch, first CSE will come and at last ISE will come
print("\n")
studs.sort(key = lambda x:int(x.split("-")[2]),reverse=True)
print("\n".join(studs))
print("\n") #Reverse Sort on basis of marks, first 87 will come and at last 54 will com
#Sort by department and then by marks
def fun(x):
name, dept, marks = x.split("-")
return dept, -int(marks) # To print marks in reverse order for the particular department use "-" in front of int(marks)
studs.sort(key=fun, reverse=True)
print("\n".join(studs))
print("\n")
studs.sort(key=fun)
print("\n".join(studs))
print("\n")
arr = [4,2,6,1]
#Difference between sort function and sorted is once list is sorted using list.sort(), it will remain sorted. However, using sorted() function, it can be used when it is required and then when you print list, it will not show in sorted manner.
print(sorted(arr))
print(arr)
arr.sort()
print(arr)
#Similary it works for reverse
#arr.reverse()
#res = reversed(arr)
| true |
be06d2226c4b4281fa5bc3f03809ba3f4844f49e | tayal1989/PythonLearning | /python_04class/42_ClassModule.py | 1,868 | 4.25 | 4 | #class Emp(object): #Applicable in Python2.7, it means object is instance of class
class Emp:
counter = 0
#Default constructor in Python
def __init__(self, name = None, dept = None, salary = None): #self is The first argument of every class method,
#including __init__, is always a reference to the current instance of the class.
#By convention, this argument is always named self.
#In the __init__ method, self refers to the newly created object;
#in other class methods, it refers to the instance whose method was called
self.name = name
self.dept = dept
self.salary = salary
Emp.counter+=1
#Destructor in Python. It will be used when you open a file in default constructor then you can close the file here in destructor
#The destructor value will show in command line not in IDE as IDE will handle the garbage collector so it doesn't print any thing
#however, in command line, it has to do all the things
def __del__(self):
print("I am in destructor")
Emp.counter-=1
print("In Destructor : ", Emp.counter)
self = None
def showvalues(self):
print(self.name)
print(self.dept)
print(self.salary)
@staticmethod
def showcounter():
print("Counter = ", Emp.counter)
eob1 = Emp('amit', 'sales', 15000)
eob2 = Emp('hari', 'hrd', 10000)
eob3 = Emp()
eob1.showvalues()
eob2.showvalues()
eob3.showvalues()
print(Emp.showcounter())
print(type(eob1))
print(eob1)
print(eob1.__dict__)
print(eob1.showvalues)
print(eob1.showcounter) | true |
ed03c7963b08db37b9ee5c8f41cb3ab4de77e489 | heittre/Year2-Sem2-sliit | /DSA/Labs/lab7/question1.py | 608 | 4.125 | 4 | # my algo
def selection_sort(array):
n = len(array)
for i in range(n):
min_inx = i
for j in range(i + 1, n):
if(array[min_inx] > array[j]):
min_inx = j
array[i], array[min_inx] = array[min_inx], array[i]
# given algo
def selection_sort2(array):
n = len(array)
for j in range(n -1):
smallest = j
for i in range(j + 1, n):
if(array[i] < array[smallest]):
smallest = i
array[j], array[smallest] = array[smallest], array[j]
array = [5, 8, 6, 3 , 2 , 1]
selection_sort2(array)
print(array)
| false |
d29c02d6fd83dd0347acc90923b9ba4d90abdc1a | sayush23/Python | /Q6.py | 276 | 4.1875 | 4 | listName = []
listAge = []
listMail = []
for i in range(0,3):
listName.append(input("Enter Name"))
for i in range(0,3):
listAge.append(int(input("Enter Age")))
for i in range(0,3):
listMail.append(input("Enter Mail"))
print(listName)
print(listAge)
print(listMail) | false |
c2df053265a2584312532e421bcfd4818b9f2a9e | HuzefaMotorwala/Python_Essentials | /Dayofyear.py | 647 | 4.21875 | 4 | def isYearLeap(year):
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False
def daysInMonth(year, month):
monthdays=[0,31,28,31,30,31,30,31,31,30,31,30,31]
if isYearLeap(year)==True and month==2:
monthdays[2]=29
return monthdays[month]
def dayOfYear(year, month, day):
if year<1582:
if month>12 or month<1:
if day>31 or day<1:
return None
totdays = day
month = month-1
while month>0:
totdays+=daysInMonth(year,month)
month-=1
return totdays
print(dayOfYear(2000, 12, 31))
| true |
2e8bcd1befc41134600667878c7aefabfe453b2f | usf-cs-spring-2019-anita-rathi/110-assignment-1-1-danicacordova | /E1.6.py | 505 | 4.21875 | 4 | #Exercise 1.6
#1
radius=float(input("Enter the radius:"))
area=float(radius**2*3.14)
circ=float(radius*2*3.14)
print("Area:",area)
print("Circumference:",circ)
#2
VAR1=float(input("Enter Variable 1:"))
VAR2=float(input("Enter Variable 2:"))
print("OG Variable 1:", VAR1)
print("OG Variable 2:", VAR2)
NVAR1=VAR2
NVAR2=VAR1
print("New Variable 1:", NVAR1)
print("New Variable 2:", NVAR2)
#3
celc=float(input("Enter degrees in Celcius:"))
fheit=float(9/5*celc+32)
print("Degree(s) in Fahrenheit:",fheit)
| false |
324691cab248781b4f6d7497cc671a87e897a2e6 | alex3287/python-2019 | /sorts/bubbleSort.py | 205 | 4.15625 | 4 | def bubble_sort(array):
for i in range(len(array)-1):
for j in range(i,len(array)):
if array[i] > array[j]:
array[i], array[j] = array[j], array[i]
return array
| false |
68f32645002f0ba59e8006678d66ddbac0869e45 | krishnatvl88/python_practice | /Python_strings.py | 1,645 | 4.34375 | 4 | # Accessing values in strings
var1 = "Guru99!"
var2 = "Software Testing"
print ("var1[0]:",var1[0])
print ("var2[1:5]:",var2[1:5])
#Concatenation
a = "guru"
b = 99
print(a+str(b))
print(a*2)
# [] - Gives letter from index
f = "Helloworld"
print(f[2])
# [:] - Gives the characters from the given range
f = "Helloworld"
print(f[2:5])
# in - Membership-returns true if a letter exist in the given string
f = "Helloworld"
print("o" in f)
# not in - Membership-returns true if a letter exist is not in the given string
x = "helloworld"
print("z" not in x)
# %r - It insert the canonical string representation of the object (i.e., repr(o)) %s- It insert the presentation string representation of the object (i.e., str(o)) %d- it will format a number for display
name = 'guru'
number = 99
print('%s %d' % (name,number))
# + - It concatenates 2 strings
x="Guru"
y="99"
print(x+y)
# * - Repeat
x = "Guru"
y = "99"
print(x * 2)
# re-assigning a variable to another string
x = "Hello World!"
#print(x[:6])
print(x[0:6] + "Guru99")
#String replace()
oldstring = 'I like Guru99'
newstring = oldstring.replace('like', 'love')
print(newstring)
# to upper case
string="python at guru99"
print(string.upper())
# to lower case
string="python at guru99"
print(string.lower())
# to capitalize
string="python at guru99"
print(string.capitalize())
#join function
print(":".join("Python"))
#Reverse string
string="12345"
print(' '.join(reversed(string)))
#Split strings
word="guru99 career guru99"
print(word.split(' '))
#Split with r
word="guru99 career guru99"
print(word.split('r'))
#Immutable
x = "Guru99"
x.replace("Guru99","Python")
print(x)
| true |
2d2897d251924538c2bb8967b25ad774abe60626 | rkzwei/python-course-projects | /hangman.py | 739 | 4.1875 | 4 | alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
#TODO-1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs.
def cipher (text, shifts):
if direction == "encode":
message = list(text)
encrypted = list.copy(alphabet)
final = ""
for char in message:
shoft = (encrypted.index(char))
encryption = (encrypted[shoft+shift])
final += encryption
print (final)
cipher(text=text,shifts=shift)
| true |
d9d3b3c983fd311963d9673e446e1b75dea2f913 | SaileshPatel/Python-Exercises | /ex21.py | 913 | 4.15625 | 4 | # creating function with 'a' and 'b' as parameters
def add(a, b):
# the function prints the following string with formatters
print "ADDING %d + %d" % (a, b)
# the function then returns the answer to a mathematic sum
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
# printing string!
print "Let's do some maths with just functions!"
# assigning value to variable. the value is add, with the parameters, '30' and '5'
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
print "Here's a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?" | true |
e0f655b6c547ff84ebe1945e9cdfb67422cffd40 | Matheuslucena/Python-class | /python_aula_1/adivinhar_numero.py | 450 | 4.125 | 4 | #!usr/bin/env python
#-*- encoding: utf-8 -*-
import random
numero = random.randint(1, 100)
escolha = 0
tentativas = 0
while escolha != numero:
escolha = input("Escolha um número entre 1 e 100: ")
tentativas += 1
if escolha < numero:
print "O número", escolha, "é menor que o sorteado"
elif escolha > numero:
print "O número", escolha, "é maior que o sorteado"
print "Parabéns você acertou com", tentativas,"tentativas"
| false |
fde8c46726c98eca0355e7cfdeef49a75ad620ca | innovationcode/Graphs | /projects/graph/src/graph_demo.py | 1,420 | 4.21875 | 4 | #!/usr/bin/python
"""
Demonstration of Graph functionality.
"""
from sys import argv
from graph import Graph
def main():
graph = Graph() # Instantiate your graph
graph.add_vertex(0)
graph.add_vertex(1)
graph.add_vertex(2)
graph.add_vertex(3)
graph.add_vertex(4)
graph.add_vertex(5)
graph.add_vertex(6)
graph.add_vertex(7)
graph.add_vertex(8)
graph.add_edge(0,1)
graph.add_edge(0,2)
graph.add_edge(1,3)
graph.add_edge(1,4)
graph.add_edge(2,4)
graph.add_edge(2,5)
graph.add_edge(3,6)
graph.add_edge(4,6)
graph.add_edge(4,7)
graph.add_edge(6,8)
graph.add_edge(7,8)
graph.add_edge(5,7)
print(graph.vertices)
print("\nBREADTH-FIRST-TRAVERSAL...")
graph.breadth_first_traversal(0)
print("\nDEPTH-FIRST-TRAVERSAL...")
graph.depth_first_traversal(0)
print("\nDEPTH-FIRST-TRAVERSAL-RECURSIVE")
print("\n",graph.DFT_recursive(0))
print("\nBREADTH-FIRST-SERACH...")
print("\n",graph.breadth_first_search(0, 3)) # TRUE as 3 is in vertices
print("\nDEPTH-FIRST-SEARCH...")
print("\n",graph.depth_first_search(0, 9)) # False as 9 is not present in vertices
print("BFS_PATH " ,graph.BFS_path(0, 3)) #0-1-3
print("DFS_PATH " ,graph.BFS_path(0, 3)) #0-1-3
print("DFS_PATH " ,graph.BFS_path(0, 4)) #0-1-4
if __name__ == '__main__':
# TODO - parse argv
main()
| false |
366631844931175d992473460b1081a1e4e9ee98 | NikitaKolotushkin/Basic-Algorithms | /insertion-sort/python/main.py | 539 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def insertion_sort(list_: list) -> list:
"""Returns a sorted list, by insertion sort method
:param list_: The list to be sorted
:type list_: list
:rtype: list
:return: Sorted list, by insertion sort method
"""
for i in range(1, len(list_)):
selected_element = list_[i]
j = i - 1
while j >= 0 and selected_element < list_[j]:
list_[j + 1] = list_[j]
j -= 1
list_[j + 1] = selected_element
return list_
| true |
b5853b679e8509c49313c29e75d3c8dd8c7a26eb | mlburgos/concept-practice | /code_challanges/prob_solving_w_algs_n_data_structs/recursion_exercises.py | 315 | 4.3125 | 4 | # 1. write a recusive function to compute the factorial of a number
def rec_fact(num):
if num == 1:
return 1
return num * rec_fact(num - 1)
# 2. write a recursive function to reverse a list
def rev_list(lst):
if len(lst) == 1:
return lst
return [lst[-1]] + rev_list(lst[:-1])
| true |
cdcde01549d511d93aacb1222837df688e85a212 | capri2020/dict_word_count | /wordcount.py | 1,554 | 4.15625 | 4 | # put your code here.
with open('test.txt') as poem:
# go through each line DONE
# find all words in line DONE
# pass words into a dictionary with a counter DONE
# check if word exists DONE
# if no, create it DONE
# if yes, increment it DONE
# repeat and increment counters as we go through each word in a line DONE
# when completed with all lines, print results of the dictionary (not just the dict), following format DONE
wordcount_dictionary = {}
for line in poem:
strip_line = line.strip()
list_line = line.split(' ')
for word in list_line:
word = word.strip()
# if word in wordcount_dictionary:
# wordcount_dictionary[word] += 1
# else:
# wordcount_dictionary[word] = 1
wordcount_dictionary[word] = wordcount_dictionary.get(word, 0) + 1
for key, value in wordcount_dictionary.items():
print(key, value)
"""
NOTES:
we get back lines of text stored as a string
example: 'As I was going to St. Ives'
we want to check the number of times each 'word' appears
Q: how do we get from a string of words to a single word that we can use to measure/count?
A: We want to split the string of words by SOMETHING. SOMETHING = ' '
['As', 'I', 'was', 'going', 'to', 'St.', 'Ives']
Q: How do we create a dictionary?
A: we name a variable with {}
wordcount_dictionary = {}
Q: How do we create a new key in a dictionary?
A: We need to use some kind of a bracket. dictionary_name[key] = value
""" | true |
665b11697134736087e9665a07c7bd5ab4bb618e | Greatdane/MITx-6.00.1x | /ProblemSets/FinalExam04b.py | 1,646 | 4.125 | 4 | # Final Exam - Problem 4, Part 2
# Write a function called longestRun, which takes as a parameter a list of integers named L (assume L is not empty).
# This function returns the length of the longest run of monotonically increasing numbers occurring in L. A run of
# monotonically increasing numbers means that a number at position k+1 in the sequence is either greater than or equal
# to the number at position k in the sequence.
def longestRun(L):
'''
Assumes L is not empty
Returns the length of the longest run of monotonically increasing numbers occurring in L
'''
total = 0 # running total
longest = 0 # longest length
last_num = L[0]
for x in L:
if x >= last_num: # if x is greater than the last number, add 1 to the total
total += 1
else:
if longest > total: # check to see of the current total is smaller than longest, if so pass
pass
else:
longest = total # otherwise, current total is the longest run to date, equals longest
total = 1 # result total back to 1.
last_num = x # last number defined at the end of the loop to give us last number used in list.
# additonal check at the end to make sure total is not a larger number than longest
if total > longest:
longest = total
return longest
# Example - Should return the value 5 because the longest run of monotonically increasing integers in L is [3, 4, 5, 7, 7]
L = [10, 4, 6, 8, 3, 4, 5, 7, 7, 2]
print longestRun(L)
L = [4, 4, 4, 4, 11, 17, 999, 3, 4, 6, 13, -1, -4 , -7 ]
print longestRun(L) | true |
93909e251ab83bc1e088cebb2f82f4982dc8a4c7 | Greatdane/MITx-6.00.1x | /ProblemSets/ProblemSet07a.py | 2,583 | 4.25 | 4 | # Problem Set 07a - The Adoption Center
class AdoptionCenter:
"""
The AdoptionCenter class stores the important information that a
client would need to know about, such as the different numbers of
species stored, the location, and the name. It also has a method to adopt a pet.
"""
def __init__(self, name, species_types, location):
'''
Initializes a AdoptionCenter object
name - A string that represents the name of the adoption center.
location - A tuple (x, y) That represents the x and y as floating point coordinates of the adoption center location.
species_types - A string:integer dictionary that represents the number of specific pets that each adoption center holds.
An example would be: {"Dog": 10, "Cat": 5, "Lizard": 3}
Note that the specific animals tracked depend on the adoption center. If an adoption center does not have any of a specific
species up for adoption, it will not be represented in the dictionary.
'''
self.name = name
self.location = (float(location[0]), float(location[1])) #location is now floating point tuple.
self.species_types = species_types
def get_number_of_species(self, animal):
'''
Returns the number of a given species that the adoption center has.
'''
if animal in self.species_types:
return self.species_types[animal]
else:
return 0 #returns zero if the adoption center does not have an animal.
def get_location(self):
'''
Returns the location of the adoption center
'''
return self.location
def get_species_count(self):
'''
Returns a copy of the full list and count of the available species at the adoption center.
'''
return self.species_types.copy()
def get_name(self):
'''
Returns the name of the adoption center
'''
return self.name
def adopt_pet(self, species):
'''
Decrements the value of a specific species at the adoption center and does not return anything.
'''
adopted = self.species_types[species]
if species in self.species_types:
adopted -= 1
self.species_types[species] = adopted
if self.species_types[species] == 0: # Delete species from dictionary if count is zero
del self.species_types[species]
# Testing..
BA = AdoptionCenter('Best adoption', {'Dog': 3, 'Cat': 1}, (43.11, 59.11))
BA.adopt_pet('Cat') | true |
47ca1fc292624850fefe2c7897b07f03daabf6bd | Greatdane/MITx-6.00.1x | /Quiz_Problem07.py | 1,881 | 4.4375 | 4 | # Quiz, Problem 7 - Summer 2016
# Write a function called dict_interdiff that takes in two dictionaries (d1 and d2).
# The function will return a tuple of two dictionaries: a dictionary of the intersect
# of d1 and d2 and a dictionary of the difference of d1 and d2
#
# intersect: The keys to the intersect dictionary are keys that are common in both d1 and d2.
# To get the values of the intersect dictionary, look at the common keys in d1 and d2 and apply the function f
# to these keys' values -- the value of the common key in d1 is the first parameter to the function and the value of
# the common key in d2 is the second parameter to the function. Do not implement f inside your
# dict_interdiff code -- assume it is defined outside.
#
# difference: a key-value pair in the difference dictionary is (a) every key-value pair in d1 whose key appears
# only in d1 and not in d2 or (b) every key-value pair in d2 whose key appears only in d2 and not in d1.
# f in example 1..
def f(a, b):
return a + b
# f in example 2..
def f2(a, b):
return a > b
def dict_interdiff(d1, d2):
'''
d1, d2: dicts whose keys and values are integers
Returns a tuple of dictionaries according to the instructions above
'''
dictA = {} # intersect
dictB = {} # difference
for n in d1:
if n in d2:
dictA[n] = f(d1[n], d2[n]) #f and f2 for example
else:
dictB[n] = d1[n]
for n in d2:
if n in d1:
n
else:
dictB[n] = d2[n]
return (dictA, dictB)
# Example 1
#d1 = {1:30, 2:20, 3:30, 5:80}
#d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
# Example 2
d1 = {1:30, 2:20, 3:30}
d2 = {1:40, 2:50, 3:60}
# Returns tuple, ({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90}) - Example 1
# Returns tuple, ({1: False, 2: False, 3: False}, {}) - Example 2
print dict_interdiff(d1, d2) | true |
8cf43c90514cbd135cc1cb7840b3eda43867f574 | Greatdane/MITx-6.00.1x | /ProblemSets/ProblemSet03b_Hangman_b.py | 1,496 | 4.1875 | 4 | #Problem Set 3 - Hangman - Printing Out the User's Guess
# implement the function getGuessedWord that takes in two parameters - a string, secretWord,
# and a list of letters, lettersGuessed. This function returns a string that is comprised of letters
# and underscores, based on what letters in lettersGuessed are in secretWord
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
ans = "" # set answer as empty string
for guess in secretWord: # go through the secret word
if guess in lettersGuessed: # if the letter gueeses is in the sercet word, add it to ans
ans += guess
else:
ans += "_ " # otherwise add a _ to indicate a missing character
return ans
#tests..
getGuessedWord('apple', ['e', 'i', 'k', 'p', 'r', 's']) # '_ pp_ e'
getGuessedWord('durian', ['a', 'c', 'd', 'h', 'i', 'm', 'n', 'r', 't', 'u']) # 'durian'
getGuessedWord('broccoli', ['g', 'b', 'h', 'r', 'k', 'i', 'c', 'm', 'p', 'u']) # 'br_ cc_ _ i'
getGuessedWord('pineapple', ['a', 'b', 'o', 'x', 'c', 'z', 'h', 'm', 's', 'e']) # '_ _ _ ea_ _ _ e'
getGuessedWord('pineapple', []) # '_ _ _ _ _ _ _ _ _ '
getGuessedWord('mangosteen', ['r', 'x', 'z', 'b', 'h', 's', 'f', 'm', 'n', 'k']) # 'm_ n_ _ s_ _ _ n' | true |
5ad4fec4dccb0e2d15277f52df7338a335a32f66 | Greatdane/MITx-6.00.1x | /TempConverter.py | 1,452 | 4.46875 | 4 | #simple temperature converter
#https://courses.edx.org/courses/course-v1:MITx+6.00.1x_9+2T2016/discussion/forum/6.00.1x_General/threads/575d833135c79c0562000340
print("Welcome to the temperature scale conversion script\n")
#note - the \n on the string. This is just an escape sequence and it's used on string formatting to print a new line
celsius = float(raw_input("Enter the value in C to convert:\n"))
#we are using Celsius as the default temperature and then convert it to Fahrenheit and Kelvin. raw_input() handles input as strings,
#so we have to convert the input to a numerical value! We do this as follows variable = float(raw_input("msg")
while(celsius < -273.15):
print("Enter a valid temperature input\n")
celsius = float(raw_input("Enter the value in C to convert:\n"))
fahrenheit = celsius * 9.0 / 5.0 + 32 #F = C * 9/5 + 32
kelvin = celsius + 273.15 #celsius + 273.15 - This is why we check we don't have a number below -273.15!
print("%.2f C = %.2f F and %.2f K"% (celsius, fahrenheit, kelvin))
#Place holders in Python work as follows: %s for strings, %f for floats, etc and replaces the annoying task of converting the temperature
#variables to strings in the print function. The .2 that lies between % symbol and the f means the decimal place i want my solution to display,
#in this case it will only show 2 decimal places.
# print("%f %s" %(variable1, variable2))
# where variable1 is a float and variable2 is a string. | true |
b566c25967741c18cd8b76fa3d8ccb9694201b71 | eddie246/python-playground | /Week 2/day 9 - Dictonaries/index.py | 1,207 | 4.15625 | 4 | programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
}
print(programming_dictionary["Bug"])
programming_dictionary["Loop"] = "The action of doing something over and over again."
programming_dictionary["Bug"] = "Overwrite"
# print(programming_dictionary)
for key in programming_dictionary:
print(programming_dictionary[key])
#######################################
#Nesting
capitals = {
"France": "Paris",
"Germany": "Berlin",
}
#Nesting a List in a Dictionary
travel_log = {
"France": ["Paris", "Lille", "Dijon"],
"Germany": ["Berlin", "Hamburg", "Stuttgart"],
}
#Nesting Dictionary in a Dictionary
travel_log = {
"France": {"cities_visited": ["Paris", "Lille", "Dijon"], "total_visits": 12},
"Germany": {"cities_visited": ["Berlin", "Hamburg", "Stuttgart"], "total_visits": 5},
}
#Nesting Dictionaries in Lists
travel_log = [
{
"country": "France",
"cities_visited": ["Paris", "Lille", "Dijon"],
"total_visits": 12,
},
{
"country": "Germany",
"cities_visited": ["Berlin", "Hamburg", "Stuttgart"],
"total_visits": 5,
},
] | true |
9e10a1a74582822b0fa6b36d676008441aa710f3 | eddie246/python-playground | /Week 2/day 10 - Function Outputs/index.py | 303 | 4.1875 | 4 | def my_func():
result = 3 * 2
return result
print(my_func())
def format_name(f_name, l_name):
"""Take first and last name and format it and returns title version"""
name = ''
name += f_name.title()
name += ' '
name += l_name.title()
return name
print(format_name('eddie', 'wang'))
| true |
81168a185d4569ff14a77676f285c7476ce354d5 | zohra009/python-beginners | /app.py | 611 | 4.3125 | 4 | #concatination = taking a string and appending another string together
phrase = "Giraffe Academy"
print(phrase.upper())
print(phrase.lower())
#replace's giraffe with elephant
print(phrase.replace('Giraffe', 'Elephant'))
#string with index on string 0 being first letter
print(phrase[3])
#index function gives position of the value in #'s
print(phrase.index('Acad'))
# length function to get length of string
print(len(phrase))
print(phrase.upper().isupper()) #isupper gives t/f value
print(phrase.isupper())
print ('Giraffe\nAcademy') #\n creates new line
#functions can modify string and get info on strings
| true |
6d01d4ede3550569ecf93c669a412ee00d9ed700 | DustinY/EcoCar3-Freshmen-Training | /Assignment_1/Matthew/Area of a cylinder.py | 390 | 4.25 | 4 |
# Area of a cylinder
# A=2πrh+2πr2
print "Finding the Area of a cylinder"
print " "
var_Radius = int(raw_input("What is the Radius of the Cylinder? "))
var_Length = int(raw_input("What is the Length of the Cylinder? "))
Area_of_cylinder = 2 * 3.14 * var_Radius * var_Length + 2 * 3.14 * var_Radius * var_Length
print ("The Area of the Cylinder is ", Area_of_cylinder)
| true |
6c31b1ae1352682985d6bd7e803767b42ea3b80d | SteveMaher/com404 | /0-setup/1-basics/4-repetition/3-nested-loop/1-nested/bot.py | 297 | 4.125 | 4 | # Nested Loop
rows = int(input("How many rows shoud I have?"))
columns = int(input("How many columns should I have?"))
emoji = ":-) "
print("Here I go:")
print()
for count in range(0, rows, 1):
for count in range(0, columns, 1):
print(emoji, end="")
print()
print("\n Done !")
| true |
e813030b55db207511ef02686121a69285e7e3ec | VCloser/CodingInterviewChinese2-python | /45_SortArrayForMinNumber.py | 781 | 4.21875 | 4 | """
由于python3中sorted函数除去compare函数,无法自定义排序规则,所以使用内置的函数,将cmp函数转化为key的值
Note:
functools.cmp_to_key() 将 cmp函数 转化为 key。
cmp函数的返回值 必须为 [1,-1,0]
"""
from functools import cmp_to_key
def compare(strNum1, strNum2):
newStrNum1 = strNum1 + strNum2
newStrNum2 = strNum2 + strNum1
if newStrNum2 > newStrNum1:
return -1
elif newStrNum2 == newStrNum1:
return 0
else:
return 1
def print_min_nums(nums):
if not nums:
return 0
arr = [str(i) for i in nums]
newarr = sorted(arr,key=cmp_to_key(compare))
return "".join(newarr)
if __name__ == '__main__':
print(print_min_nums([3,32,321])) | false |
2d4512bd301c67402d8fbc8e305a1eec11c21d06 | VCloser/CodingInterviewChinese2-python | /56_01_NumbersAppearOnce.py | 1,408 | 4.15625 | 4 | """
从头到尾一次异或数组中的每一个数字,那么最终得到的结果就是两个只出现一次的数组的异或结果。因为其他数字都出现了两次,在异或中全部抵消了。
由于两个数字肯定不一样,那么异或的结果肯定不为0,也就是说这个结果数组的二进制表示至少有一个位为1。
我们在结果数组中找到第一个为1的位的位置,记为第n位。
现在我们以第n位是不是1为标准把元数组中的数字分成两个子数组,第一个子数组中每个数字的第n位都是1,而第二个子数组中每个数字的第n位都是0。
"""
def find_nums_appear_once(arr):
if not arr or len(arr)<2:
return []
res = 0
for i in arr:
res = res^i
index = find_first_bit_is_1(res)
num1 = 0
num2 = 0
for i in arr:
if is_bit_1(i,index):
num1 = num1^i
else:
num2 = num2^i
return num1,num2
def find_first_bit_is_1(num):
"""
找到num的二进制位中最右边是1的位置
"""
index_of_bit = 0
while num != 0 and num & 1 == 0:
num = num >> 1
index_of_bit += 1
return index_of_bit
def is_bit_1(num,index):
"""
判断第index位是不是1
"""
num = num>>index
return num&1
if __name__ == "__main__":
print(find_nums_appear_once([-8, -4, 3, 6, 3, -8, 5, 5])) | false |
e65aca0ce37ebdc2cd7fa3b6731b1594c0ebfdbf | sachingharge/python-labs | /linkedin-python/excercise-files/Ch2/variables_start.py | 516 | 4.1875 | 4 | #
# Example file for variables
# (For Python 3.x, be sure to use the ExampleSnippets3.txt file)
# declare a variable and intialize it
f = 0
print (f)
# re-declaring the variable works
#f = "abcd"
#print (f)
# ERROR: variables of different types can not be combined
#print "string type" + 123
#print ("string type " + str(1234))
# Global vs local variables in functions
def somefunction():
global f
f = "def"
print (f)
somefunction()
print (f)
#un declare or remove variable value
del f
print (f)
| true |
6562f1f372f75ea97b6db7693b305718d6e19dad | sachingharge/python-labs | /stackskills-ex-files/volume_calculator_tuple.py | 1,267 | 4.34375 | 4 | '''
The program will ask the user will for the length, width and height of a rectangular box.
The program will calculate the volume of the box and display the result.
The program will display meaningful error messages and exit gracefully in all situations.
'''
def get_user_input(length, width, height):
input_length = input("Enter length value : ")
length_value = input_length
input_width = input("Enter width value : ")
width_value = input_width
input_height = input("Enter height value : ")
height_value = input_height
tupple_value = ('length_value', 'width_value', 'input_height')
print (tupple_value)
#try:
float_check = tupple_value
#except ValueError:
# raise ValueError("%s is not a number" % float_check)
#if float_check <= 0:
# raise ValueError("All dimensions must be greater than zero.")
def main():
print ("This program will calculate the volume of a rectangular box given its length, width, and height.\n")
sucess = False
try:
length, width, height = get_user_input('Length', 'Width', 'Height')
sucess = True
except ValueError as e:
print (e)
except KeyboardInterrupt:
print ("\nGoodBye.")
if __name__ == "__main__":
main()
| true |
5a61d14f12927d9851a4919ea71ea20adc41fc9d | harmonybo/python_day2 | /day2_6_算术运算符.py | 789 | 4.375 | 4 | # + - * / %取余 ** //
print(4+2,12.4-4.5,4*2,4/2)
print(8/3)
print(10%5)
print(8//3) #整除
# / 和 //区别: // 是整除,/会取到小数
print(4**3) # x**y :求x的y次方
str1 = "11.2"
str1 = float(str1)#将字符串对应的数据类型转换时,整数转换为整数,小数转换为小数
print(str1,type(str1))
num = 4;
#print(num--); #在python中,没有 ++ -- 这种写法
num+=1; # num=num+1 5
num-=1;#num = num-1 4
num*=2;#num = num*2 8
#num/=2#num = num/2 4.0
#num%=2 ;#num = num%2 0.0
num**=2;#num=num**2
print(num);
list1 = [1,12,"abc"];
#self :类似于java中的this,方法参数中有self时,可以不用管他,直接传对应的参数即可
list1.append("def")
#根据下标进行添加
list1.insert(1,True)
print(list1) | false |
f7c42c2a3429c65c4df2ee17c09fcb38c9bdf1d2 | tryanbeavers/prep_work | /ice_cream_parlor.py | 2,445 | 4.15625 | 4 | # Two friends like to pool their money and go to the ice cream parlor. They always choose two distinct flavors and they spend all of their money.
#
# Given a list of prices for the flavors of ice cream, select the two that will cost all of the money they have.
#
# Example.
#
# The two flavors that cost and meet the criteria. Using -based indexing, they are at indices and .
#
# Function Description
#
# Complete the icecreamParlor function in the editor below.
#
# icecreamParlor has the following parameter(s):
#
# int m: the amount of money they have to spend
# int cost[n]: the cost of each flavor of ice cream
# Returns
#
# int[2]: the indices of the prices of the two flavors they buy, sorted ascending
# Input Format
#
# The first line contains an integer, , the number of trips to the ice cream parlor. The next sets of lines each describe a visit.
#
# Each trip is described as follows:
#
# The integer , the amount of money they have pooled.
# The integer , the number of flavors offered at the time.
# space-separated integers denoting the cost of each flavor: .
# Note: The index within the cost array represents the flavor of the ice cream purchased.
# STDIN Function
# ----- --------
# 2 t = 2
# 4 k = 4
# 5 cost[] size n = 5
# 1 4 5 3 2 cost = [1, 4, 5, 3, 2]
# 4 k = 4
# 4 cost[] size n = 4
# 2 2 4 3 cost=[2, 2,4, 3]
# OUTPUT
# 1 4
# 1 2
def icecreamParlor(m, arr):
guesser = m - 1
quick_find = {}
for k, v in enumerate(arr):
quick_find[v] = k + 1
print(quick_find)
flav1= 0
flav2= 0
while guesser > 0:
if quick_find.get(guesser,None) is not None and quick_find.get(m - guesser,None) is not None:
#we have a duplicate
if (quick_find[m - guesser] == quick_find[guesser]):
for k,v in enumerate(arr):
if (v == (m-guesser)) and (k+1 != quick_find[guesser]):
flav1 = k+1
flav2 = quick_find[guesser]
continue
else:
flav1=quick_find[m - guesser]
flav2=quick_find[guesser]
break
else:
guesser = guesser - 1
if flav1 > flav2:
return (flav2, flav1)
else:
return (flav1, flav2)
if __name__ == "__main__":
m=4
arr=[2,2,4,3]
res = icecreamParlor(m,arr)
print(res) | true |
3b60cc8f574b76f172a6ed3399c2ad73025d5b77 | tryanbeavers/prep_work | /level_order_tree.py | 1,400 | 4.53125 | 5 | # Trees: Level order traversal of binary tree
# Given the root of a binary tree, display the node values at each level.
# Node values for all levels should be displayed on separate lines.
#TAKEN FROM EXAMPLE
class Node(object):
"""Binary tree Node class has
data, left and right child"""
def __init__(self, item):
self.data = item
self.left = None
self.right = None
def process_level(current_level, q_current):
q_next = []
print("LEVEL #" + str(current_level))
while (len(q_current) > 0):
print(q_current[0].data)
element = q_current.pop(0)
# try to add each child to keep the queue going
if element.left is not None:
q_next.append(element.left)
if element.right is not None:
q_next.append(element.right)
print("\n")
return q_next
def level_order_tree(root):
#start with your queue empty
current_level = 0
q_current = []
q_current.append(root)
while True:
if len(q_current) == 0:
return
else:
current_level = current_level+1
q_current = process_level(current_level, q_current)
if __name__ == "__main__":
root = Node(100)
root.left = Node(50)
root.right = Node(200)
root.left.left = Node(25)
root.left.right = Node(75)
root.right.right = Node(350)
level_order_tree(root) | true |
e9492cadc0caf7499a4b293422565ea8bf98ccd7 | codenigma1/Python_Specilization_University_of_Michigan | /Getting Started with Python AND Python Data Structure/tuples.py | 671 | 4.34375 | 4 | # Tuples simple program #
(x, y) = ("Vaibhav", 39)
print y
# Tuples are also comparable #
a = (9, 2, 5) # It is look only first value of the tuples while comparing #
b = (10, 3, 4)
c = a > b
print c
# Tuple match only first value whether is greater or not #
v = ("vaibhav", "Sachin", "Drag")
k = ("fun", "fuck", "did")
f = v > k
print f
# Sorting Lists of tuples #
d = {"ema": 3, "fun": 4, "shit": 34}
t = d.items()
print t
# t.sort() # Simply sorting a list without variabe #
r = sorted(t) # Sorted() fuction, it is new fuction for sorting tuples we can assign variable sorted(t) them #
print r
# we can also sort by forloop#
for k,v in sorted(t) :
print k, v | true |
357c75005e5a820c2fb4d92aaf8aeaa67158f587 | codenigma1/Python_Specilization_University_of_Michigan | /Getting Started with Python AND Python Data Structure/list.py | 929 | 4.25 | 4 | # List items #
print ["tupples", 34, 34.5]
# Print what you like it in list #
friends = ["Vaibhav", "Naruto", "Batman"]
print "Welcome", friends[1]
# Immutable list #
fruit = "Banana"
# fruit[0] = "b" # string doesn't change data #
# It will give teaceback....#
x = fruit.lower()
print x
# Mutable list #
num = [2,44,3,5,53,5] # List does change data #
num[3] = 23
print num
# Difference between length and range #
print "Range is: ", range(4)
print "Len is: ", len(friends)
print "Range is: ", range(len(friends))
# concatenation list but it doesn't hurt list #
a = [1,2,3]
b = [4,5,6]
c = a + b
print "comnbined list: ", c
print "doesn't hurt previous list: ", a
# List slice to the string #
# Remember: Just like string, second string up to but not including #
t = [2,3,4,5,6,7,8,3,21,21,313]
print "Remember: Just like string, second string up to but not including: ", t[1:3]
print t[4:9]
print t[3:7]
print t[:]
| true |
ef8d97fd7301bdf2a4dea832fca1932734a56142 | Airono/ifmo_informatics | /lab_01/lab_01_03.py | 1,249 | 4.21875 | 4 | '''
Форматированный ввод/вывод данных
'''
m = 10
pi = 3.1415927
print("m = ", m)
print("m = %d" % m)
print("%7d" % m)
print("pi = ", pi)
print("%.3f" % pi)
print("%10.4f\n" % pi)
print("m = {}, pi = {}".format(m, pi))
ch = 'A'
print("ch = %c" % ch)
s = "Hello"
print("s = %s" % s)
print("\n\n")
code = input("Enter your position number in group: ")
n1, n2 = input("Enter two numbers splitted by space: ").split()
d, m, y = input("Enter three numbers splitted by \'.\': ").split('.')
print("{} + {} = {}".format(n1, n2, float(n1)+float(n2)))
print("Your birthday is %s.%s.%s and you are %d in the group list" % (d, m, y, int(code)))
print("\n")
m = 10
pi = 3.1415927
print("m = %4d; pi = %.3f" % (m, pi))
print("m = {}; pi = {}".format(m, pi))
print("\n")
year = input("Enter your year of study: ")
print("year = ", year)
print("\n")
r1, m1, p1 = input("Enter your marks for russian, math and profile subject exams by \',\': ").split(',')
print(r1, m1, p1)
print("\n")
sys = int(d) % 8
print("Enter twelve-digit number in {} notation: ".format(sys))
number = input()
number = int(str(number), sys)
print("Your number in 10 notation: ", number)
print("number * 2 = ", number << 1)
print("number / 2 = ", number >> 1)
| false |
8fa8a00926d9e1e5eaf0d61f254dae4265e0363d | chenyaoling/python-study2 | /day06/03-线程的基本使用2.py | 713 | 4.28125 | 4 | """
子线程创建的步骤:
1、导入模块 threading
2、使用threading.Thread() 创建对象(子线程对象)
3、指定子线程执行的分支
4、启动子线程 线程对象.start()
"""
import time
import threading
# 定义函数
def saySorry():
print("对不起,我错了!")
time.sleep(0.5)
# 调用函数(单线程方式)
if __name__ == '__main__':
# 1、导入模块 threading
for i in range(5):
# 2、使用threading.Thread() 创建对象(子线程对象)
# 3、指定子线程执行的分支
thread_obj = threading.Thread(target=saySorry)
# 4、启动子线程 线程对象.start()
thread_obj.start()
print("xxxx")
| false |
5dff6a2cd671c7c8ae9f56826bf037c8b006e9cd | chenyaoling/python-study2 | /day15/05-多继承.py | 1,059 | 4.25 | 4 | # 定义父类Parent
class Parent(object):
def __init__(self, name, *args, **kwargs):
self.name = name
print('parent的init结束被调用')
class Son1(Parent):
def __init__(self, name, age, *args, **kwargs):
self.age = age
# Parent.__init__(self, name)
super(Son1, self).__init__(name, *args, **kwargs)
print('Son1的init结束被调用')
class Son2(Parent):
def __init__(self, name, gender, *args, **kwargs):
self.gender = gender
# Parent.__init__(self, name)
super(Son2, self).__init__(name, *args, **kwargs)
print('Son2的init结束被调用')
# 定义子类 Grandson --继承--> Son1 \ Son2
class Grandson(Son1, Son2):
def __init__(self, name, age, gender):
# Son1.__init__(self, name, age) # 单独调用⽗类的初始化方法
# Son2.__init__(self, name, gender)
super().__init__(name, age, gender)
print('Grandson的init结束被调用')
# 创建对象
gs = Grandson('grandson', 12, '男')
print(Grandson.mro())
| false |
134dc59150e44f53b9e8a1a32b59073a36a975f1 | chenyaoling/python-study2 | /day15/13-自定义上下文管理器实现文件操作.py | 1,126 | 4.375 | 4 | """
类: MyFile()
类方法:
1. __enter__() 上文方法
2. __exit__() 下文方法
3. __init__() 方法,接收参数并且初始化
with MyFile('hello.txt', 'r') as file:
file.read()
"""
class MyFile(object):
# 1. __enter__() 上文方法
def __enter__(self):
print("进入上文....")
# 1,打开文件
self.file = open(self.file_name, self.file_model)
# 2,返回打开的文件资源
return self.file
# 2. __exit__() 下文方法
def __exit__(self, exc_type, exc_val, exc_tb):
print("进入下文....")
# 关闭文件资源
self.file.close()
# 3. __init__() 方法,接收参数并且初始化
def __init__(self, file_name, file_model):
# 保存文件名和文件打开模式,到实例属性中
self.file_name = file_name
self.file_model = file_model
if __name__ == '__main__':
with MyFile("hello.txt", "r") as file:
# 开始读取文件
file_data = file.read()
print(file_data)
"""
进入上文....
hello,python!
进入下文....
""" | false |
53335998f0aa2be898e62667b511385a549801ba | rmodi6/scripts | /practice/Leetcode/3621_vertical_order_traversal_of_a_binary_tree.py | 936 | 4.125 | 4 | # https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/583/week-5-january-29th-january-31st/3621/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
def traverse(node, x, y, heap):
if node:
heapq.heappush(heap, (x, y, node.val))
traverse(node.left, x-1, y+1, heap)
traverse(node.right, x+1, y+1, heap)
heap = []
traverse(root, 0, 0, heap)
ans, px = [], None
while heap:
x, y, val = heapq.heappop(heap)
if x == px:
ans[-1].append(val)
else:
px = x
ans.append([val])
return ans
| false |
49b03f77c080e958807a3d5a8260a6af2619b717 | shankarpilli/PythonWorkout | /operators/RelationalOperators.py | 645 | 4.34375 | 4 | #This is the example for the relational or comparision operators
a = input ("Enter your number a : ")
b = input ("Enter your number b : ")
print "== ralational operator : "+str(a==b)
print "> ralational operator : "+str(a>b)
print "< ralational operator : "+str(a<b)
print "!= ralational operator : "+str(a!=b)
print ">= ralational operator : "+str(a>=b)
print "<= ralational operator : "+str(a<=b)
#Output
'''Enter your number a : 1
Enter your number b : 1
== ralational operator : True
> ralational operator : False
< ralational operator : False
!= ralational operator : False
>= ralational operator : True
<= ralational operator : True'''
| false |
9a580e4bdcf9eb09c5d96698f58195533d34d447 | Syedhash1/pyapi_2020_08_17 | /pyapi/backintime/clock01.py | 1,049 | 4.34375 | 4 | #!/usr/bin/python3
import time # This is required to include time module
def main():
## Count the number of ticks from the epoch
ticks = time.time()
print("Number of ticks since 12:00am, January 1, 1970: ", ticks)
## Show how we can convert ticks into a useful time tuple
myTime = time.localtime(ticks) # pass ticks to localtime
print("The local time tuple is: ", myTime)
print("The local time tuple year is: ", myTime[0])
print("The local time tuple month is: ", myTime[1])
print("The local time tuple day is: ", myTime[2])
print("The local time tuple hour is: ", myTime[3])
print("The local time tuple minute is: ", myTime[4])
print("The local time tuple second is: ", myTime[5])
print("The local time tuple week is: ", myTime[6])
print("The local time tuple year is: ", myTime[7])
print("The local time tuple daylight savings is: ", myTime[8])
for x in range(10):
print('This program will end in...', x)
time.sleep(5)
if __name__ == "__main__":
main()
| true |
687875edad5b42c29a11f7a9d29d1c862da6c023 | Luiza-Teixeira/Lista-de-exercicio | /quest 1 - lista 1 do professor - crescente e decrescente.py | 1,629 | 4.3125 | 4 |
numero_1 = int(input("Digite o 1° número:"))
numero_2 = int(input("Digite o 2° número:"))
numero_3 = int(input("Digite o 3° número:"))
ordem = input("Digite 3 números e coloque (d) para decrescente e (c) para crescente:")
if ordem == "c" or ordem == "C" or ordem == "d" or ordem== "D":
if ordem == "c" or ordem == "C":
if numero_1 < numero_2 < numero_3:
print(numero_1, numero_2, numero_3)
elif numero_3 < numero_1 < numero_2:
print(numero_3, numero_1, numero_2)
elif numero_2 < numero_3 < numero_1:
print(numero_2, numero_3, numero_1)
elif numero_1 < numero_3 < numero_2:
print(numero_1, numero_3, numero_2)
elif numero_3 < numero_2 < numero_1:
print(numero_3, numero_2, numero_1)
elif numero_2 < numero_1 < numero_3:
print(numero_2, numero_1, numero_3)
elif ordem == "d" or ordem == "D":
if numero_1 > numero_2 > numero_3:
print(numero_1, numero_2, numero_3)
elif numero_2 > numero_3 > numero_1:
print(numero_2, numero_3, numero_1)
elif numero_2 > numero_3 > numero_1:
print(numero_2, numero_3, numero_1)
elif numero_1 > numero_3 > numero_2:
print(numero_1, numero_3, numero_2)
elif numero_3 > numero_2 > numero_1:
print(numero_3, numero_2, numero_1)
elif numero_2 > numero_1 > numero_3:
print(numero_2, numero_1, numero_3)
| false |
c30a3a415d60a85bbec248fafc1df75b69c3bbe2 | beardedsamwise/Python-Crash-Course | /Chapters 1-11/Chapter 8/make_album.py | 741 | 4.1875 | 4 | def make_album(artist,album,tracks=''):
"""Return a dictionary containing details about an album"""
album_dict = {'artist': artist.title(), 'album': album.title()}
if tracks:
album_dict['tracks'] = tracks
return album_dict
while True:
print('Please tell me an album: ')
print('(enter "q" to quit at any time')
artist_name = input('Album name: ')
if artist_name == 'q':
break
album_name = input('Artist name: ')
if album_name == 'q':
break
album_info = make_album(artist_name, album_name)
print(album_info)
#old code
# album = make_album('tool','lateralus')
# print(album)
# album = make_album('a perfect circle','mer de noms')
# print(album)
# album = make_album('james blake','james blake','11')
# print(album)
| false |
c67d366da290f642ef05e7b0b4b5e8f8ec0106f9 | VaibhavDhaygonde7/Coding | /Python Projects/P61PythonComphrensions.py | 1,247 | 4.3125 | 4 | # we have to make a list which would store the numbers which are divisble by 3 from 0 to 100
# normal method
ls = []
for i in range(100):
if i % 3 == 0:
ls.append(i)
print(ls)
# by list comphrension method
ls2 = [i for i in range(100) if i%3==0]
# first one is the variable second one is the loop and the third one is the conditional statement which is optional
print(ls2)
# now will make a dictionary which would store a number and the value will be 'item i' where i is the number
# we will do it by dictionary comphrension
dict1 = {i:f"item{i}" for i in range(100) if i % 2 == 0}
# print(dict1)
# first one is the variable second one is the loop and the third one is the conditional statement which is optional
dict2 = {i:f"Item {i}" for i in range(5)}
# reversing the key and value
dict3 = {value:key for key,value in dict2.items()} # we are storing the reverse of dict2 in dict3
print(dict3)
# making a set comphrension
dresses = {dress for dress in ["dress1", "dress2", "dress1", "dress2", "dress1", "dress2"]}
print(dresses)
# we will make a generator comphrension
evens = (i for i in range(100) if i % 2 == 0)
print(type(evens)) # this will print generator object
print(evens.__next__())
print(evens.__next__()) | true |
11f05208d7898d58d0ce0c2e01eab26946f6184c | VaibhavDhaygonde7/Coding | /Python Projects/P13Dictionary.py | 645 | 4.5 | 4 | # we declare dictionary using {} curly braces
d1 = {"Vaibhav":"Paneer", "Ritika":"Pani Puri", "Suresh":"Chocolate", "Vaishali":"Manchurian"}
# remember that dictionary is case-sensitive
print(d1["Vaibhav"]) #this will print Paneer as Vaibhav eats paneer
d2 = {"Virat": {"Breakfast":"Tea", "Lunch":"Roti", "Dinner":"Rice"}}
print(d2["Virat"])
print(d2["Virat"]["Breakfast"])
# adding elements to the dictionary
d2["Ankit"] = "Vada Pav" #this will be added to the end of the dictionary
print(d2) #verifying whether Ankit added or not
#deleting element of the dictionary
del d2["Ankit"] #this will delete Ankit from the dictionary
print(d2) | false |
baf52f942f5ef04e9ab721057366a44b028b2730 | VaibhavDhaygonde7/Coding | /Python Projects/P22ReadinAFile.py | 818 | 4.25 | 4 | f = open("vaibhav.txt", "r") #f is the file pointer
# content = f.read(3) #this will read the content of the file
# print(content)
# content = f.read(3) #this will read 3 characters from the file
# print(content)
# -------------------------- READING LINES FROM A FILE ---------------------------------------- #
# for line in f:
# print(line, end="")
# ------------------------------------READLINE()------------------------------------------------ #
# print(f.readline()) #this will read one line from the file
# print(f.readline())
# -------------------------------------------READLINES()------------------------------------------#
print(f.readlines()) #this will read lines from the file and it will store the line in a list
f.close() #remember to close the file because it is a good practice | true |
f5d065954d4f8a66ee2f800ae0e9a9db1cc809c4 | VaibhavDhaygonde7/Coding | /Python Machine Learning/main.py | 1,875 | 4.28125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error
diabetes = datasets.load_diabetes()
#this will load the data of the diabetes which is already present in the module
# ['data', 'target', 'frame', 'DESCR', 'feature_names', 'data_filename', 'target_filename']
# print(diabetes.keys())
#this will print what is present in the dataset diabetes
# print(diabetes.DESCR) #this will print the description of the data
diabetes_x = diabetes.data
#this will return an array of array using numpy module
# print(diabetes_x)
#declaring the features
diabetes_x_train = diabetes_x[:-30]
#this will slice and take the last 30 features of the diabetes data
diabetes_x_test = diabetes_x[-20:]
#this will slice and take the first 20 features of the diabetes data
#declaring the labels
diabetes_y_train = diabetes.target[:-30]
#remember to take the labels as per the features declared because they are corresponding to each other
diabetes_y_test = diabetes.target[-20:]
#making our linear model
model = linear_model.LinearRegression()
#we are doing here linear regression
model.fit(diabetes_x_train, diabetes_y_train)
#this function is learning the data which is passed to it
diabetes_y_predicted = model.predict(diabetes_x_test)
#here we are testing our machine learning
print("Mean squared error is: ", mean_squared_error(diabetes_y_test, diabetes_y_predicted))
#mean_squared_error() first argument is the test values and the second argument is the predicted value
print("Weights: ", model.coef_)
print("Intercept: ", model.intercept_)
#plotting our values using matplotlib
# plt.scatter(diabetes_x_test, diabetes_y_test)
# plt.plot(diabetes_x_test, diabetes_y_predicted)
# plt.show()
# Mean squared error is: 2561.3204277283867
# Weights: [941.43097333]
# Intercept: 153.39713623331698 | true |
ebb1b44dc2a5d110d0b11cc0b93ba97341f8ab47 | VaibhavDhaygonde7/Coding | /Python Projects/P68OsModule.py | 1,460 | 4.15625 | 4 | import os
# os - operating system
# print(dir(os)) #this will print the functions in the os module
# print(os.getcwd()) #getcwd() means current working directory
# # if we want to read or write a file then python will find the file in the cwd which is current working directory
# # function to change the current working directory
# # os.chdir("") write the file path in the ""
# print(os.listdir()) #this will print all the files in the cwd
# print("\n\n\n")
# print(os.listdir("C://")) #this will print all the files in the C:\
# os.listdir() will return a list
# function to make a new folder
# os.mkdir("NewFolder")
# os.makedirs("NewFolder2/NewFile") #this will make a new folder and store a folder named NewFile in it
# function to rename a file
# os.rename("vaibhav2.txt", "vaibhavtwo.txt")
# function to get the environment variables
# print(os.environ.get('Path'))
# function to get the address of the files
# print(os.path.join("C:/", "vaibhav.txt")) #this will remove all the slash of the names and we get our desired file easily
# function to know if a path exists or not
# print(os.path.exists("C://")) #this will return true is the path exists otherwise false
# function isdir()
# print(os.path.isdir("C://Program Files")) #this will return true if the directory exists otherwise flase
# # function isfile()
# print(os.path.isfile("C://Program Files")) #this will return true if the file exists otherwise flase | true |
c8bee75189d05fd07be7ce2c2662fd984a6a8db9 | Perceu/python-infox | /exemplos/aula6/dojo.py | 790 | 4.3125 | 4 | """
Neste problema, você deverá exibir uma lista de 1 a 100, um em cada linha,
com as seguintes exceções:
Números divisíveis por 3 deve aparecer como 'Fizz' ao invés do numero;
Números divisíveis por 5 devem aparecer como 'Buzz' ao invés do numero;
Números divisíveis por 3 e 5 devem aparecer como 'FizzBuzz' ao invés do numero'.
"""
def fizz3(numero):
if numero % 3 == 0:
return "Fizz"
return ""
def fizzbuzz(numero):
retorno = ""
retorno += fizz3(numero)
if numero%5==0:
retorno += "Buzz"
if retorno == "":
retorno = str(numero)
return retorno
assert fizzbuzz(1)=="1"
assert fizzbuzz(3)=="Fizz"
assert fizzbuzz(5)=="Buzz"
assert fizzbuzz(2)=="2"
assert fizzbuzz(15)=="FizzBuzz"
assert fizzbuzz(9)=="Fizz"
| false |
dbedb431526576ea9db7f23318672699fb32de16 | anastas-ananas/itstep | /lesson4/months_extended.py | 2,589 | 4.375 | 4 | #Тут я вирiшила доповнити завдання months. Я захотiла щоб мiй користувач вводив даннi до того моменту, поки сам не
#захоче вийти з программи, ввiвши значення exit. Попередження про те, що так можна закрити программу з'являться 1 раз
#пiсля першого виводу iнформацiї про мiсяць
show_hint = True
while True:
user_input = input("Enter number from 1 to 12: ")
if user_input == "1":
print("January")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "2":
print("February")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "3":
print("March")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "4":
print("April")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "5":
print("May")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "6":
print("June")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "7":
print("July")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "8":
print("August")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "9":
print("September")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "10":
print("October")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "11":
print("November")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "12":
print("December")
if show_hint:
print("Enter 'exit' if you want to quit")
show_hint = False
elif user_input == "exit":
break
else:
print("You made a mistake, repeat with numbers from 1 to 12")
| false |
39f6ec906a57303fe69a24355a87681bcb912a20 | anastas-ananas/itstep | /lesson10/even_list_generate.py | 708 | 4.125 | 4 | def even_list_generate(num1, num2):
even_number_list = []
# Try/except використовую для того, щоб программа не крашилась коли користувач вводить флоат і видала повідомлення,
# що треба вводити тільки цілі числа
try:
for number in range(num1, num2 +1):
if number < 0:
print("Only whole numbers allowed")
break
elif number %2 == 0:
even_number_list.append(number)
return even_number_list
except TypeError:
print("Only whole numbers allowed")
print(even_list_generate(2, 22))
| false |
4490ca6dead2ae12126e33365a40ac64270f31f5 | avolt1234/CS3180_MiniProject2 | /main.py | 1,864 | 4.125 | 4 | """
Mini Project 2 for Comparative Languages @ Wright State University
Author: Alexander Voultos
Date: 10/14/2019
Tokenizes a string input and displays the value of the tokens
"""
import ply.lex as lex
def lexing(inp):
"""
Function for tokenizing input and displaying token value
:param inp: (String) - Input value for tokenizing
:return: N/A
"""
# Initialize Token names
tokens = ["NUM", "SYM", "ADD", "SUBTRACT", "MULTIPLY", "DIVIDE", "LPAREN", "RPAREN", "ERROR"]
# Used to ignore space values in token
t_ignore = ' \t'
# If error is thrown, display the illegal character
def t_error(t):
print(f'Illegal Character {t}')
# Token logic and regex for ADD
def t_ADD(t):
r'\+'
print('ADD', end=' ')
# Token logic and regex for SUBTRACT
def t_SUBTRACT(t):
r'\-'
print('SUBTRACT', end=' ')
# Token logic and regex for MULTIPLY
def t_MULTIPLY(t):
r'\*'
print("MULTIPLY", end=' ')
# Token logic and regex for DIVIDE
def t_DIVIDE(t):
r'/'
print("DIVIDE", end=' ')
# Token logic and regex for LPAREN
def t_LPAREN(t):
r'\('
print("LPAREN", end=' ')
# Token logic and regex for RPAREN
def t_RPAREN(t):
r'\)'
print("RPAREN", end=' ')
# Token logic and regex for NUM
def t_NUM(t):
r'[0-9]+[.]*[0-9]*'
print("NUM", end=' ')
# Token logic and regex for SYM
def t_SYM(t):
r'[_a-zA-Z][_a-zA-Z]*'
print("SYM", end=' ')
# Build the Lexer
lexer = lex.lex()
# Input data into lexer
lexer.input(inp)
# Tokenize input
while True:
tok = lexer.token()
if not tok:
break
print(tok)
if __name__ == '__main__':
lexing(input("Enter String: "))
#lexing("3 99 5 + 4 * 3 + 44")
| true |
60b2cbb744868b6cd5ee6be1c2fcf4d671e95683 | soundharya99/python | /game.py | 1,098 | 4.28125 | 4 | import random
print("rules for winning paper vs rock =paper,rock vs scissor = rock, paper vs scissor =scissor")
while True:
choice=int(input("user choice"))
while (choice >3 or choice<1):
choice= int(input("enter valid data"))
if(choice == 1):
choice_name="rock"
elif(choice == 2):
choice_name="paper"
else:
choice_name="scissor"
print("user choice is"+choice_name)
print("computer choice")
comp_choice=random.randrange(1,3)
while(comp_choice == choice):
if (comp_choice ==1):
comp_name="rock"
elif(comp_choice== 2):
comp_name="paper"
else:
comp_name="scissor"
if(choice ==1 and comp_choice==2) and (choice == 2 and comp_choice == 1):
print ("paper wins")
result="paper"
elif(choice ==1 and comp_choice==3) and (choice == 3 and comp_choice == 1):
print ("rock wins")
result="paper"
else:
print("scissor wins")
result="scissor"
if(result ==choice_name):
print ("user wins")
else:
print("comp wins")
ans=str(input("enter yes or no to play"))
if (ans=="n"):
break
| true |
c6166415f54e0d71c93c07653e40be98aa4b7a39 | aikinjess/python-containers-lab | /python-containers.py | 975 | 4.21875 | 4 | # Excercise 1
students = ['Jessica', 'Taylor', 'Julia']
print(students[1])
print(students[-1])
# Excercise 2
foods = ['Tacos', 'Oxtails', 'Crab']
for food in foods:
print(f"{food} is a good food!")
# Exercise 3
for food in foods[-2:]:
print(food)
# Exercise 4
home_town = {
'city': 'Saginaw',
'state': 'Michigan',
'population': 50000
}
print(f"I was born in {home_town['city']}, {home_town['state']} - population of {home_town['population']}")
# Exercise 5
for key, value in home_town.items():
print(f"{key} ={value}")
# Exercise 6
cohort = []
for index, student in enumerate(students):
cohort.append({
'student': student,
'fav_food': foods[index]
})
for student in cohort:
print(student)
# Exercise 7
awesome_students = [f"{name} is awesome!" for name in students]
for student in awesome_students:
print(student)
# Exercise 8
for food in [food for food in foods if 'a' in food]:
print(food)
| false |
1a814513f99c6e63aa2c8bd76fc0851331dcb4f4 | django-group/python-itvdn | /домашка/starter/lesson 5/Sokolov Aleksandr/Task_3.py | 888 | 4.125 | 4 | def oper_plus(a, b):
return a + b
def oper_minus(a, b):
return a - b
def oper_multiplication(a, b):
return a * b
def oper_divizion(a, b):
return a / b
while True:
op = input('Enter operation sign(+,-,*,/): ')
if op == 'exit':
break
if op in ('+', '-', '*', '/'):
x = float(input('Enter 1-st number x = '))
y = float(input('Enter 2-nd number y = '))
if op == '+':
print('Summ = %.2f' % oper_plus(x, y))
elif op == '-':
print('Разность = %.2f' % oper_minus(x, y))
elif op == '*':
print('Multiplication = %.2f' % oper_multiplication(x, y))
elif op == '/':
if y != 0:
print('Division = %.2f' % oper_divizion(x, y))
else:
print('Division by zero!')
else:
print('You entered an invalid operation sign!') | false |
1d9ed26dfde374ff8bd91f70dcc37bcd20a4b7be | django-group/python-itvdn | /домашка/starter/lesson 7/MaximKologrimov/Task dop.py | 565 | 4.25 | 4 | # Задание
# Создайте список, введите количество его элементов и сами значения, выведите эти значения на
# экран в обратном порядке.
from random import randint
list = [randint(1, 100) for x in range(10)]
num = 0
for x in list:
num = num + 1
print(f'{num} >> {x}')
print()
print(f'Кол-во элементов: {len(list)}')
print(f'Сами элементы: {list}')
print(f'Перевернутый список: {list[::-1]}') | false |
afbe8d3ae14c4a4f9538661a461ee758c78e0873 | django-group/python-itvdn | /домашка/starter/lesson 4/KologrimovMaxim/Task 3.py | 353 | 4.53125 | 5 | #Задание 3
#Используя вложенные циклы и функции print(‘*’, end=’’), print(‘ ‘, end=’’) и print() выведите на
#экран прямоугольный треугольник.
for n in range(6):
for m in range(n):
print('*', end='')
print(' ', end='')
print() | false |
497a08d0ecd53d89f10fa535e16cf03061c92138 | django-group/python-itvdn | /домашка/essential/lesson 8/Pavel K/hw_16_4.py | 798 | 4.125 | 4 | # Создайте список товаров в интернет-магазине. Сериализуйте и сохраните его при помощи pickle и JSON.
import json
import pickle
shop_list = {
'pickle':'50 jar',
'bananas':'10 box',
'milk':'50 bottle'
}
################json#################################
with open('D:\\random.txt', 'w') as k:
json.dump(shop_list, k) # record to json
with open('D:\\random.txt', 'r') as k1:
after_save = json.load(k) # reading from json
print(after_save)
####################pickle###########################
with open('D:\\data.pickle', 'wb') as pic:
pickle.dump(shop_list, pic)
with open('D:\\data.pickle', 'rb') as pic2:
after_save_p = pickle.load(pic2)
print(after_save_p)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.