blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0e21ece8f07b4abc07641459cc09d68cc31f351c | Nam1130Tx/Python | /Python Assignments/PY_Class_Assignment.py | 1,304 | 4.125 | 4 | # Python: 3.8.5
# Name: Nicholas Mireles
# Assignment: Class Assignment
class instrument():
def __init__(self, name, section, band):
self.name = name
self.section = section
self.band = band
class strings( instrument ):
def __init__(self, name, section, band, play, strNum):
self.play = play
self.stringNumber = strNum
instrument.__init__(self, name, section, band)
def display(self):
print("The", self.name,"is a member of the", self.section, "family used in", self.band, "bands." \
" It is played by", self.play, "over", self.stringNumber, "string's.")
class brass( instrument ):
def __init__(self, name, section, band, bore, note):
self.bore = bore
self.note = note
instrument.__init__(self, name, section, band)
def display(self):
print("The", self.name,"is a member of the", self.section, "family used in", self.band, "bands." \
"It has a", self.bore, "bore, and uses", self.note, "to change pitch.")
b = strings("double bass","strings","symphonic","bowing","six")
b.display()
t = brass("trombone","brass","concert","cylindrical","slides")
t.display()
| false |
73d4dbc12fed8bc83ac68f19a31a729283c9a05f | cascam07/csf | /hw2.py | 2,244 | 4.34375 | 4 | # Name: ... Cameron Casey
# Evergreen Login: ... cascam07
# Computer Science Foundations
# Programming as a Way of Life
# Homework 2
# You may do your work by editing this file, or by typing code at the
# command line and copying it into the appropriate part of this file when
# you are done. When you are done, running this file should compute and
# print the answers to all the problems.
## Hello!
###
### Problem 1
###
# DO NOT CHANGE THE FOLLOWING LINE
print "Problem 1 solution follows:"
import hw2_test
i = 1
x = 0
while (i<=hw2_test.n):
x = x + i
i=i+1
print x
###
### Problem 2
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 2 solution follows:"
for t in range(2,11):
print '1/',t
###
### Problem 3
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 3 solution follows:"
n = 10
triangular = 0
for i in range(n+1):
triangular = triangular + i
print "Triangular number", n, "via loop:", triangular
print "Triangular number", n, "via formula:", n*(n+1)/2
###
### Problem 4
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 4 solution follows:"
n = 10
factorial = 1
for i in range(1,n+1):
factorial = factorial*i
print n, "factorial:", factorial
###
### Problem 5
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 5 solution follows:"
n = 10
for counter in range(n): #execute inner loop 10 times
factorial = 1
for i in range(1,n+1): #computes n factorial
factorial = factorial*i
print factorial
n=n-1
###
### Problem 6
###
# DO NOT CHANGE THE FOLLOWING LINE
print "\n"
print "Problem 6 solution follows:"
reciprocal = 1
n = 10
for counter in range(n): #execute inner loop n times
factorial = 1.0
for i in range(1,n+1): #adds up 1/n!
factorial = factorial*i
reciprocal = reciprocal + (1/factorial)
n=n-1
print reciprocal
###
### Collaboration
###
# ... List your collaborators and other sources of help here (websites, books, etc.),
# ... as a comment (on a line starting with "#").
###
### Reflection
###
# ... The assignment took me around 3 hours. It would have been helpful to get
# ... some examples of how to use for loops in class before spending so much
# ... time on the code critique.
| true |
8bbd6935cc49c5280a79327c61d90ffb2ef5889c | Skp80/mle-tech-interviews | /data-structure-challenges/leetcode/543. Diameter of Binary Tree.py | 1,658 | 4.25 | 4 | """
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3is the length of the path [4,2,1,3] or [5,2,1,3].
Example 2:
Input: root = [1,2]
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 104].
-100 <= Node.val <= 100
Learning:
- Solution must be between 2 leaf nodes
- Recursion. O(n)
"""
from typing import List
class TreeNode:
"""Definition for a binary tree node."""
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
diameter = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self._longest_path(root)
return self.diameter
def _longest_path(self, node):
if not node:
return 0
left_path = self._longest_path(node.left)
right_path = self._longest_path(node.right)
self.diameter = max(self.diameter, left_path + right_path)
return max(left_path, right_path) + 1
tree = TreeNode(val=1)
tree.left = TreeNode(val=2)
tree.right = TreeNode(val=3)
tree.left.left = TreeNode(val=4)
tree.left.right = TreeNode(val=5)
sol = Solution().diameterOfBinaryTree(root=tree)
print(sol == 3)
tree = TreeNode(val=1)
tree.left = TreeNode(val=2)
sol = Solution().diameterOfBinaryTree(root=tree)
print(sol == 1)
| true |
9086e676e72f459b15df69d93859f939f4cb4a0f | starFaby/cursoPython | /parte 20 - 30/iConjuntos.py | 930 | 4.21875 | 4 | # Conjuntos
# Conjuntos nos muestra cunado existe un numero repetitivo ya no se mostarar lo quitara
print('Conjuntos nos muestra cunado existe un numero repetitivo ya no se mostarar lo quitara')
conjunto = set()
conjunto = {1,2,3,4,5,1}
conjunto.add(4)
conjunto.add(6)
print(conjunto)
# Para quitar del conjunto
print('Para quitar del conjunto')
conjuntoA = set()
conjuntoA = {1,2,3}
conjuntoA.discard(1)
print(conjuntoA)
# Para limpiar un conjunto
print('Para limpiar un conjunto')
conjuntoB = set()
conjuntoB = {1,2,3}
conjuntoB.clear()
print(conjuntoB)
# Para Buscar en un conjunto
print('Para Buscar en un conjunto')
conjuntoB = set()
conjuntoB = {1,2,3}
conjuntoB1 = 1 in conjuntoB
print(conjuntoB1)
# Existe el item en un conjunto pero lo niega y lo manda false
print('Existe el item en un conjunto pero lo niega y lo manda false')
conjuntoB = set()
conjuntoB = {1,2,3}
conjuntoB1 = 1 not in conjuntoB
print(conjuntoB1) | false |
f0881f9ec77a982825071ed8106c4900278ac1a5 | vuthysreang/python_bootcamp | /sreangvuthy17/week01/ex/17_str_last.py | 625 | 4.40625 | 4 | """ Description : You will write a program that ask for one string as and return the last character.
If no argument is passed, display “Empty”
Requirements : ● Program must be named : 17_str_last.py and saved into week01/ex folder
Hint : ❖ print function
❖ string index
"""
# user input
strInput = input("Enter a string: ")
# check the condition again
if strInput == "":
# print output
print("Empty")
else:
# reverse the strInput
x = strInput[::-1]
# print output (we want to print the last character of the string)
print(x[0])
| true |
b09cbe34ac66a41d58ab047f0dfbb6024c9a105e | vuthysreang/python_bootcamp | /Documents/week03/sreangvuthy17/week03/ex/45_auto_folder.py | 2,173 | 4.46875 | 4 | """
Description : You will create a program that take a list of string as argument, that represents folders names.
Then, for each, you will create a folder with the corresponding name.
Before create anything, you will check that the folders doesn’t already exists.
If they, you will ask: “Are you sure you want to replace <FOLDER_NAME>? [Y/N]”
If the user enter anything that is not Y or N, you will write:
“Invalid Option” and then print the confirmation message again:
“Are you sure you want to replace <FOLDER_NAME>? [Y/N]”
Make sure that you ask for EVERY folders that already exist only.
Be careful with this program and don’t delete your work!
At the end, if your program did create any new folder you will return 1 Else you will return 0.
If the list of folder name is empty, your program will also return 0.
Requirements : ● Program name : 45_auto_folder.py
● Function name : auto_folder
● Directory : week03/ex folder
Hint : ❖ os library
"""
import os
import shutil
def auto_folder(mylist_folder):
modification = 0
if mylist_folder == []:
return 0
for foldername in mylist_folder:
if not os.path.exists(foldername):
os.makedirs(foldername)
modification = 1
elif os.path.exists(foldername):
while True:
user_input = input("Are you sure you want to replace " + str(foldername) + "? [Y/N]\n>> ")
if (user_input == "Y" or user_input == "y"):
shutil.rmtree(foldername)
os.makedirs(foldername)
modification = 1
break
elif (user_input == "N" or user_input == "n"):
break
else:
print(">> Invalid Option")
return modification
#auto_folder(["new_folder_name", "second_folder", "third_folder"])
#auto_folder([])
| true |
201dac84630f55ffceb24392cd58051b66e60495 | vuthysreang/python_bootcamp | /sreangvuthy17/week01/ex/08_random.py | 465 | 4.28125 | 4 | """ Description : You will write a program that take display a random number between 1 and 100
Requirements : ● Program must be named : 08_random.py and saved into week01/ex folder
Hint : ❖ print function
❖ random
"""
# import random library
import random
# print random output between 1 and 100
print(random.randint(1,100))
# another way
# x = random.randrange(1,101) or x = random.randint(1,100)
# print(x)
| true |
421e2d5f4300102b66651efd180d3dbd6bf66a82 | vuthysreang/python_bootcamp | /sreangvuthy17/week01/ex/06_odd_even.py | 1,491 | 4.46875 | 4 | """ Description : You will write a program that take will ask for a number in parameter and display “<number> is EVEN” or “number is ODD”.
If the number is not an integer, you will have to display “<input> is not a valid number.”.
If you enter “exit” or “EXIT” the program will quit. Else the program will continue ask you for a number.
Requirements : ● Program must be named : 06_odd_even.py and saved into week01/ex folder
Hint : ❖ print function
❖ input function
❖ arithmetic operators ❖ conditions
"""
# assign the True variable
program_is_running = True
# check the loop True or False
while (program_is_running == True):
# user input
n = input("Enter a number:\n>> ")
# check the condition
if n == "EXIT" or n == "exit":
# If program_is_running is False the program will be break
program_is_running = False
# check he condition again (check if digit or not)
elif n.isdigit():
# convert string to integer or number
num = int(n)
# check the condition again (check is even or not)
if (num % 2 == 0):
print(n+" is EVEN")
# check the condition again (check is odd or not)
else:
print(n+" is ODD")
# check the condition again after above "EXIT" or "exit"
else:
print(n+" is not a valid number.")
| true |
926c19499256827be9c6f281257082f307432908 | vuthysreang/python_bootcamp | /Documents/week03/sreangvuthy17/week03/ex/59_regex_html.py | 1,235 | 4.1875 | 4 | """
Description : You will create a function that take a string in parameter and remove every HTML content ( everything between ‘<’ and ‘>’ ) You will return the new formatted string.
You need to do it using REGEX only.
EXAMPLE :
regex_html("<html lang = 'pl' ><body> content of body </body> ... </html>")
⇒ " content of body ..."
regex_html("<h1>hello</h1> <p>hello</p>")
⇒ "hello hello"
regex_html("")
⇒ ""
regex_html("hello")
⇒ "hello"
regex_html("<<><>>><>")
⇒ ">>"
Requirements : ● Program name : 59_regex_html
● Function name : regex_html
● Directory : week03/ex folder
Hint : ❖ re
❖ sub
"""
import re
def regex_html(mystr):
print('regex_html("' + str(mystr) + '")')
final_str = re.sub(r'<.*?>', '', mystr)
print('=> "' + str(final_str) + '"')
return final_str
# regex_html("<html lang = 'pl' ><body> content of body </body> ... </html>")
# regex_html("<<><>>><>")
| true |
a287483a91fa92fd183f524039b0255d4ea11f7d | vuthysreang/python_bootcamp | /sreangvuthy17/week02/ex/35_current_time.py | 1,079 | 4.3125 | 4 | """
Description : You will write a function that return the current time with the following format: hh:mm:ss The return value must be a string.
Requirements : ● Program must be named : 35_current_time.py and saved into week02/ex folder
Hint : ❖ function
❖ datetime
Output :
current_time()
>> 04:59:40
"""
from datetime import datetime
from datetime import time
from datetime import date
# Define current_time() method/function
def current_time():
# inside the function/method
# print output
print('current_time()')
# declare (my_current_time) and to assign current time with only time format: hh:mm:ss
my_current_time = datetime.time(datetime.now())
# convert time format into string format
my_current_time = my_current_time.strftime("%H:%M:%S")
# print output of (my_current_time)
print(">> " + str(my_current_time))
# return output of (my_current_time)
return my_current_time
# outside the function/method
# call the current_time() function/method
current_time()
| true |
0613d7beaa42dfe4acbccbcd93a154f788ba7c6f | vuthysreang/python_bootcamp | /sreangvuthy17/week03/ex/41_current_path.py | 577 | 4.15625 | 4 | """
Description : You will write a function that print the current path of your program folder, then you will return it as a string.
Requirements : ● Program name : 41_current_path.py
● Function name : current_path
● Directory : week03/ex folder
Hint : ❖ os library
❖ os path
"""
import os
def current_path():
my_current_path = os.getcwd()
print("My current path of my program folder is:\n>> " + str(my_current_path))
return str(my_current_path)
#current_path()
| true |
aa27c29c3a7884b708bcb5490e6698ad96ec275b | Wright2533/cti110 | /P2HW1_CelsiusConverter(Resubmit)_ShawnWright.py | 374 | 4.28125 | 4 | # Celsius Fahrenheit Converter
# 9/10/18
# CTI-110 P2HW1 - Celsius Fahrenheit Converter
# Shawn Wright
#
#temperature in celcius c= celcius
c = float(input('Enter temperature in celsius: '))
#convert farenheit F = Fahrenheit FE = 9/5c
FE = c* 1.8
F = FE + 32
#show the conerted temperature in Farenheit
print('temperature in Farenheit is', F)
| false |
a075edb4de5ac8b34032dd82dee03978fbf0b6ac | anversa-pro/ejerciciosPython | /excepciones.py | 1,665 | 4.21875 | 4 | #usr/bin/python
# -*- coding: utf -*-
print(""" Lo que hace try es ejecutar un bloque de sentencias en un “entorno controlado”, para que el error generado (si se da) no detenga el programa, sino que se retorne de modo que pueda manejarse.
Por ejemplo, el clasico error de la division por 0 hara que el programa falle y se detenga en ese punto. sin embargo con el uso de try podemos evitar la interrupcion del programa """)
print("")
dividendo = 1
divisor = 0
try:
resultado = dividendo/divisor
print("La división resulta: ", resultado)
except:
if divisor == 0:
print("No puedes dividir por cero")
print("Hemos terminado")
print("")
print("""python tiene una forma mas concreta de manejar los errores usando el o los tipos de error que se quieran manejar """)
print("")
dividendo = "A"
divisor = 2
try:
resultado = dividendo/divisor
print("La división resulta: ", resultado)
except ZeroDivisionError:
if divisor == 0:
print("No puedes dividir por cero")
except TypeError:
print("Hay que ser bruto: eso no es un número")
print("")
print("Cada uno de los bloques except se ejecuta solo si se da el tipo de error especificad")
print("")
dividendo = 1
divisor = 2
try:
resultado = dividendo/divisor
except ZeroDivisionError:
if divisor == 0:
print("No puedes dividir por cero, animal")
except TypeError:
print("Hay que ser bruto: eso no es un número")
else:
print("La división resulta: ", resultado)
print("")
print("Es importante hacer notar que dentro del try hemos dejado solo la instrucción que requiere que verifiquemos, dejando el print en el else final") | false |
9e2f2ccb0e7c1f8103abb86d1581e24ca4d03f3d | aengel22/Homework_Stuff | /module12_high_low.py | 2,532 | 4.21875 | 4 | # The get_price function accepts a string that is assumed to be
# in the format MM-DD-YYYY:Price. It returns the Price component
# as a float.
def get_price(str):
# Split the string at the colon.
items = str.split(':')
# Return the price, as a float.
return float(items[1])
# The get_year function accepts a string that is assumed to be
# in the format MM-DD-YYYY:Price. It returns the YYYY component
# as an int.
def get_year(str):
# Split the string at the colon.
items = str.split(':')
# Split the date item at the hyphens.
date_items = items[0].split('-')
# Return the year, as an int.
return int(date_items[2])
# The display_highest_per_year function steps through the gas_list
# list, displaying the highest price for each year.
def display_highest_per_year(gas_list):
current_year = get_year(gas_list[0])
highest = get_price(gas_list[0])
for e in gas_list:
if get_year(e) == current_year:
if get_price(e) > highest:
highest = get_price(e)
else:
print('Highest price for ', current_year, ': $',
format(highest, '.2f'), sep='')
current_year = get_year(e)
highest = get_price(e)
# Display the highest for the last year.
print('Highest price for ', current_year, ': $',
format(highest, '.2f'), sep='')
# The display_lowest_per_year function steps through the gas_list
# list, displaying the lowest price for each year.
def display_lowest_per_year(gas_list):
current_year = get_year(gas_list[0])
lowest = get_price(gas_list[0])
# Step through the list.
for e in gas_list:
if get_year(e) == current_year:
if get_price(e) < lowest:
lowest = get_price(e)
else:
print('Lowest price for ', current_year, ': $',
format(lowest, '.2f'), sep='')
current_year = get_year(e)
lowest = get_price(e)
# Display the lowest for the last year.
print('Lowest price for ', current_year, ': $',
format(lowest, '.2f'), sep='')
def main():
# Open the file.
gas_file = open('GasPrices.txt', 'r')
# Read the file's contents into a list.
gas_list = gas_file.readlines()
# Display the highest prices per year.
display_highest_per_year(gas_list)
# Display the lowest prices per year.
display_lowest_per_year(gas_list)
main()
| true |
55ebfed116af1e9389e2a81d432a237b90e7262e | RecklessDunker/Codewars | /Get the Middle Character.py | 789 | 4.25 | 4 | # --------------------------------------------------------
# Author: James Griffiths
# Date Created: Wednesday, 3rd July 2019
# Version: 1.0
# --------------------------------------------------------
#
# You are going to be given a word. Your job is to return the middle character of the
# word. If the word's length is odd, return the middle character. If the word's length
# is even, return the middle 2 characters.
def get_middle(s):
# your code here
wordlen = len(s)
if wordlen % 2 == 0:
# is even, so find middle two characters
middlechar = s[len(s) // 2 - 1] + s[len(s) // 2]
else:
# is odd, so find the middle letter
middlechar = s[len(s) // 2]
return middlechar
midchar = get_middle(input("Please type in a word: "))
print(midchar)
| true |
deec653fc1bbe1f2ff5d32d2970265a89e68b7b0 | cthompson7/MIS3640 | /Session01/hello.py | 2,277 | 4.59375 | 5 | print("Hello, Christian!")
# Whenever you are experimenting with a new feature, you should try to make mistakes. For example, in the “Hello, world!” program, what happens if you leave out one of the quotation marks? What if you leave out both? What if you spell print wrong?
print(Hello, world!")
# When I leave out one of the quotation marks, I get the following error, SyntaxError: invalid syntax/
print(Hello, world!)
# When I leave out both of the quotation marks, I get the following error, SyntaxError: invalid syntax/
prin("Hello, world!")
# When I spell print wrong, I get the following error, NameError: name 'prin' is not defined
# Exercise 1
# 1.) In a print statement, what happens if you leave out one of the parentheses, or both? */
print("Hello, world!"
# When I leave out one of the parentheses, as shown above, I get the following error, SyntaxError: unexpected EOF while parsing
print"Hello, world!"
# When I leave out both of the parentheses, as shown above, I get the following error, SyntaxError: invalid syntax
# 2.) If you are trying to print a string, what happens if you leave out one of the quotation marks, or both?
print(Hello")
# When trying to print a string, if I left out one of the quotation marks, I get the following error, SyntaxError: EOL while scanning string literal
print(Hello)
# When trying to print a string, if I left out both of the quotation marks, I get the following error, NameError: name 'Hello' is not defined
# 3.) You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2?
print(+2)
# If you put a plus sign before a number like 2, as shown above, you get an output of 2.
print(2++2)
# If you try to perform 2++2, as shown above, you get the following error, SyntaxError: invalid syntax
# 4.) In math notation, leading zeros are ok, as in 02. What happens if you try this in Python?
print(02)
# When you try to include leading zeros, as shown above, you get the following error, SyntaxError: invalid token
# 5.) What happens if you have two values with no operator between them?
print(2 5)
# When you have two values with no operator between them, as shown above, you get the following error, SyntaxError: invalid syntax | true |
e2ae0826393ebf746222d47506a538662f0c4016 | cthompson7/MIS3640 | /Session11/binary_search.py | 1,069 | 4.28125 | 4 | def binary_search(my_list, x):
'''
this function adopts bisection/binary search to find the index of a given
number in an ordered list
my_list: an ordered list of numbers from smallest to largest
x: a number
returns the index of x if x is in my_list, None if not.
'''
left = 0
right = len(my_list)-1
middle = int((left+right)/2)
if x not in my_list:
return None
while (right - left > 1):
if my_list[middle] == x:
return middle
elif my_list[middle] > x:
right = middle
middle = int((left+right/2))
elif my_list[middle] < x:
left = middle
middle = int((left+right/2))
if my_list[right] == x:
return right
elif my_list[left] == x:
return left
test_list = [1, 3, 5, 235425423, 23, 6, 0, -23, 6434]
test_list.sort()
print(binary_search(test_list, -23))
print(binary_search(test_list, 0))
print(binary_search(test_list, 235425423))
print(binary_search(test_list, 30))
# expected output
# 0
# 1
# 8
# None
| true |
d2c3f792c5b41ff79f7d6f7fa76c75317c6687be | aleperno/blog | /fibo.py | 1,313 | 4.25 | 4 | #!/usr/bin/python
import time
def recursiveFibo(number):
"""Recursive implementation of the fibonacci function"""
if (number < 2):
return number
else:
return recursiveFibo(number-1)+recursiveFibo(number-2)
def iterativeFibo(number):
list = [0,1]
for i in range(2,number+1):
list.append(list[i-1]+list[i-2])
return list[number]
def main():
print "Calculating the fibonacci of 4 by recursion"
exetime = time.time()
print "The fibonacci of 4 is: ",recursiveFibo(4)
print "The execution lasted: ",time.time()-exetime," seconds"
print "-----------------------------------------------------"
print "Calculating the fibonacci of 4 by iteration"
exetime = time.time()
print "The fibonacci of 4 is: ",iterativeFibo(4)
print "The execution lasted: ",time.time()-exetime," seconds"
print "#####################################################"
print "Calculating the fibonacci of 40 by recursion"
exetime = time.time()
print "The fibonacci of 40 is: ",recursiveFibo(40)
print "The execution lasted: ",time.time()-exetime," seconds"
print "-----------------------------------------------------"
print "Calculating the fibonacci of 40 by iteration"
exetime = time.time()
print "The fibonacci of 40 is: ",iterativeFibo(40)
print "The execution lasted: ",time.time()-exetime," seconds"
main() | true |
7850a710550a6bba787f81b5945d70098c60ba14 | jradd/small_data | /emergency_map_method.py | 518 | 4.46875 | 4 | #!/usr/bin/env python
'''
the following is an example of map method in python:
class Set:
def __init__(self, values=None):
s1 = []
# s2 = Set([1,2,2,3])
self.dict = {}
if values is not None:
for value in values:
self.add(value)
def __repr__(self):
return "Set: " + str(self.dict.keys())
def add(self, value):
self.dict[value] = True
print("OOPs")
def contains(self, value):
return value in self.dict
def remove(self, value):
del self.dict[value]
'''
| true |
28aa9e66286818d5ee939a6016df3dbe5490a265 | xxpasswd/algorithms-and-data-structure | /other/queue.py | 1,334 | 4.21875 | 4 | '''
python 队列实现
is_empty():O(1)
enqueue(item):O(n)
dequeue(item):O(1)
size():O(1)
'''
class Queue:
def __init__(self):
self._queue = []
def is_empty(self):
return self._queue == []
def enqueue(self, item):
self._queue.insert(0, item)
def dequeue(self):
return self._queue.pop()
def size(self):
return len(self._queue)
'''
双端队列实现
add_front(item):O(n)
add_rear(item):O(1)
remove_front():O(n)
remove_rear():O(1)
is_empty():O(1)
size():O(1)
'''
class Deque:
def __init__(self):
self._deque = []
def add_front(self, item):
self._deque.insert(0, item)
def add_rear(self, item):
self._deque.append(item)
def remove_front(self):
return self._deque.pop(0)
def remove_rear(self):
return self._deque.pop()
def is_empty(self):
return self._deque == []
def size(self):
return len(self._deque)
"""
用双端队列实现回文检测
"""
def palchecker(astring):
chardeque = Deque()
for i in astring:
chardeque.add_rear(i)
stillequel = True
while chardeque.size()>1 and stillequel:
front = chardeque.remove_front()
rear = chardeque.remove_rear()
if front != rear:
stillequel = False
return stillequel
| false |
95a3aa9fbc89837526c1f3e4dd44e85783176f20 | bhaumik1991/Python-Basic-Programs | /prime_number.py | 481 | 4.1875 | 4 | #Python program to print all Prime numbers in an interval
n = int(input("Enter the number of terms:"))
for num in range(2,n+1):
for i in range(2,num):
if num%i == 0:
break
else:
print(num)
#Python Program to check Prime Number
n = int(input("Enter a number:"))
if n>1:
for i in range(2,n):
if (n%i==0):
print("Not a prime number")
break
else:
print("Prime number")
else:
print("Prime number") | false |
925ffcfcff7df4ee4db086783374321ee32f092a | Andreabrian/python-programming-examples-on-lists | /assign1.py | 295 | 4.21875 | 4 | #find the largest number in the list.
a=[]
n=int(input("Enter the number of elements:"))
for i in range(n):
a.append(int(input("enter new element:")))
print(a)
s=a[0]
for i in range(1,len(a)):
if a[i]>s:
s=a[i]
y=("the largest number is: ")
print(y,s)
| true |
5f498fc6d83701963d4800d121630523e805568b | chriskok/PythonLearningWorkspace | /tutorial11-tryelsefinally.py | 1,333 | 4.4375 | 4 | # ---------- FINALLY & ELSE ----------
# finally is used when you always want certain code to
# execute whether an exception is raised or not
num1, num2 = input("Enter to values to divide : ").split()
try:
quotient = int(num1) / int(num2)
print("{} / {} = {}".format(num1, num2, quotient))
except ZeroDivisionError:
print("You can't divide by zero")
# else is only executed if no exception was raised
else:
print("You didn't raise an exception")
finally:
print("I execute no matter what")
# ---------- PROBLEM EXCEPTIONS & FILES ----------
# 1. Create a file named mydata2.txt and put data in it
# 2. Using what you learned in part 8 and Google to find
# out how to open a file without with try to open the
# file in a try block
# 3. Catch the FileNotFoundError exception
# 4. In else print the file contents
# 5. In finally close the file
# 6. Try to open the nonexistent file mydata3.txt and
# test to see if you caught the exception
try:
myFile = open("mydata.txt", encoding="utf-8")
# We can use as to access data and methods in the
# exception class
except FileNotFoundError as ex:
print("That file was not found")
# Print out further data on the exception
print(ex.args)
else:
print("File :", myFile.read())
myFile.close()
finally:
print("Finished Working with File")
| true |
1d1b0213e352a561d37417353719711b31bd3de4 | chriskok/PythonLearningWorkspace | /primenumber.py | 696 | 4.34375 | 4 | # Note, prime can only be divided by 1 and itself
# 5 is prime because only divided by 1 and 5 - positive factor
# 6 is not a prime, divide by 1,2,3,6
# use a for loop and check if modulus == 0 True
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
def get_prime(max_number):
list_of_primes = []
for num1 in range(2, max_number):
if is_prime(num1):
list_of_primes.append(num1)
return list_of_primes
# Ask the user to type in the maximum prime
max_prime = input("Insert max prime: ")
max_prime = int(max_prime)
primes_list = get_prime(max_prime)
for prime in primes_list:
print(prime)
| true |
8d598dc40e8428a74f5668cc6b6a29a86214e9bd | chriskok/PythonLearningWorkspace | /pinetree.py | 1,026 | 4.3125 | 4 | # How tall is the tree: 5
# 1 while loop and 3 for loops
#
###
#####
#######
#########
#
# 4 spaces: 1 hash
# 3 spaces: 3 hashes
# 2 spaces: 5 hashes
# ...
# 0 spaces: 9 hashes
# Need to do
# 1. Decrement spaces by 1 each time through the loop
# 2. Increment the hashes by 2 each time through the loop
# 3. Save spaces to the stump by calculating tree height
# 4. Decrement from tree height until it equals 0
# 5. Print spaces and then hashes for each row
# 6. Print stump spaces and then 1 hash
# Note: print('', end="") for space with no new line
# get user input
height = input("What is the height of your tree: ")
height = int(height)
initialSpaces = height - 1
increment = 1
# While loop checking going from height to 0
while height > 0:
spaces = height - 1
for s in range(spaces):
print(' ', end="")
for j in range(increment):
print('#', end="")
print('')
increment += 2
height -= 1
for s in range(initialSpaces):
print(' ', end="")
print('#', end="")
| true |
cd6759aa55356291bb5b1f277fd8f0a88f950be1 | TapasDash/Python-Coding-Practice | /oddEvenList.py | 519 | 4.1875 | 4 | '''
This is a simple programme which takes in input from the user as a series of numbers
then, filter out the even and odd ones and
append them in two different lists naming them oddList and evenList
Input : 1,2,3,4,5,6
Output : oddList = [1,3,5]
evenList = [2,4,6]
'''
myList = [eval(x) for x in input("Enter series of numbers = ").split(",")]
oddList = []
evenList = []
for x in myList:
if(x % 2 == 0):
evenList.append(x)a
else:
oddList.append(x)
print("Odd List=",oddList)
print("Even List=",evenList)
| true |
04edbaa127a19c39abb58fc4ab009161ddd40aee | rexarabe/Python_Projects | /class_01.py | 1,414 | 4.53125 | 5 | """Creating and using class """
#The car class
class Car():
""" A simple attemt to model a car. """
def __init__(self, make, model, year):
"""Initialize car attributes."""
self.make = make
self.model = model
self.year = year
#Fuel capacity and level in gallons.
self.fuel_capacity = 15
self.fuel_level = 0
def fill_tank(self):
"""Fill gas tank to capacity. """
self.fuel_level = self.fuel_capacity
print("Fuel tank is full.")
def drive(self):
""" Simulate driving."""
print("The car is moving.")
#creating and using a class
my_car = Car('audi' , 'a4', 2016)
print(my_car.make)
print(my_car.model)
print(my_car.year)
#calling methods
my_car.fill_tank()
my_car.drive()
my_new_car = Car('peugeot' , '205' , 1997)
my_new_car.fuel_level = 5
#Writing a method to update an attribute's value
def update_fuel_level(self, new_level):
""" Update the fuel level. """
if new_level <= self.fuel_capacity:
self.fuel_level = new_level
else:
print("The tank can't hold that much!")
def update_fuel_level(self, amount):
""" Add Fuel to the tank."""
if (self.fuel_level + amount
<= self.fuel_capacity):
self.fuel_level += amount
print("Added fuel.")
else:
print("The tank won't hold that much.")
| true |
b71c815fa1f8167c8594774745dfccef3931add9 | mustafaAlp/StockMarketGame | /Bond.py | 1,075 | 4.3125 | 4 | #!/usr/bin/env python
"""
This module includes Bond class which is a subclass of the Item class.
Purpose of the module to learn how to use
inheritance and polymorphizm in the python.
Its free to use and change.
writen by Mustafa ALP.
16.06.2015
"""
import random as ra
from Item import Item
#
#
# object
#
#
class Bond(Item):
"""
subclass Bond derived from Item superclass
purpose of the Bond class:
to learn inheritance and polymorphizm in python
"""
def __init__(self):
super(Bond, self).__init__()
self._name = 'bond'
#
# object property
#
def name():
doc = """The name property, keeps name of the Item and can't be changed"""
def fget(self):
return self._name
return locals()
name = property(**name())
#
# object static method
#
@staticmethod
def setWorth():
"""changes worth of Bond items"""
Bond._worth = ra.randint(25, 75)
#
# object static method
#
@staticmethod
def worth():
"""@return worth of Bond items"""
return Bond._worth
| true |
26c3e650eddb2c736279bccc1f8c99c5c6f794aa | rlopezb115/CursoPython | /4. HerramientasControlFlujo/b_FuncionRANGE.py | 1,099 | 4.125 | 4 | print('Inicio...')
print('\nSecuencia de números, básico')
# único parámetro, indica el final y no es parte de la secuencia.
for num in range(10):
print('Número: ', num)
print('\nSecuencia de número, empieza con otro rango.')
# Primer parámetro indica el comienzo del rango.
# Segundo parámetro indica el final y no es parte de la secuencia.
for num in range(1, 10):
print('Número: ', num)
print('\nSecuencia de número, empieza con otro valor en rango e incremento.')
# Primer parámetro indica el comienzo del rango.
# Segundo parámetro indica el final y no es parte de la secuencia.
# Tercer parametro, indica el incremento
for num in range(1, 10, 2):
print('Número: ', num)
print('\nSecuencia de número, con valores negativos')
for num in range(10, -10, -2):
print('Número: ', num)
print('\nIndice de una Secuencia, combinando range() y len()')
colores = ['amarillo', 'azul', 'rojo', 'verde', 'negro', 'morado']
for indice in range(len(colores)):
print(indice, colores[indice])
print(sum(range(0, 10, 2)))
print(list(range(0, 10, 2)))
print('\n...final') | false |
4aa65e5ce29cd4fae61a8e321842cf2b11af1eee | fernandezfran/python_UNSAM | /ejercicios/Clase12/burbujeo.py | 1,362 | 4.53125 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def ord_burbujeo(lista):
"""
Ordenamiento por burbujeo. O(N^2)
Pre: los elementos de la lista deben ser comparables
Post: la lista está ordenada
Devuelve la cantidad de comparaciones realizadas
"""
#comparaciones = 0
n = len(lista) - 1
while (n > 0):
for i in range(n):
a = lista[i]
b = lista[i+1]
#comparaciones += 1
if a > b:
lista[i+1] = a
lista[i] = b
n -= 1
#return comparaciones
if __name__ == '__main__':
lista_1 = [1, 2, -3, 8, 1, 5]
print("lista = ", lista_1)
ord_burbujeo(lista_1)
print("burbujeo = ", lista_1)
print("-----------")
lista_2 = [1, 2, 3, 4, 5]
print("lista = ", lista_2)
ord_burbujeo(lista_2)
print("burbujeo = ", lista_2)
print("-----------")
lista_3 = [0, 9, 3, 8, 5, 3, 2, 4]
print("lista = ", lista_3)
ord_burbujeo(lista_3)
print("burbujeo = ", lista_3)
print("-----------")
lista_4 = [10, 8, 6, 2, -2, -5]
print("lista = ", lista_4)
ord_burbujeo(lista_4)
print("burbujeo = ", lista_4)
print("-----------")
lista_5 = [2, 5, 1, 0]
print("lista = ", lista_5)
ord_burbujeo(lista_5)
print("burbujeo = ", lista_5)
| false |
76512e65fadd9589b50889cbf42b99f68686983e | andrewlehmann/hackerrank-challenges | /Python Data Structures/Compare two linked lists/compare_linked_lists.py | 956 | 4.1875 | 4 | #Body
"""
Compare two linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def equalityCheck(first, other):
var = 1
if first is None:
if other is not None:
var = 0
elif other is None:
if first is not None:
var = 0
else:
var = first.data == other.data
return var
def notEqual(first, other):
return not equalityCheck(first, other)
def CompareLists(headA, headB):
cur_nodeA = headA
cur_nodeB = headB
while cur_nodeA is not None and cur_nodeB is not None:
if cur_nodeA.data != cur_nodeB.data:
return 0
cur_nodeA = cur_nodeA.next
cur_nodeB = cur_nodeB.next
return int(cur_nodeA == None and cur_nodeB == None)
| true |
f5090b41b7e5cb5e98c4dc3ac85f092df79000bd | iyoussou/CAAP-CS | /hw1/fibonacci.py | 469 | 4.28125 | 4 | #Prints a specific value of the Fibonacci Sequence.
def main():
print("This program prints a specific term of the Fibonacci Sequence.")
term = eval(input("Which term of the Fibonacci Sequence would you like?: "))
current = 1
previous = 0
old_previous = 0
for i in range(0, term-1):
old_previous = previous
previous = current
current = previous + old_previous
print("Term " + str(term) + " of the Fibonacci Sequence is " + str(current) + ".")
main()
| true |
2212f3aa40b95de35bb686d7462c95119bc865be | idealgupta/pyhon-basic | /matrix1.py | 310 | 4.1875 | 4 | matrix =[
[3,4,5],
[5,7,8],
[4,9,7]
]
print(matrix)
transposed=[]
#for colem
for i in range(3):
list=[]
for row in matrix:
list.append(row[i])
transposed.append(list)
print(transposed)
#same
trans =[[row[i] for row in matrix] for i in range(3)]
print(trans) | true |
38fa12bb089d62f76120c49953c8b0b359368281 | forzen-fish/python-notes | /1.简单介绍/5简单操作.py | 1,186 | 4.25 | 4 | #语句与函数
#赋值语句:由辅助符号构成的一行代码
#赋值语句用来给变量赋予新的数据值
#赋值语句右侧的数据类型同时作用于变量
#如:
#代码:
# a = 10
# b = "10"
# c = str(a)
# print(type(a))
# print(type(b))
# print(type(c))
#输出结果:
# <class 'int'>
# <class 'str'>
# <class 'str'>
#分支结构语句
#作用:根据判断条件决定运行方向的语句
# 由if elif else 构成
#格式:
"""
if 条件:
成立语句
elif 条件:
elif条件成立语句
else:
if与elif都不成立时的语句
注意缩进
"""
#函数:根据输入参数产生不同的输出功能与过程
#如:input() ,print()...
#函数中传入的量叫做参数 如:print("123"),字符串"123"为函数的参数
#调用格式: 函数名(<参数>(尖括号"<>"表示可有可无))
#输入输出:
# 使用方法:<变量> = input(<提示信息字符串>),从控制台获取输入,输入的信息
#保存在变量中,提示字符串不传递给变量
#使用方法:print(<字符串变量>)
#格式化操作方法
"""
代码:
PI=3.1415926
print("{:.2f}".format(PI))
""" #输出结果:3.14
| false |
4bb1f08be42cd7249b668f40e707a79cfca25477 | forzen-fish/python-notes | /4.元组列表&字典/3列表排序与元祖.py | 768 | 4.53125 | 5 | """
列表的排序操作
sort从小到大,如需大到小排序,利用reverse翻转
num = [1,5,61,7,8,5]
num.sort()
print(num)
[1, 5, 5, 7, 8, 61]
num = [1,5,61,7,8,5]
num.sort()
num.reverse()
print(num)
[61, 8, 7, 5, 5, 1]
"""
"""
列表的嵌套
列表中还有列表:
[[1,2],[2,3],[3,4]]
"""
"""
元组
与列表类似但是元组不能修改,使用圆括号
a = (1,2,3,4)
索引从零开始
a[0]--》1
...
"""
"""
修改元组
元组的值是不允许修改的,但是可以对元组进行连接组合
name1 = ("wang","yu")
name2 = ("chen","lu")
name3 = name1+name2
print(name3)
"""
"""
元组内置函数
len(tuple):计算元组元素个数
max(tuple):返回元组最大值
min(tuple):返回最小
tuple(seq):将列表转换为数组
"""
| false |
8646d28c0880d9b3851d0ec49e97ef259031bec3 | akshitshah702/Akshit_Task_5 | /# Task 5 Q3.py | 436 | 4.21875 | 4 | # Task 5 Q3
def mult_digits():
x = input("Enter number ")
while type(x) is not int:
try:
while int(x) <= 1:
x = input("Please enter a number greater than 1: ")
x = int(x)
except ValueError:
x = input("Please enter integer values only: ")
x = int(x)
print(f"Yes, you have entered {x}.") | true |
183b9a7d439dca14510d9257712d90d1adc8a515 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/QuickSort.py | 801 | 4.125 | 4 | def partition(array, low, high):
i = (low - 1)
pivot = array[high]
for j in range(low, high):
if array[j] <= pivot:
i = i + 1
array[i], array[j] = array[j], array[i]
array[i+1], array[high] = array[high], array[i+1]
return (i + 1)
def quickSort(array, low, high):
if len(array) == 1:
return array
if low < high:
part = partition(array, low, high)
quickSort(array, low, part - 1)
quickSort(array, part + 1, high)
array = []
while 1:
try:
x = input("Enter a number (To exit write something tha is not a number): ")
except:
break
array.append(x)
quickSort(array, 0, len(array) - 1)
print("Sorted array using Quicksort:")
for i in range(len(array)):
print("%d" % array[i]), | true |
c4f2ba0d605988bfcfb046c42e92b4ef216c0534 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Merge_sort.py | 916 | 4.28125 | 4 | def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Finding the middle point and partitioning the array into two halves
middle = len(unsorted_list) // 2
left = unsorted_list[:middle]
right = unsorted_list[middle:]
left = merge_sort(left)
right = merge_sort(right)
return list(merge(left, right))
#Merging the sorted halves
def merge(left,right):
res = []
while len(left) != 0 and len(right) != 0:
if left[0] < right[0]:
res.append(left[0])
left.remove(left[0])
else:
res.append(right[0])
right.remove(right[0])
if len(left) == 0:
res = res + right
else:
res = res + left
return res
input_list = list(map(int,input("Enter unsorted input list: ").split()))
print("Unsorted Input: ", input_list)
print("Sorted Output: ", merge_sort(input_list)) | true |
6e3235205388258659eb7ac63925152e52267ed9 | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Insertion_sort.py | 305 | 4.21875 | 4 | def insertionSort(array):
for index in range(1,len(array)):
currentvalue = array[index]
position = index
while position>0 and array[position-1]>currentvalue:
array[position]=array[position-1]
position = position-1
array[position]=currentvalue
return array
| true |
04994935faa67526f4588d98d22ca235e993285d | rodrigobn/Python | /Lista de exercício 4 (laços)/ex09.py | 275 | 4.21875 | 4 | """
9 - Faça um programa para calcular a área de N quadriláteros. Fórmula: Área = Lado * Lado.
"""
quadrados = int(input("Informe quantos quadrados: "))
for i in range(quadrados):
lado = float(input("Informe o lado do quadrado: "))
area = lado * lado
print(area) | false |
c2b759bb13e094290557153d12bb221a97b9718a | rodrigobn/Python | /Lista de exercício 3 (if, elif, else)/ex13.py | 1,252 | 4.375 | 4 | """
13. Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações:
• Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os demais valores, sendo encerrado;
• Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa;
• Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário;
• Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário;
"""
print("ax2 + bx + c")
a = int(input("Digite o valor de A: "))
b = int(input("Digite o valor de B: "))
c = int(input("Digite o valor de C: "))
if a != 0:
delta = (b**2) - (4 * a * c)
if delta < 0:
print("Delta negativo({:.2f}). Não existe raizes reais".format(delta))
elif delta == 0:
print("Delta = 0. A equação possui apenas uma raiz real")
elif delta > 0:
print("Delta positivo({:.2f}), a equação possui duas raiz reais".format(delta))
else:
print("a = {}. A equação não é do segundo grau".format(a)) | false |
4b974df000fc347992e1cf94bde59a217fd55dfd | rodrigobn/Python | /Lista de exercício 4 (laços)/ex07.py | 278 | 4.15625 | 4 | """
7 - Escreva um programa que calcula o fatorial de um dado número N.
"""
num = int(input("Digite o valor: "))
while num < 0:
num = int(input("Digite o valor: "))
fatorial = 1; #O valor neutro da multiplicação
for i in range(num, 1, -1):
fatorial *= i
print(fatorial) | false |
970d9c88ae8b94072b9fe44dda83bfba5b13195e | redclazz2/LogicaDeProgramacion | /Quizzes/Quiz23Abril/Punto6.py | 282 | 4.125 | 4 | palabra = input("Ingrese una palabra para verificar si es un palíndromo: ")
palabraLista = list(palabra.lower())
palabraInver = list(palabra.lower())
palabraInver.reverse()
if palabraLista == palabraInver:
print("Es un palíndromo!")
else:
print("No es un palíndromo!")
| false |
f48416b78c2e6a29a4b041b843cd8de5d280a2b0 | anilgeorge04/cs50harvard | /python-intro/credit.py | 1,958 | 4.25 | 4 | # This software validates a credit card number entered by the user
# Validity checks: Format, Luhn's checksum algorithm*, Number of digits, Starting digit(s) with RegEx
# Output: It reports whether the card is Amex, Mastercard, Visa or Invalid
# *Luhn's checksum algorithm: https:#en.wikipedia.org/wiki/Luhn_algorithm
import re
def main():
card_type = {
1: "AMEX",
2: "MASTERCARD",
3: "VISA",
4: "INVALID"
}
# Get credit card number
cardnum = input("Number: ")
# check card length
if len(cardnum) == 13 or len(cardnum) == 15 or len(cardnum) == 16:
key = checkcard(cardnum)
else:
key = 4
print(card_type[key])
def checkcard(cardnum):
# check card meet Luhn's algorithm specs
# if yes, RegEx check on first digits of card
if luhn(int(cardnum)):
# AMEX starts with 34 or 37
if re.search("^3(4|7)*", cardnum):
return 1
# MASTERCARD starts with 51-55
elif re.search("^5[1-5]*", cardnum):
return 2
# VISA starts with 4
elif re.search("^4+", cardnum):
return 3
else:
return 4
else:
return 4
def luhn(cardnum):
last_digit, sum_odd, sum_prod_even, pos = 0, 0, 0, 1
num = cardnum
while num > 0:
last_digit = num % 10
# alternate numbers from right
if not pos % 2 == 0:
sum_odd += last_digit
# alternate numbers second from right
else:
sum_prod_even += (last_digit * 2) % 10
if last_digit * 2 >= 10:
# max number in 10s place can only be 1 (9*2=18)
sum_prod_even += 1
# remove last digit
num = (num - last_digit) / 10
pos += 1
# Luhn's algorithm check
if (sum_prod_even + sum_odd) % 10 == 0:
return True
else:
# print("Failed Luhn Algorithm check")
return False
main()
| true |
0cf8dabae652848b5d0ac46fd753e0ee977630ee | AjayMistry29/pythonTraining | /Extra_Task_Data_Structure/ETQ8.py | 831 | 4.1875 | 4 | even_list=[]
odd_list=[]
while True:
enter_input = int(input("Enter a number from from 1 to 50: "))
if enter_input>=1 and enter_input<=50 and (enter_input % 2) != 0 and len(odd_list)<5:
odd_list.append(enter_input)
print("Odd List :" ,odd_list)
continue
elif enter_input>=1 and enter_input<=50 and (enter_input % 2) == 0 and len(even_list)<5:
even_list.append(enter_input)
print("Even List :" ,even_list)
else:
print("Entered Number is out of range")
break
print("Sum of Even Numbers List is :", sum(even_list))
print("Sum of Odd Numbers List is :", sum(odd_list))
print("Maximum number from Even List is :", max(even_list))
print("Maximum number from Odd List is :", max(odd_list))
| true |
b7497ea31a107328ecb0242600df34d808483353 | AjayMistry29/pythonTraining | /Task4/T4Q2.py | 359 | 4.3125 | 4 | def upperlower(string):
upper = 0
lower = 0
for i in string:
if (i>='a'and i<='z'):
lower=lower+1
if (i>='A'and i<='Z'):
upper=upper+1
print('Lower case characters = %s' %lower,
'Upper case characters = %s' %upper)
string = input("Enter the String :")
upperlower(string) | true |
3fab33ec2b0ec5d95bcfefbab6c1b878d0c81daf | mrodzlgd/dc-ds-071519 | /Warm_Ups/number_finder.py | 766 | 4.25 | 4 | def prime_finder(numbers):
import numpy as np
prime=np.array([])
"""will select only the prime #'s from a given numpy array"""
for n in np.nditer(numbers):
if (n%2)>0:
prime = np.append(prime,n)
return prime
#a series of numbers in which each number ( Fibonacci number ) is the sum of the \n,
#two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.\n,
def fibonacci_finder(numbers):
""""will select only the Fibonacci numbers from a given numpy array."""
import numpy as np
fib_nums=np.array([])
x=2 #index counter
for n in np.nditer(numbers[2:]):
if n == (numbers[x-1]+numbers[x-2]):
fib_nums = np.append(fib_nums,n)
x+=1
return fib_nums | true |
df78a002fdb80aa75916d98777f5036f53c24082 | mariololo/EulerProblems | /problem41.py | 1,162 | 4.25 | 4 | """
We shall say that an n-digit number is pandigital if it makes use of
all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
def is_pandigital(n):
digits = []
for dig in str(n):
if dig in digits:
return 0
else:
digits.append(int(dig))
digits = sorted(digits)
if digits[0] == 1:
last = 1
if len(digits) == 1:
return 1
for dig in digits[1:]:
if dig != last + 1:
return 0
last = dig
return len(digits)
else:
return 0
from math import sqrt
def is_prime(a):
if a % 3 == 0:
return False
else:
for div in range(5, int(sqrt(a))+1, 2):
if a % div == 0:
return False
return True
def largest_pandigital():
print("Searching largest pandigital prime")
largest = float("-inf")
running = 9999999
while True:
if is_prime(running) and is_pandigital(running) > 0:
return running
running = running - 2
if running % 10000 == 0:
print(running)
if __name__ == "__main__":
print(largest_pandigital())
| true |
28785e79791f208e24240290142fd8bb87680e92 | boquer/Python | /condicionales.py | 477 | 4.125 | 4 | numero = int(input("Digite un número: "))
if numero>0: #Si el número es mayor a cero, imprime lo de abajo.
print("El número que ingresó es positivo")
#Si el número no es mayor a cero, pasa a elif
elif numero==0:#Si el número es igual a cero, imprime lo de abajo.
print("El número que ingresó es cero")
#Si no se cumplieron ningunas de las condiones pasadas, pasa al else
else:
print("El número que ingresó es negativo")
print("\nFin del programa")
| false |
97cc0a8e13f2517cd8c55c0741cc5d94bfa4d7ea | AshTiwari/Standard-DSA-Topics-with-Python | /Array/Array_Merge_Sorted_Array_in_O(1)_Space.py | 772 | 4.28125 | 4 | # Merge two sorted array in O(1) time.
from binaryInsertion import binaryInsertion
######### Increase the Efficiency by using binaryInsertion function to add element in sorted arr2 ###########
def addElement(arr,element):
index = 0
# alternate way is to use binaryInsertion.
while(index < len(arr)-1):
if arr[index] > arr[index+1]:
arr[index], arr[index+1] = arr[index+1], arr[index]
index += 1
def swapAndSort(arr1,arr2):
index1 = 0
index2 = 0
while(index1 < len(arr1)):
if arr1[index1] > arr2[index2]:
arr1[index1], arr2[index2] = arr2[index2], arr1[index1]
temp_index2 = index2
addElement(arr2,arr1[index1])
index1 += 1
if __name__ == "__main__":
arr1 = [0,8,9,10,15]
arr2 = [1,3,9,11,14,16]
swapAndSort(arr1,arr2)
print(*arr1+arr2) | true |
835cfbcb2ebd756769226a1b3745427f70c17c50 | LucioOSilva/HackerRankPython-PS | /LinkedList-PrintTheElementsOfALinkedList.py | 1,868 | 4.375 | 4 | """
If you're new to linked lists, this is a great exercise for learning about them. Given a pointer to the head node of a
linked list, print its elements in order, one element per line. If the head pointer is null (indicating the list is
empty), don’t print anything.
Input Format:
The first line of input contains "n", the number of elements in the linked list.
The next "n" lines contain one element each, which are the elements of the linked list.
Note: Do not read any input from stdin/console. Complete the printLinkedList function in the editor below.
Constraints:
1 <= n <= 1000
1 <= list[i] <= 1000, where list[i] is the i[th] element of the linked list.
Output Format:
Print the integer data for each element of the linked list to stdout/console (e.g.: using printf, cout, etc.).
There should be one element per line.
Sample Input:
2
16
13
Sample Output:
16
13
Explanation:
There are two elements in the linked list. They are represented as 16 -> 13 -> NULL. So, the printLinkedList function
should print 16 and 13 each in a new line.
"""
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def printLinkedList(head):
cur = llist.head
while cur.next != None:
print(cur.data)
cur = cur.next
print(cur.data)
if __name__ == '__main__':
llist_count = int(input())
llist = SinglyLinkedList()
for _ in range(llist_count):
llist_item = int(input())
llist.insert_node(llist_item)
printLinkedList(llist.head)
| true |
8db7becd41ea2f645a1f523a662ca9715da4121b | MrKonrados/PythonTraining | /Change Calculator/change_calc.py | 1,369 | 4.3125 | 4 | """
BASIC GOAL Imagine that your friend is a cashier, but has a hard time counting back change to customers.
Create a program that allows him to input a certain amount of change, and then print how how many quarters, dimes,
nickels, and pennies are needed to make up the amount needed.
For example, if he inputs 1.47, the program will tell that he needs 5 quarters, 2 dimes, 0 nickels, and 2 pennies.
SUBGOALS
1. So your friend doesn't have to calculate how much change is needed, allow him to type in the amount of money
given to him and the price of the item. The program should then tell him the amount of each coin he needs
like usual.
2. To make the program even easier to use, loop the program back to the top so your friend can continue to use
the program without having to close and open it every time he needs to count change.
"""
from decimal import Decimal
coins = {
'quarter': Decimal(.25),
'dime': Decimal(.10),
'nickel': Decimal(.05),
'penny': Decimal(.01),
}
amount_money = Decimal(4.21)
price = Decimal(1.47)
price = amount_money - price
change = {}
for coin in sorted(coins, key=coins.__getitem__, reverse=True):
div, mod = divmod(price, coins[coin])
change[coin] = int(div)
price = Decimal(price) - Decimal(coins[coin] * div)
for c in change:
print(c,"\t=\t", change[c]) | true |
393492c970c349b49cc63d282ab8cc521308f462 | shebilantony/3numlar | /3lar.py | 262 | 4.25 | 4 | num1=float(input("Enter first no:"))
num2=float(input("Enter second no:"))
num3=float(input("Enter third no:"))
if(num1>num2) and (num1>num3):
largest=num1
elif(num2>num1) and (num2>num3):
largest=num2
else:
largest=num3
print("the largest no is",largest)
| false |
b017de724c850cdc2c2dd757d7508ee2083db0f6 | lmitchell4/Python | /ch_3_collatz.py | 428 | 4.3125 | 4 | ## Collatz sequence
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
else:
print(3*number + 1)
return(3*number + 1)
inputOK = False
while not inputOK:
try:
print('Enter an integer to start the Collatz sequence:')
n = int(input())
inputOK = True
except ValueError:
print('That\'s not an integer! Try again below ...\n')
while n > 1:
n = collatz(n)
| true |
a95914f8996bc96b2e60ca8951bdeaf3611652d5 | igelritter/learning-python | /ex35-lphw.py | 2,759 | 4.125 | 4 | #This is basically a text style adventure. Each room is defined as a function
#as well as the starting and dying text.
#importing the exit function
from sys import exit
#gold room.
def gold_room():
print "This room is full of gold. How much do you take?"
next=(raw_input(">"))
#This 'if/else' statement is broken. It will only accept numbers with 1 or 0
#It does very little to figure out whether the user entered numbers or a string
## if "0" in next or "1" in next:
## how_much=int(next)
## else:
## dead("Man, learn to type a number.")
#what we need here is a try/except block. The try except attempts to convert the
#inputed string into an int. If it succeeds, then the int is evaluated for
#the next condition; if not, then the user gets a homemade error message--they die--
#and the program terminates.
try:
how_much=int(next)
except:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
EXIT (0)
else:
dead("You greedy bastard!")
#bear room
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input(">")
if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
# cthulu room
def cthulu_room():
print "Here you see the great evil Cthulu."
print "He...it...whatever...stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input(">")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty")
else:
cthulu_room()
#dead() and start() functions
def dead(why):
print why,"Good job!"
exit (0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
next = raw_input(">")
if next == "left":
bear_room()
elif next == "right":
cthulu_room()
else:
dead("you stumble around the room until you starve.")
#after all the function definitions, we get to the function call that starts
#the program
start()
| true |
aa4e4e9f3f69af579d0f62498167fc4cdf087f91 | igelritter/learning-python | /ex34-lphw.py | 512 | 4.28125 | 4 | #demonstarting the difference between ordinal numbers and
#the cardinal numbers of indices in lists
animals = ['bear' ,'python' ,'peacock' ,'kangaroo' ,'whale' ,'platypus']
print animals
print "The animal at 1"
print animals[1]
print "The 3rd animal"
print animals[2]
print "The 1st animal"
print animals[0]
print "The animal at 3"
print animals[3]
print "The 5th animal"
print animals[4]
print "The animal at 2"
print animals[2]
print "The 6th animal"
print animals[5]
print "The animal at 4"
print animals[4]
| false |
95af2966515dd3cfca5459096762f8c0d5790ab3 | dao-heart/Leetcode-solutions | /pythonDataStructures/llist.py | 2,157 | 4.1875 | 4 | # Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
## Test the nodes
n1 = Node("Mon")
n2 = Node("Tues")
n1.next = n2
print(n1)
class LinkedList:
print_list = []
def __init__(self):
self.headval = None
def __repr__(self):
return "->".join(self.helperFunction(self.headval))
# IMPROV: Using generator instead of iterator.
# Recursive traversal and print linked list - O(n)
def helperFunction(self,node):
if node:
self.print_list.append(node.data)
self.helperFunction(node.next)
return self.print_list
# Insert at the front of the linked List - O(1)
def insertNodeStart(self,data):
NewNode = Node(data)
NewNode.next = self.headval
self.headval = NewNode
# Insert at the end of the linked list - O(n) transverse using while loop
def insertNodeEnd(self, data):
node = self.headval
NewNode = Node(data)
if node is None:
node = NewNode
while node.next is not None:
node = node.next
node.next = NewNode
# Insert at the middle of the list - O(1) traverse and swap pointers
def insertNodeMiddle(self, middle_node, new_data):
if middle_node is None:
print("The mentioned node is empty")
return
NewNode = Node(new_data)
NewNode.next = middle_node.next
middle_node.next = NewNode
# Delete the selected node. Need to traverse the list - O(n)
def removeNode(self, delete_node):
node = self.headval
target_node = self.delete_node(node,delete_node)
target_node.next = delete_node.next
delete_node = None
def del_helper_function(self, node, delete_node):
if node.next is delete_node:
retun node
else:
self.del_helper_function(node.next, delete_node)
#### Create a Linked List
l1 = LinkedList()
l1.headval = Node("Mon")
l2 = Node("Tues")
l1.headval.next = l2
l2.next = Node("Wed")
l1.insertNodeStart("Sun")
l1.insertNodeEnd("Fri")
l1.insertNodeMiddle(l2.next, "Thu")
print(l1)
| true |
06e0eeff8467efd1538056e984644ea665656c0c | mobbarley/python2x | /fizzbuzz.py | 559 | 4.3125 | 4 | # This program mocks the script for the game fizz - buzz where we print all the numbers
# from 1 to the number entered by the user but we say Fizz when number is divisible by 3
# and Buzz when it is divisible by 5, when it is both like in 15, 30 etc we will say FizzBuzz
num = int(raw_input("Enter a number : "))
if num < 0:
print "Invalid number ", num
else:
for ix in range(1,num+1):
text = ''
if ix%3 == 0:
text = text + "Fizz"
if ix%5 == 0:
text = text + "Buzz"
if text == '':
print ix
else:
print text
| true |
88663a9fba92b5e8ca7a0121d3fdfabea283cb05 | cindygao93/Dartboard | /assignment 2 third try.py | 2,469 | 4.1875 | 4 | ##this is a program in turtle that will draw a dart board
from turtle import *
def main() :
shape("turtle")
pendown()
pencolor("yellow")
pensize(5)
speed(20)
radius=200
subradius=0
forward(radius)
left(90)
sideCount = 0
color = "yellow"
while sideCount <80:
if sideCount>0 and sideCount<20:
if color == "yellow":
color = "black"
elif color== "black":
color="yellow"
if sideCount==20:
subradius=subradius+20
home()
forward(radius-subradius)
left(90)
if sideCount>20 and sideCount<40:
if color == "yellow":
color = "black"
elif color== "black":
color="yellow"
if sideCount==40:
subradius=subradius+80
home()
forward(radius-subradius)
left(90)
if sideCount>40 and sideCount<60:
if color == "yellow":
color = "black"
elif color== "black":
color="yellow"
if sideCount==60:
##stop
subradius=subradius+10
home()
forward(radius-subradius)
left(90)
if sideCount>60 and sideCount<80:
if color == "yellow":
color = "black"
elif color== "black":
color="yellow"
pencolor(color)
fillcolor(color)
circle(radius-subradius, 18)
pendown()
begin_fill()
left(90)
forward(radius-subradius)
left(162)
forward(radius-subradius)
end_fill()
left(90)
circle(radius-subradius,18)
penup()
sideCount = sideCount + 1
home()
forward(30)
begin_fill()
pencolor("black")
fillcolor("black")
left(90)
circle(30)
end_fill()
home()
forward(20)
begin_fill()
pencolor("red")
fillcolor("red")
left(90)
circle(20)
end_fill()
home()
main()
| true |
8dc6e4c41403953b42dde18cfb626598815bcee7 | rkuzmyn/DevOps_online_Lviv_2020Q42021Q1 | /m9/task9.1/count_vowels.py | 428 | 4.125 | 4 | vowels = 'aeiou'
def count_vowels(string, vowels):
# casefold() it is how lower() , but stronger
string = string.casefold()
# Forms a dictionary with key as a vowel
count = {}.fromkeys(vowels, 0)
# To count the vowels
for character in string:
if character in count:
count[character] += 1
return count
string = 'YaroslavVoloshchukISdevops'
print(count_vowels(string, vowels)) | true |
899721b5c37fc46b0ff9cc23180428800a349589 | rogerroxbr/pysuinox-sprint-zero | /capitulo 04/exercicio-04-08.py | 415 | 4.125 | 4 | a = float(input("Primeiro número:"))
b = float(input("Segundo número:"))
operação = input("Digite a operação a realizar (+,-,* ou /):")
if operação == "+":
resultado = a + b
elif operação == "-":
resultado = a - b
elif operação == "*":
resultado = a * b
elif operação == "/":
resultado = a / b
else:
print("Operação inválida!")
resultado = 0
print("Resultado: ", resultado)
| false |
d643bffc1fc1c1c029543510b66c5a0b1bc77377 | slauney/Portfolio | /Python/InClassMarking/TC5/HighestCommonDivisor.py | 2,611 | 4.125 | 4 | ###########################################
# Desc: Highest Common Divisor
#
# Author: Zach Slaunwhite
###########################################
def main():
#initialize the continue condition
continueLoop = "y"
#while continue loop is equal to y, repeat the program
while(continueLoop == "y"):
#get the first number from the user
num1 = input("Enter the first number: ")
#if the input is not a number, ask the user until it is a number
while (not num1.isnumeric()):
print("ERROR! Enter a valid first number.")
num1 = input("Enter the first number: ")
#cast the input to an int (this is because we cannot initialize the input as an int, or else the while loop wouldn't work)
num1 = int(num1)
#get the second number from the user
num2 = input("Enter the second number: ")
#if the input is not a number, ask the user until it is a number
while (not num2.isnumeric()):
print("ERROR! Enter a valid second number.")
num2 = input("Enter the second number: ")
#cast the input to an int
num2 = int(num2)
#sort the min and max numbers (could use sort() instead?)
minNumber = min(num1, num2)
maxNumber = max(num1, num2)
#calling highest divisor function and catching the result
highestDivisor = getHighestCommonDivisor(minNumber, maxNumber)
print("The Highest Common Divisor of {} and {} is {}.\n".format(num1, num2, highestDivisor))
#ask user to repeat program
continueLoop = input("Would you like to try again? (y/n)").lower()
#End message once loop is exited
print("\nThank you for using HCD program.")
#this function is to get the highest common divisor of two numbers
def getHighestCommonDivisor(num1, num2):
#initialize variable for checking if there is a remainder
noRemainder = 0
rangeOffSet = 1
#initialize highest divisor
highestDivisor = 0
#loop to go through all possible divisors
for x in range(num1 + rangeOffSet):
#if the number is 0, continue (cannot divide by 0 or it breaks program)
if x == 0:
continue
#if the lowest number divided by x has no remainder, continue to second if statement
if (num1 % x) == noRemainder:
#if the highest number divided by x has no remainder, set highest divisor to x
if (num2 % x) == noRemainder:
highestDivisor = x
#returns the highest divisor
return highestDivisor
if __name__ == "__main__":
main() | true |
6c85d89a5becfcce7df81801b3cd511c82b829b8 | slauney/Portfolio | /Python/Labs/Lab04/ProvincialTaxes.py | 2,194 | 4.21875 | 4 | ###########################################
# Desc: Enter application description here.
#
# Author: Enter name here.
###########################################
def main():
# Constants
GST = 1.05
HARMONIZED_TAX = 1.15
# PROVINCIAL_TAX will be added onto GST to bring tax to 1.11
PROVINCIAL_TAX = 0.06
#addTax is false by default, and set later on if conditions are met
addTax = False
continueProgram = True
# Input
while continueProgram:
purchaseCost = float(input("Please enter the cost of your purchase: "))
customerCountry = input("Please enter the country you are from: ")
# Process
totalCost = purchaseCost
tax = 0
customerCountry = customerCountry.lower()
#adding tax if the country is canada
if customerCountry == "canada":
addTax = True
if addTax:
customerProvince = input("Please enter what province you are from: ")
#if province is alberta, set tax to 5% and calculate total cost
if customerProvince == "alberta":
tax = GST
#if the province is ontario, new brunswick, or nova scotia, set tax to 15% and calculate total cost
elif customerProvince == "ontario" or customerProvince == "new brunswick" or customerProvince == "nova scotia":
tax = HARMONIZED_TAX
#if the province is not any of the provinces listed above, set tax to 11% and calculate total cost
else:
tax = GST + PROVINCIAL_TAX
totalCost = purchaseCost * tax
#changing tax from decimal to percentage
tax = (tax - 1) * 100
# Output
print("\nYour total cost is ${:.2f}".format(totalCost))
print("Tax was {:.0f}%\n".format(tax))
#prompting user if they would like to run the program again
userContinue = input("Would you like to run this program again? (Yes/no): ")
userContinue = userContinue.lower()
if userContinue != "yes":
continueProgram = False
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main() | true |
df11e224537c2d5ea2aa747b7a71e12b0c4a975c | slauney/Portfolio | /Python/InClassMarking/TC2/taxCalculator.py | 1,638 | 4.25 | 4 | ###########################################
# Desc: Calculates the total amount of tax withheld from an employee's weekly salary (income tax?)
#
# Author: Zach Slaunwhite
###########################################
def main():
# Main function for execution of program code.
# Make sure you tab once for every line.
# Input
#prompt user for pre-tax weekly salary amount, and the number of dependants they wish to claim
salaryAmount = float(input("Please enter the full amount of your weekly salary: $"))
totalDependants = int(input("How many dependants do you have?: "))
# Process
#program calculates the provincial tax withheld, the federal tax withheld, the total tax withheld, and the users take home amount
#provincial tax: 6.0%
provTaxWithheld = salaryAmount*0.06
#federal tax: 25.0%
fedTaxWithheld = salaryAmount*0.25
#deduction amount: 2.0% of salary per dependant
taxDeduction = salaryAmount * (totalDependants * 0.02)
#calculate total tax withheld
totalTaxWithheld = provTaxWithheld + fedTaxWithheld - taxDeduction
#calculate total take home pay
takeHomePay = salaryAmount - totalTaxWithheld
# Output
print("Provincial Tax Withheld ${:.2f}".format(provTaxWithheld))
print("Federal Tax Withheld ${:.2f}".format(fedTaxWithheld))
print("Dependant deduction for {} dependants: {:.2f}".format(totalDependants, taxDeduction))
print("Total Withheld: ${:.2f}".format(totalTaxWithheld))
print("Total Take-Home Pay: ${:.2f}".format(takeHomePay))
#PROGRAM STARTS HERE. DO NOT CHANGE THIS CODE.
if __name__ == "__main__":
main()
| true |
067ba4d62b07896b1a484dc7a47a39d9aba968e7 | ggibson5972/Project-Euler | /euler_prob_1.py | 232 | 4.15625 | 4 | result = 0
#iterate from 1 to 1000
for i in range(1000):
#determine if i is a multiple of 3 or 5
if ((i % 3 == 0) or (i % 5 == 0)):
#if i is a multiple of 3 or 5, add to sum (result)
result += i
print result
| true |
052857681781833e79edd5eecb1e32b99f561749 | chmod730/My-Python-Projects | /speed_of_light.py | 944 | 4.375 | 4 |
'''
This will query the user for a mass in kilograms and outputs the
energy it contains in joules.
'''
SPEED_OF_LIGHT = 299792458 # c in m/s2
TNT = 0.00000000024 # Equivalent to 1 joule
def main():
print()
print("This program works out the energy contained in a given mass using Einstein's famous equation: E = mc2 ")
while True:
print()
mass = input("Please enter a mass in Kg: ")
energy = float(mass) * (float(SPEED_OF_LIGHT) ** 2)
boom = (float(energy) * TNT) / 1000000
boom = int(boom)
print()
print("E = mc2")
print("Mass = " + str(mass) + " Kg")
print("C = 299792458 m/s")
print("Energy = " + str(energy) + " joules")
print()
print("That's the same as " + str(boom) + " Megatons of TNT !! ")
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main() | true |
eb54fcd8f36e094f77bccdcebc0ae8230a2db34d | adneena/think-python | /Iteration/excercise1.py | 1,142 | 4.25 | 4 | import math
def mysqrt(a):
"""Calculates square root using Newton's method:
a - positive integer < 0;
x - estimated value, in this case a/2
"""
x = a/2
while True:
estimated_root = (x + a/x) / 2
if estimated_root == x:
return estimated_root
break
x = estimated_root
def test_square_root(list_of_a):
"""Displays outcomes of calculating square root of a using different methods;
list_of_a - list of positive digit.
"""
line1a = "a"
line1b = "mysqrt(a)"
line1c = "math.sqrt(a)"
line1d = "diff"
line2a = "-"
line2b = "---------"
line2c = "------------"
line2d = "----"
spacing1 = " "
spacing2 = " " * 3
spacing3 = ""
print(line1a, spacing1, line1b, spacing2, line1c, spacing3, line1d)
print(line2a, spacing1, line2b, spacing2, line2c, spacing3, line2d)
for a in list_of_a:
col1 = float(a)
col2 = mysqrt(a)
col3 = math.sqrt(a)
col4 = abs(mysqrt(a) - math.sqrt(a))
print(col1, "{:<13f}".format(col2), "{:<13f}".format(col3), col4)
test_square_root(range(1, 10)) | true |
3642cd6a682a9a05c2a5bc9c7597fd02af43a417 | adneena/think-python | /Fruitiful-functions/excercise-3.py | 856 | 4.34375 | 4 | '''
1. Type these functions into a file named palindrome.py and test them out. What happens if
you call middle with a string with two letters? One letter? What about the empty string,
which is written '' and contains no letters?
2. Write a function called is_palindrome that takes a string argument and returns True if it
is a palindrome and False otherwise. Remember that you can use the built-in function len
to check the length of a string
'''
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if len(word) <= 1:
return True
if first(word) != last(word):
return False
return is_palindrome(middle(word))
print(is_palindrome('adheena'))
print(is_palindrome('wow'))
print(is_palindrome('malayalam'))
print(is_palindrome('yellow'))
| true |
5674ddd6d622dad21e14352332cdb85bf7adf9fc | adneena/think-python | /variables-expressions-statements/excercise1.py | 520 | 4.375 | 4 | '''
Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = '.'
For each of the following expressions, write the value of the expression and the type (of the value of
the expression).
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. delimiter * 5
'''
width = 17
height = 12.0
delimiter = '.'
x = width/2
print(x)
print(type(x))
y = width/2.0
print(y)
print(type(y))
z = height/3
print(z)
print(type(z))
p = 1+2*5
print(p)
print(type(p))
q = delimiter*5
print(q)
print(type(q)) | true |
5327e3c6d6563e1fe25572b838f7274c7524c7ba | 09jhoward/Revison-exercies | /task 2 temprature.py | 482 | 4.15625 | 4 | #08/10/2014
#Jess Howard
#development exercises
#write a program that reads in the temperature of water in a container(in centigrade and displays a message stating whether the water os frozen,boiling or neither.
temp= int(input(" Please enter the water temprature in the unit of centigrade:"))
if temp<= 0:
print(" Your water is currently frozen")
elif temp >=100:
print("Your water is currently boiling")
else:
print("Your water is niether froezen or boiling")
| true |
056182ab50cd45d941652e85d9758c6a2d24011c | agmghazi/arcpySamples | /python Tutorial/20.Python_If... Else.py | 1,197 | 4.3125 | 4 | # Python Conditions and If statements
# Equals: a == b
# Not Equals: a != b
# Less than: a < b
# Less than or equal to: a <= b
# Greater than: a > b
# Greater than or equal to: a >= b
# a = 33
# b = 200
# if b > a:
# print("b is greater than a")
# a = 33
# b = 33
# if b > a:
# print("b is greater than a")
# elif a == b:
# print("a and b are equal")
# a = 200
# b = 33
# if b > a:
# print("b is greater than a")
# elif a == b:
# print("a and b are equal")
# else:
# print("a is greater than b")
# a = 200
# b = 33
# if b > a:
# print("b is greater than a")
# else:
# print("b is not greater than a")
# if a > b: print("a is greater than b")
# a = 2
# b = 330
# print("A") if a > b else print("B")
# a = 330
# b = 330
# print("A") if a > b else print("=") if a == b else print("B")
# a = 200
# b = 33
# c = 500
# if a > b and c > a:
# print("Both conditions are True")
# a = 200
# b = 33
# c = 500
# if a > b or a > c:
# print("At least one of the conditions is True")
# x = 41
# if x > 10:
# print("Above ten,")
# if x > 20:
# print("and also above 20!")
# else:
# print("but not above 20.")
# a = 33
# b = 200
# if b > a:
# pass
| false |
7aa43ddbb81ccbb9e8ad6fa74424dbe46fdeca35 | Wambita/pythonwork | /converter.py | 597 | 4.1875 | 4 | #Program to convert pounds to kilograms
#Prompt user to enter the first value in pounds
print("Enter the first value in pounds you wish to convert into kilograms")
pound1= float(input())
#prompt user to enter the second value in pounds
print("Enter the second value in pounds you wish to convert into kilograms")
pound2 = float(input())
#converting pounds to kgs
kgs1 = pound1/2.20462
kgs2 = pound2/2.20462
#display the results
print("Results")
print(" ")
print("The weight in kgs of" ,pound1, " pounds is",round(kgs1,3))
print("The weight in kgs of" ,pound2, " pounds is",round(kgs2,3))
| true |
0a1054b195d5ffe53bc14e92e6080edf6093d5f3 | deodacodesage/data_science_program | /classes.py | 1,154 | 4.21875 | 4 | class Human (object):
"""
Class that defines human beings
"""
def __init__ (self, name, age, race, gender, religion):
self.name = name
self.age = age
self.race = race
self.gender = gender
self.religion = religion
def __person(self):
profile = """
The name of the guy is {}, \n
{} is {} years old. \n
{} is an {} and practices {} .\n
{} is an {} {} so we have to deport the motherF***ker
""".format(self.name, self.name, self.age, self.name, self.race, self.religion, self.name, self.race, self.gender)
print(profile)
def grow(self, value):
new_age = int(self.age) + int(value)
self.age = new_age
print("Sola is now", self.age ,"after serving his time")
sola = Human("Sola", "28", "African", "Man","Christianity")
sola.__person()
"""
class Swimmer(Human):
def swim(self):
print(self.name, "is a swimmer now")
sola = Human("Sola", "28", "African", "Man","Christianity")
sola.person()
sola.grow(15)
career = Swimmer ("Sola", "28", "African", "Man", "Christianity")
career.swim()
"""
| false |
f06a59233c6ebdbd37e9da2a4ca06321ca839055 | clwater/lesson_python | /old/learn_old/if.py | 693 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#if 注意条件后加: 自上至下 某个符合后则忽略后面的
# age = 20
# if age >= 6:
# print('teenager')
# elif age >= 18:
# print('adult')
# else:
# print('kid')
# birth = input('birth: ')
# #通过int()将input得到的str类型转换为int类型
# birth = int(birth)
# if birth > 2000:
# print '00后'
# else :
# print '00前'
height = input('身高: ')
weight = input('体重: ')
height = float(height)
weight = float(weight)
bmi = weight / (height * height)
if bmi <=18.5:
print '过轻'
elif bmi < 25:
print '正常'
elif bmi < 28:
print '过重'
elif bmi < 32:
print '肥胖'
else:
print '严重肥胖'
| false |
12fd7ae41f492a7cb882e38fcdb9d729d6289189 | rmesquita91/exerciciosPOOpython | /exercicio03.python.py | 1,007 | 4.46875 | 4 | """
Faça um Programa que leia três números e mostre o maior e o menor deles.
"
print ('************************************************************')
print ('*** INFORMA O MAIOR E MENOR NUMERO ************************')
print ('***************** RAFAEL MESQUITA *************************')
print ('****** SISTEMAS DE INFORMAÇÃO - UNIS - POO PYTHON **********')
print ('************************************************************')
print ('')
print ('Entre com os numeros')
n1 = int(input('Primeiro número: '))
n2 = int(input('Segundo número: '))
n3 = int(input('Terceiro número: '))
maior = n1
menor = n1
if maior < n2:
maior = n2
if maior < n3:
maior = n3
if menor > n2:
menor = n2
if menor > n3:
menor = n3
print ('*********************************************************************')
print ('O maior número foi: %d ' %maior)
print ('O menor número foi: %d ' %menor)
print ('*********************************************************************')
| false |
e0aea95c21e5134bef5cf6501033d9b9d7d8119a | hwichman/CYEN301 | /KeyedCaesar/KeyedCaesar.py | 1,330 | 4.21875 | 4 | import sys
alphabet = "abcdefghijklmnopqrstuvwxyz"
### Main ###
# Check for arguments
if sys.argv < 3:
raise Exception("CaesarCipher.py <1-25> <alphabetKey>")
try:
# Make sure second argument is an int
numKey = int(sys.argv[1])
except:
print "Key must be an integer."
alphaKey = sys.arv[2]
# New alphabet the cipher will use
# Starts with the alphaKey
# Each character in the alphabet not in the alphaKey is added to the end of the alphaKey
for character in alphabet:
if character not in alphaKey:
alphaKey += character
# Get user input for encoded text
cypherText = raw_input()
# Split cypherText up by spaces
cypherText = cypherText.split(" ")
plainText = []
# Decode each word based on the key and add it to the plainText list
for word in cypherText:
plainWord = ""
for character in word:
# Shift index of character by key.
x = alphaKey.index(character)
x = (x - numKey) % 26
# Decrypted character is the character at the new index
character = alphaKey[x]
# Add character to decrypted word
plainWord.append(character)
plainWord = "".join(plainWord)
plainText.append(plainWord)
# Join everything together and print it
# Make everything lowercase because Caesar() prints it in upper
print " ".join(plainText).lower() | true |
2a4a4034e78d0dca4a5e3429fc29e0df2cfbb35e | popovata/ShortenURL | /shorten_url/app/utils.py | 393 | 4.21875 | 4 | """
A file contains utility functions
"""
import random
import string
LETTERS_AND_DIGITS = string.ascii_letters + string.digits
def get_random_alphanumeric_string(length):
"""
Generates a random string of the given length
:param length: length of a result string
:return: a random string
"""
return ''.join(random.choice(LETTERS_AND_DIGITS) for i in range(length))
| true |
3e34aff568ec6791a2cb378f93a45ce714083911 | GabrielRioo/Curso_em_Video | /Curso_Python/Exercícios/ex016.py | 401 | 4.25 | 4 | # Crie um programa que leia um numero Real qualquer pelo teclado e mostre na tela a sua porção inteira
# Ex: Digite um numero: 6.127, o numero 6.127 tem a parte inteira 6.
num = float(input('Digite um numero: '))
print('O numero digitado foi {} e em inteiros é: {}'.format(num, int(num)))
# OU
from math import trunc
print('O numero digitado foi {} e em inteiros é: {}'.format(num, trunc(num)))
| false |
f2fba366bd724b0bbcb6d9ef80cad1edcb1e546e | AswinSenthilrajan/PythonRockPaperScissor | /PaperStoneScissor/StonePaperScissor.py | 848 | 4.1875 | 4 | from random import randrange
options = ["Scissor", "Stone", "Paper"]
random_number = randrange(3)
user_option = input("Choose between Paper, Scissor and Stone:")
computer_option = options[random_number]
def play():
if computer_option == user_option:
user_optionNew = input("Choose again:")
elif computer_option == "Scissor" and user_option == "Stone" or computer_option == "Stone" and user_option == "Paper" \
or computer_option == "Paper" and user_option == "Scissor":
print("You won")
print("Computer: " + computer_option)
elif computer_option == "Scissor" and user_option == "Paper" or computer_option == "Stone" and user_option == "Scissor" \
or computer_option == "Paper" and user_option == "Stone":
print("You lost")
print("Computer: " + computer_option)
play()
| true |
2311b07ae564fd53cabee5532a39392c9e86793c | hiteshvaidya/Football-League | /football.py | 2,397 | 4.25 | 4 | # Football-League
#This is a simple python program for a Football League Management System. It uses sqlite and tkinter for managing database and UI.
#created by Hitesh Vaidya
from tkinter import *
import sqlite3
class App:
def __init__(self,master):
frame = Frame(master)
frame.pack()
a=StringVar()
b=StringVar()
a1=StringVar()
b1=StringVar()
c=StringVar()
self.button=Button(frame, text='Open Db', fg='red', command=self.ouvrir) #ouvrir method called by command on mouse click
self.button.pack(side=LEFT)
self.button2=Button(frame, text='Create Table',fg='green', command=self.tabluh) #tabluh method called by command on click
self.button2.pack(side=LEFT)
self.button3=Button(frame,text='Close Db',fg='blue',command=self.ferver) #ferver method called on click
self.button3.pack(side=LEFT)
self.button4=Button(frame,text='Insert Rec',command=self.insertar)
self.button4.pack(side=LEFT)
self.button5=Button(frame,text='List Recs',command=self.listar)
self.button5.pack(side=LEFT)
self.a=Entry(frame)
self.a.pack(side=BOTTOM)
self.b=Entry(frame)
self.b.pack(side=BOTTOM)
self.c=Entry(frame)
self.c.pack(side=BOTTOM)
def ouvrir(self):
#method which makes database.Its name may change
self.con=sqlite3.connect('footballdb')
self.cur=self.con.cursor()
def tabluh(self):
#method for creating table.Name may vary
#self.cur = self.con.cursor()
self.cur.execute('''CREATE TABLE team(
team_id INTEGER,
team_name stringvar(20),
team_players INTEGER)''')
def ferver(self):
self.con.close()
def insertar(self):
#self.con=sqlite3.connect('footballdb') #doubt=why these 2 lines
#self.cur=self.con.cursor() #are again needed? not in original code
a1=self.a.get()
b1=self.b.get()
c1=int(self.c.get())
self.cur.execute('''insert into team(team_id,team_name,team_players) values(?,?,?)''',(c1,a1,b1))
self.con.commit()
def listar(self):
self.cur.execute('SELECT * FROM team')
print(self.cur.fetchall())
root = Tk()
root.title('Dbase R/W')
root.geometry('700x300')
app = App(root)
root.mainloop()
| true |
2224d73582b20f4542eb637c3a40579571ed4ac3 | azzaHA/Movie-Trailer | /media.py | 1,220 | 4.21875 | 4 | """
Define Movie class to encapsulate movies attributes and methods
"""
class Movie():
"""
Define attributes and methods associated to Movie objects
* Attributes:
title (string): Movie name
story_line (string): Brief summary of the movie
trailer_youtube_id (string): trailer ID on youtube
poster_image_url (string): link to movie's poster image
* Methods:
__init__: instantiates a new Movie object with passed arguments
serialize: serializes Movie object to its JSON representation
"""
def __init__(self, movie_name, movie_story_line, movie_youtube_trailer_id,
movie_poster_url):
"""Generate a movie object and assign its value"""
self.title = movie_name
self.story_line = movie_story_line
self.trailer_youtube_id = movie_youtube_trailer_id
self.poster_image_url = movie_poster_url
def serialize(self):
"""serialize Movie object to its JSON representation"""
return{
'title': self.title,
'story_line': self.story_line,
'trailer_youtube_id': self.trailer_youtube_id,
'poster_image_url': self.poster_image_url
}
| true |
36a3e44f366e2bcf8bbab61ce3cee2f551acd80b | itsfarooqui/Python-Programs | /Program15.py | 275 | 4.125 | 4 | #15. Write a method to find number of even number and odd numbers in an array.
arr = [8, 4, 3, 6, 9, 2]
i = 0
for i in range(0, len(arr)):
if arr[i]%2 == 0:
print("Even Number: ", arr[i])
else:
print("Odd Number: ", arr[i])
i = i +1 | true |
960bc02fa729a588f9220769365fd4194fc7e0a3 | thinkphp/rabin-miller | /rabin-miller.py | 2,613 | 4.21875 | 4 | # Miller-Rabin Probabilistic Primality Test.
#
# It's a primality test, an algorithm which determines whether a given number is prime.
#
# Theory
#
# 1. Fermat's little theorem states that if p is a prime and 1<=a<p then a^p-1 = 1(mod p)
#
# 2. If p is a prime x^2 = 1(mod p) or(x-1)(x+1) = 0 (mod p), then x = 1 (mod p) or x = -1 (mod p)
#
# 3. If n is an add prime then n-1 is an even number and can be written as 2^s*d. By Fermat's Little Theorem
# either a^d = 1 (mod n) or a^2^r*d = -1 (mod n) for some 0<=r<=s-1
#
# 4. The Rabin-Miller primality test is base on contrapositive of the above claim. That is, if we can find an
# a(witness) such that a^d != 1 (mod n) and a^2^r*d != -1 (mod p) for all 0<=r<=s-1 then a is witness of compositeness
# of n and we can say n is not prime, otherwise n may be prime.
#
# 5. We test our number P for some numbers random a and either declare that p is definitely a composite or probably
# a prime.
#
# The probably that a composite number is returned as prime after k iterations is 1/4^k.
#
# The Running Time: O(k log 3 n)
#
import random
def modexp(x, y, mod):
sol = 1
i = 0
while (1<<i) <= y:
if (1<<i)&y:
sol = (sol * x) % mod
x = (x * x) % mod
i = i + 1
return sol
#
# @param n, n > 3, an odd integer to be tested for primality
# @param accuracy, a parameter that determines the accuracy of the test
# @return false, if n is composite, otherwise probably prime
#
def isPrime(n, accuracy):
# If the number is 2 or 3, then return True
if n == 2 or n == 3:
return True
# if the number is negative or oven then I have to return False
if n<=1 or n&1 == 0:
return False
# next step we write n-1 as 2^s*d
s = 0
m = n - 1
while m&1 == 0:
s += 1
m >>= 1
# now we have and s and d as well
d = (n-1) / (1<<s)
for i in range(1, accuracy + 1):
# next step we pick a random number between 2 and n-2
# we call a a witness for compositeness of n, or is called
# strong liar when is n is probably prime to a base a.
witness = random.randint(2,n-2)
q = modexp(witness, d, n)
if q == 1 or q == n - 1:
continue
for i in range(0, s):
q = modexp(q, 2, n)
if q == 1:
return False
if q == n-1:
break
return False
# return n is probably prime
return True
print isPrime(21, 3)
| true |
15b439cc89bae13fbfd7a981ce68aa5c23ecaf0f | randcyp/FIT2085 | /Practical 1/Exercise 1 - task_1.py | 1,633 | 4.21875 | 4 | # Non-assessed practical
"""
This module demonstrates a way to interface basic list
operations.
"""
__author__ = "Chia Yong Peng"
from typing import List, TypeVar
T = TypeVar('T')
list_of_items = []
def print_menu() -> None:
"""
Prints the menu.
"""
menu_items = ["append", "reverse", "print", "pop", "count", "quit"]
print("Menu: ")
for i in range(0, len(menu_items)):
print(str(i+1) + ". " + menu_items[i])
print()
def reverse(ls: List[T]) -> List[T]:
"""
Reverses a list.
:param ls: The list to be reversed
:return: The reversed list
"""
for i in range(len(ls) // 2):
ls[i], ls[len(ls) - 1 - i] = ls[len(ls) - 1 - i], ls[i]
return ls
def count(ls: List[T], obj: T) -> int:
"""
Returns the number of times an element appears in a list
:param ls: The list to iterate through
:param obj: The element to be counted
:return: The number of times an element appears in a list
"""
return len([x for x in ls if x is obj])
# Displays the menu and prompts for an option
while True:
print_menu()
option = int(input("Enter an option: "))
if option == 1:
item = input("Enter an item: ")
list_of_items.append(item)
elif option == 2:
reverse(list_of_items)
elif option == 3:
print(list_of_items)
elif option == 4:
print(list_of_items.pop())
elif option == 5:
item = input("Enter an item: ")
print(count(list_of_items, item))
elif option == 6:
exit()
else:
print("You've entered an invalid option, please try again.")
print()
| true |
461c5e56da879c382f30317af48f304d8e33840d | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 1/Exercise 033 - Sort 3 Integers.py | 697 | 4.1875 | 4 | # Exercise 33: Sort 3 Integers
# Creare un programma che legga tre numeri interi dall'utente e li mostri in ordine ordinato
# (dal più piccolo al più grande). Usate le funzioni min e max per trovare il valore più piccolo e
# quello più grande. Il valore medio può essere trovato calcolando la somma di tutti e tre i valori,
# e poi sottraendo il valore minimo e quello massimo.
a=int(input("inserisci il primo numero intero: "))
b=int(input("inserisci il secondo numero intero: "))
c=int(input("inserisci il terzo numero intero: \n"))
d=min(a, b, c)
f=max(a, b, c)
e=(a+b+c-d-f)
print("il numero più piccolo è:",d)
print("il numero intermedio è:",e)
print("il numero maggiore è:",f)
| false |
583f9a7bf7f1aa39295f404f8ad42ba4c529abb3 | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 040 - Sound Levels.py | 845 | 4.4375 | 4 | # Exercise 40: Sound Levels
# Jackhammer 130 dB
# Gas Lawnmower 106 dB
# Alarm Clock 70 dB
# Quiet Room 40 dB
Sound=float(input("Enter a number to define a sound level in decibels: "))
if Sound > 130:
Sound="The sound level is louder than a Jackhammer"
elif Sound == 130:
Sound="The sound level is Jackhammer"
elif Sound > 106 :
Sound="The sound level is between Gas Lawnmower and Jackhammer"
elif Sound == 106:
Sound="The sound level is Gas Lawnmower"
elif Sound > 70 :
Sound="The sound level is between Alarm Clock and Gas Lawnmower"
elif Sound == 70:
Sound="The sound level is Alarm Clock"
elif Sound >40 :
Sound="The sound level is between Quiet Room and Alarm Clock"
elif Sound == 40:
Sound="The sound level is Quiet Room"
else:
Sound="The sound leve is between silence and Quiet Room"
print(Sound)
| true |
93153b09c6c76b9e8b7daf4643d507e2a4bbacde | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 051 - Roots of a Quadratic Function.py | 547 | 4.1875 | 4 | # Exercise 51: Roots of a Quadratic Function
import math
a=float(input("Enter the value a: "))
b=float(input("Enter the value b: "))
c=float(input("Enter the value c: "))
discriminant = (b**2) - (4 * a * c)
print(discriminant)
if discriminant < 0:
print("has no real roots")
elif discriminant == 0:
result = (-b / (2 * a))
print(result)
else:
root1 = (- b - math.sqrt(discriminant)) / (2 * a)
root2 = (- b + math.sqrt(discriminant)) / (2 * a)
print("the first root is:", root1)
print("the second root is:", root2)
| true |
22c14c12f08fcc25ab970493f8ef05cb5b73982b | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 035 - Even or Odd.py | 208 | 4.125 | 4 | # Exercise 35: Even or Odd?
number=int(input("Enter a valid integer number: "))
number1=number % 2
if number1 == 0:
number1="the number is even."
else:
number1="the number is odd: "
print(number1)
| true |
b971b310ae02ec049a32d1bebca9ea41a6ac5fb1 | taoyuc3/SERIUS_NUS | /5.28.py | 1,699 | 4.125 | 4 | # https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
from keras.models import Sequential
from keras.layers import Dense
import numpy
# fix random seed for reproducibility
numpy.random.seed(7)
# Load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.data.csv", delimiter=",")
# split into input (X) and output (Y) variables
# the dataset has 9 cols, 0:8 will select 0 to 7, stopping before index 8
# *Numpy Arrays for ML in Python
X = dataset[:, 0:8]
Y = dataset[:, 8]
# Define a sequential model and add layers one at a time
model = Sequential()
# first layer has 12 neurons and expects 8 inputs with rectifier activation function
model.add(Dense(12, input_dim=8, activation='relu'))
# the hidden layer has 8 neurons
model.add(Dense(8, activation='relu'))
# finally the output layer has 1 neuron to predict the class (onset of diabetes or not)
model.add(Dense(1, activation='sigmoid'))
# Compile modelsurface-defect-detection
# binary_crossentropy refer to logarithmic loss
# adam refers to gradient descent
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit/Train model
# 150 iterations with the batch size 10
# these can be chosen experimentally by trial and error
model.fit(X, Y, epochs=150, batch_size=10, verbose=2)
# # Evaluate
# # we have trained our nn on the entire dataset, but only know train accuracy
# # don't know how well the algorithm might perform on new data
# scores = model.evaluate(X, Y)
# print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
# calculate predictions
predictions = model.predict(X)
# round predictions
rounded = [round(x[0]) for x in predictions]
print(rounded)
| true |
9d44df3ad84744af06d02d53553f0049c382f2d2 | Nana-Antwi/UVM-CS-21 | /distance.py | 799 | 4.125 | 4 | #Nana Antwi
#cs 21
#assignment 4
#distance.py
#write a program that calculates distance
#distance is equal to speed muliple by time
#variables
speed = 0.0
time = 0.0
distance = 0.0
var_cons = 1.0
#user input variable
speed = float(input('Enter speed: ')) #user prompts
#condition loop statements
while speed <= 0:
print('Speed must always be greater than zero')
speed = int(input('Enter speed: '))
time = int(input('Enter time: '))
while time <= 0:
print('Time must always be greater than zero')
time = int(input('Enter time: '))
#results output
print('Hour of distance treavelled')
print('---------------------------')
for var_cons in range(1, (time + 1)):
distance = var_cons * speed
print(var_cons, "\t", format(distance, ',.1f'))
| true |
0c2bc2ff035678d3f8d947124c05d6293a0c7da0 | rynoV/andrew_ng-ml | /mongo-lin-reg/src/computeCost.py | 790 | 4.3125 | 4 | import numpy as np
def computeCost(X, y, theta):
"""
Compute cost for linear regression with multiple variables.
Computes the cost of using theta as the parameter for linear regression to fit the data points in X and y.
Parameters
----------
X : array_like
The dataset of shape (m x n+1).
y : array_like
A vector of shape (m, ) for the values at a given data point.
theta : array_like
The linear regression parameters. A vector of shape (n+1, )
Returns
-------
J : float
The value of the cost function.
"""
m = y.shape[0] # number of training examples
predictions = X @ theta
differences = predictions - y
J = (1/(2*m)) * np.sum(differences**2)
return J
| true |
2a84fde9734f92965d0545bb3dd0fb0a6b06a190 | ClaudiaMoraC/Ciclo1_Python | /Clase11junioListas_Tuplas.py | 2,106 | 4.15625 | 4 | # thislist = ["apple", "banana", "cherry"]
# print(thislist)
# Longitud de lita
# thislist = ["apple", "banana", "cherry"]
# print(len(thislist))
#tipo
# mylist = ["apple", "banana", "cherry"]
# print(type(mylist))
#Acceder a un elemento de la lista
# thislist = ["apple", "banana", "cherry"]
# print(thislist[1]) # posicion 1
#La ultima posicion
# thislist = ["apple", "banana", "cherry"]
# print(thislist[-1])
#Rango
# thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
# print(thislist[2:5]) # Toma de la posicion 2 a la 5
# thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
# print(thislist[:4])#Imprime hasta la posicion 4
#Comprobar si existe
# thislist = ["apple", "banana", "cherry"]
# if "apple" in thislist:
# print("Yes, 'apple' is in the fruits list")
#Ordenar
# thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
# thislist.sort()
# print(thislist)
# thislist = [100, 50, 65, 82, 23]
# thislist.sort()
# print(thislist)
#Muestra los valores de la lista que contengan a
# fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newlist = []
# for x in fruits:
# if "a" in x:
# newlist.append(x)
# print(newlist)
#Elimiar srt
# thislist = ["apple", "banana", "cherry"]
# thislist.remove("banana")
# print(thislist)
#Eliminar int
# thislist = ["apple", "banana", "cherry"]
# thislist.pop(1)#Posicion 1
# print(thislist)
#Agregar Datos a la lista
# thislist = ["apple", "banana", "cherry"]
# thislist.append("orange")
# print(thislist)
#Insertar
# thislist = ["apple", "banana", "cherry"]
# thislist.insert(1, "orange")
# print(thislist)
#Agregar una lista a otra
# thislist = ["apple", "banana", "cherry"]
# tropical = ["mango", "pineapple", "papaya"]
# thislist.extend(tropical)
# print(thislist)
#Unir lista1 + lista2 conformando lista3
# list1 = ["a", "b", "c"]
# list2 = [1, 2, 3]
# list3 = list1 + list2
# print(list3)
#count() Número de veces que se repite a
# list1 = ["a", "b", "c","a"]
# list2 = ["2","4","2","4","6","2"]
# print("a-> ",list1.count ("a"))
# print("2-> ",list2.count ("2")) | false |
7a2aba24cf92a368bdeef9eae3951420627c2830 | nazomeku/miscellaneous | /fizzbuzz.py | 489 | 4.375 | 4 | def fizzbuzz(x):
"""Take integer and check if it is divisable by:
3: return 'fizz',
5: return 'buzz',
3 and 5: return 'fizzbuzz',
otherwise: return input as string.
Args:
x: The integer for which the condition is checked.
Returns:
Corresponding string value.
"""
if x % 3 == 0 and x % 5 == 0:
return "fizzbuzz"
elif x % 3 == 0:
return "fizz"
elif x % 5 == 0:
return "buzz"
else:
return str(x)
| true |
cc79f38420b39113f7d988a6171bdf3fd6f27e2d | UmmadisettyRamsai/ramsai | /labprogramme2.py | 1,140 | 4.46875 | 4 |
# basic operations on single array
#A PYTHON PROGRAM TO PERFORM UNIARY OPERATIONS
import numpy as np
a = np.array([1, 2, 5, 3])
# add 2 to every element
print ("Adding 2 to every element:", a+2)
# subtract 3 from each element
print ("Subtracting 3 from each element:", a-3)
# multiply each element by 10
print ("Multiplying each element by 10:", a*10)
# square each element
print ("Squaring each element:", a**2)
# modify existing array
a *= 2
print ("Doubled each element of original array:", a)
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)
arr = np.array([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
# maximum element of array
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",
arr.max(axis = 1))
# minimum element of array
print ("Column-wise minimum elements:",
arr.min(axis = 0))
# sum of array elements
print ("Sum of all array elements:",
arr.sum())
| true |
ab7ef4dd24c0e21a857cd1a8c28c9fdb36739169 | Psycadelik/sifu | /general/is_integer_palindrome.py | 486 | 4.15625 | 4 | """
Check Whether a Number is Palindrome or Not
Time complexity : O(log 10(n)).
We divided the input by 10 for every iteration,
so the time complexity is O(log10(n))
Space complexity : O(1)
"""
def is_palindrome(num):
original_num = num
reversed_num = 0
while (num != 0):
num, rem = divmod(num, 10)
reversed_num = (reversed_num * 10) + rem
return original_num == reversed_num
assert is_palindrome(121) == True
assert is_palindrome(1212) == False
| true |
1f3533dc0dd324766f4e7d39681dbdf434ad0d4d | MPeteva/HackBulgariaProgramming101 | /Week0/1-PythonSimpleProblemsSet/T11_CountSubstrings.py | 330 | 4.25 | 4 | def count_substrings(haystack, needle):
count_of_occurrences = haystack.count(needle)
return count_of_occurrences
def main():
String = input("Input a string: ")
Word = input("Input a word to count occurrences of it in string: ")
print (count_substrings(String, Word))
if __name__ == '__main__':
main()
| true |
5445bd1df1895ec3906c10d5362b51d138400726 | benjamin0905883618/goCode_LeetCode | /Day_5.py | 2,838 | 4.40625 | 4 | """
這道題目曾出現在 Uber 的面試中。
給定一個 linked list 的 head node, 刪除所有總和為 0 的 sub linked lists,
直到此 linked list 不存在一個總和為 0 的 sub linked list 為止,
最後 return 刪除後的 linked list head node。
Example 1:
Input: 3 -> 2 -> 1 -> -1 -> -2 -> None
Output: 3 -> None
Explanation: Sub list 2 -> 1 -> -1 -> -2 的總和為 0, 所以可把此 sub list 刪除
Example 2:
Input: -5 -> 2 -> 1 -> -3 -> 10 -> 1 -> 2 -> -2 -> None
Output -5 -> 10 -> 1 -> None
Explanation: Sub lists 2 -> 1 -> -3 及 2 -> -2 各自的總和為 0, 所以可把這兩個 sub lists 刪除
"""
# Definition of a linked list node
class ListNode:
# @param val: int
def __init__(self, val):
self.val = val
self.next = None
class Solution:
# @param head: ListNode
# @retrun ListNode
def removeZeroSumSublists(self, head):
# Implement me
new_head = ListNode(0)
temp_head = new_head
cursor = head
while True:
cursor_1 = cursor
sum = 0
#if sum == 0 then stop loop and delete the sublist
while True:
#print(cursor_1.val)
sum += cursor_1.val
if sum == 0:
break
if cursor_1.next.val != None:
cursor_1 = cursor_1.next
else:
break
#delete the sublist or merge the sublist
if sum == 0:
if cursor_1.next.val == None:
temp_head.next = ListNode(None)
break
else:
cursor = cursor_1.next
else:
temp_head.next = cursor
temp_head = temp_head.next
if temp_head.val == None:
break
cursor = cursor.next
return new_head.next
#outpu list
def print_List(root):
cursor = root
while True:
print(cursor.val,end = " ")
if cursor.next != None:
cursor = cursor.next
else:
break
#input
input = input().split(">")
if input[0] == None:
print(None)
else:
root = ListNode(int(input[0]))
cursor = root
for i in range(1,len(input)):
if input[i] == "None":
temp = ListNode(None)
cursor.next = temp
break
temp = ListNode(int(input[i]))
cursor.next = temp
cursor = cursor.next
#print_List(root)
#print()
#call function and validation whether it is good enough
s = Solution()
new_List = s.removeZeroSumSublists(root)
print_List(new_List)
print()
| false |
15836a7c158c46605a536ab7b889119eed45fe7b | SaudiWebDev2020/Sumiyah_Fallatah | /Weekly_Challenges/python/week5/wee5day3.py | 2,632 | 4.3125 | 4 | # Create a queue using 2 stacks. A hint: stack1 will hold the contents of the actual queue, stack2 will be used in the enQueueing
# Efficiency is not the goal!
# Efficiency is not the goal!
# Efficiency is not the goal!
# The goal is to practice using one data structure to implement another one, in our case Queue from 2 Stacks
# Queue is FIFO --> First In First out
# Stack is LIFO --> Last In First Out
class StackNode:
def __init__(self, value=None, next=None):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = None
self.tail = None
class QueueOfStacks:
class StackNode:
def __init__(self, value=None, next=None):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = None
self.tail = None
# def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def front(self):
if self.head == None:
return None
else:
print('top is :')
print (self.head.value)
def isEmpty(self):
if self.head == None:
print ("this stack is empty")
else:
print ("this stack is not empty")
def size(self):
temp = self.head
count = 0
while(temp):
count+=1
# print('value', temp.value)
temp = temp.next
print('size is :', count)
return count
def deQueue(self):
temp = 0
if self.head == self.tail:
self.head = None
self.tail = None
else:
temp = self.head
self.head = self.head.next
return temp.value
def enQueue(self, value):
if self.head == None:
new_node = StackNode(value)
self.head = new_node
self.tail = new_node
else:
new_node = StackNode(value)
self.tail.next = new_node
self.tail = new_node
# Optional
# def showQS(self):
# pass
# head = self.head
# while(head):
# print(head.value)
# head = head.next
stack1 = QueueOfStacks.Stack()
stack2 = QueueOfStacks.Stack()
stack1.isEmpty()
print('*'*70)
stack2.isEmpty()
stack1.enQueue(7)
# stack1.showQS()
print(stack1.front())
stack1.isEmpty()
print('*'*70)
print(stack1.deQueue())
stack1.isEmpty() | true |
c059e02dfe1f9c556b82de12ee26cd89a810db93 | ton4phy/hello-world | /Python/55. Logic.py | 253 | 4.28125 | 4 | # Exercise
# Implement the flip_flop function, which accepts a string as input and, if that string is 'flip',
# returns the string 'flop'. Otherwise, the function should return 'flip'.
def flip_flop(arg):
return 'flop' if arg == 'flip' else 'flip'
| true |
ca71548c786da72de4c83531cdba7a5d8e6f3519 | ton4phy/hello-world | /Python/57. Cycles.py | 379 | 4.3125 | 4 | # Exercise
# Modify the print_numbers function so that it prints the numbers in reverse order. To do this,
# go from the top to the bottom. That is,
# the counter should be initialized with the maximum value,
# and in the body of the loop it should be reduced to the lower limit.
def print_numbers(n):
while n > 0:
print(n)
n = n - 1
print('finished!')
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.