blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b0cea73eafad1a0327f69801d0067a5e1c32010a | cristinamais/exercicios_python | /Exercicios Estruturas Logicas e Condicionais/18.py | 1,425 | 4.40625 | 4 | """
18 - Faça um programa que mostre ao usuário um menu com 4 opções de operações
matemáticas (as básicas por exemplo). O usuário escolhe umas das opções e o seu
programa então pede dois valores numéricos e realiza a operação, mostrando o re
sultado e saindo.
"""
num1 = float(input("Digite o primeiro número: "))
num2 = float(input("Digite o segundo múmero: "))
opcao = 0
while opcao != 6:
print('''\n( 1 ) Somar \n( 2 ) Subtrair \n( 3 ) Multiplicar \n( 4 ) Dividir \n( 5 ) Colocar números novos \n( 6 ) Sair''')
opcao = int(input("Escolha uma das opções acima: "))
if opcao == 1:
soma = num1 + num2
print(f'A soma entre os números {num1} + {num2} é: {soma}')
elif opcao == 2:
sutrair = num1 - num2
print(f'A subtração entre os números {num1} - {num2} é: {sutrair}')
elif opcao == 3:
multiplicar = num1 * num2
print(f'A multiplicação entre os dois números {num1} x {num2} é: {multiplicar}')
elif opcao == 4:
dividir = num1 / num2
print(f'A divisão entre os números {num1} / {num2} é: {dividir:.2f}')
elif opcao == 5:
print('Digite números novos')
num1 = int(input("Digite o primeiro número: "))
num2 = int(input("Digite o segundo múmero: "))
elif opcao == 6:
print('Sair do programa')
print('>>>>>> Fim do programa <<<<<<')
| false |
2ddb71b98fa70291fa0b3b895e9e86ab0003ba61 | Hscpro/Python-Study | /Animal.py | 877 | 4.1875 | 4 | #!/usr/bin/env python3
class Animal(object):
owner = 'jack1'
#动物的名称
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_name(self,value):
self.__name = value
@classmethod
def get_owner(cls):
return cls.owner
class Dog(Animal):
#狗的叫声,继承Animal
owner = 'jack2'
def make_sound(self):
print(self.get_name() + '的叫声是汪汪汪')
class Cat(Animal):
#猫的叫声,继承Animal
def make_sound(self):
print(self.get_name() + '的叫声是喵喵喵')
if __name__ == '__main__':
#多态
animals = [Dog('旺财'), Cat('Kitty'), Dog('来福'), Cat('Betty')]
for animal in animals:
animal.make_sound()
print(Dog('旺财').get_owner())
print(Animal.get_owner()) | false |
6045bc04be311fe39536317c887401cf2f1717f6 | thejose5/Motion-Planning-Algorithms | /Basic/BFS.py | 2,810 | 4.375 | 4 | print("DEPTH FIRST SEARCH ALGORITHM")
print("The graph is implemented using dictionaries. The structure of the dictionary is as follows: {Node1:{NeighbourNode1:[<distance b/w nodes>,<heuristic>],...},Node1:{NeighbourNode1:[<distance b/w nodes>,<heuristic>],...} and so on\n\n")
graph = {'A':['S','B'],
'B':['A'],
'S':['G','C','A'],
'C':['E','F','D','S'],
'G':['S','F','H'],
'E':['H','C'],
'F':['C','G'],
'D':['C'],
'H':['G','E']}
startNode = 'A'
goalNode = 'H'
print("Start Node: ",startNode)
print("Goal Node: ",goalNode)
#currentNode = startNode
open = [startNode]
closed = []
paths = [startNode];
flag = False
print("We define the following variables: \nopen: Queue containing nodes left to explore. Initialized with start node. \nclosed: List of explored nodes. \npaths: Queue of all possible paths")
print("\nInitially, closed = ",closed,"open = ",open," paths = ",paths)
print("\n\n #################### Algorithm begins here. Iterations end when open is empty #####################")
iter = 1
while len(open)!=0:
print(" \nITERATION ", iter)
currentNode = open.pop(0)
print(" Current node is the top of open queue:", currentNode)
adm_nbrs = [];
print("Iterate over every neighbour of current Node ")
for i in range(len(graph[currentNode])):
print("Neighbour:", graph[currentNode][i])
print("is ", graph[currentNode][i], " the goal node?")
if graph[currentNode][i] == goalNode:
print("Yes")
flag = True
break
print("No. Then is the neighbour is neither already explored nor in the open stack?")
if graph[currentNode][i] not in closed and graph[currentNode][i] not in open:
print("Yes. Then add ",graph[currentNode][i]," to open and also set it as an admissible neighbour.")
open.append(graph[currentNode][i])
# print(open)
adm_nbrs.append(graph[currentNode][i])
if flag==True:
print("Then set final series as the top of the paths queue + the goal node")
final_series = paths.pop(0)+goalNode
break;
print("After iterating through all neighbours of ",currentNode," add it to closed")
closed.append(currentNode)
# print(adm_nbrs)
print("Add new items to back of path queue. Each of these paths will be the path till current node + 1 of the admissible neighbours")
prev_series = paths.pop(0)
for i in adm_nbrs:
# prev_series = prev_series+i
paths.append(prev_series+i)
print("After iteration number", iter, "\nopen = ", open, "\nclosed = ", closed, "\npaths = ",
paths)
iter = iter+1
# print(prev_series)
print("The final path is")
print(final_series)
#print(currentNode)
| true |
edb281a7b109cf17fcd3e57aec82dd125b51de60 | imakash3011/PythonFacts | /Maths/DoubleDivision.py | 413 | 4.1875 | 4 | # ###################### Double division
print(-5//2)
print(-5.0//2)
# ################################# Power operator
# Right associative (right to left)
print(2**1**2)
print(1**3**2)
# ############################ No increment and decrement operators
x = 10
print(x)
# x++
x+=1
print(x)
# ############################ Negative Module
# (-5%4) => (-8+3)%4 =3
# 8 is next multiple after 5
print(-5%4) | true |
7e0fcc5cac0753e25e70f69a63388b358ff6aa1d | lyf1006/python-exercise | /7.用户输入和while循环/7.2/tickets.py | 202 | 4.3125 | 4 | tip = "How old are you?"
while True:
age = input(tip)
if int(age) < 3:
print("票价为0$")
elif int(age) <= 12:
print("票价为10$")
else:
print("票价为15$") | false |
d8eeb69854f7a00b908e5b9b209684c46a3bc887 | lyf1006/python-exercise | /7.用户输入和while循环/7.2/pizza.py | 244 | 4.125 | 4 | tip = "Please enter an ingrident you want to add: "
tip += "\n(Enter 'quit' when you are finished)"
while True:
ingrident = input(tip)
if ingrident == "quit":
break
else:
print("We will add this ingrident for you.")
| true |
8a46f1f736b1c5f782f9cfbd385ea5b01e0379e6 | DD-PATEL/AkashTechnolabs-Internship | /Basic.py | 1,156 | 4.28125 | 4 | #Task 1- printing value of variables and finding variable type
a=7
b=3.6
c= "DD"
print("value of a is :", a)
print("value of b is :", b, type)
print(c)
#Task 2- Basic string commands such as printing and slicing of string
name = "Divyesh"
print(name)
print(name[1:5])
print(name[:4])
print("Hello", name)
#Task 3- Basic commands for list such as printing a list and creating a new list
l1 = [10, 'Oreo', 6.9, "Divyesh"]
print("l1 =" ,l1)
print(l1[1])
list =[]
x= int(input("Enter number of elements in list :"))
for i in range(0,x):
element=input("Enter value of Element: ")
list.append(element)
print(list)
#Task 4- Basic Tuple Commands such as printing, slicing and creating a new tuple
T1 = (8, 420, 10.7, "Attitude")
print("Third element of the tuple: ", T1[2])
print(T1[1:3])
list =[]
x= int(input("Enter number of Elements in tuple: "))
for i in range(0,x):
element=input("Enter value of Element: ")
list.append(element)
T2= tuple(list)
print(T2)
#Task 5- Basic Dictionary Commands such as printing value of a specific key
D1= {1: "DD", 2: "Patel", 3: 9}
print(D1[2]) | true |
14a14730776ee546b12942ad8145261b531f9e13 | mail-vishalgarg/pythonPracticeOnly | /Array/palindromString.py | 505 | 4.125 | 4 | def palindromString(str):
print "reverse string:",str[::-1]
if str == str[::-1]:
print "palindrom"
else:
print "not a palindrom"
def palindromString2(str):
revStr = ''
i = len(str)
while i > 0:
revStr = revStr + str[i -1]
i = i - 1
print 'rev str:',revStr
if revStr == str:
print "palindrom"
else:
print 'not a palindrom'
if __name__ == '__main__':
str = 'abcd'
palindromString(str)
palindromString2(str) | false |
d9881c031ca58a90e6bc1407f9e935b8c23a457e | dannymccall/PYTHON | /password_generator.py | 1,852 | 4.125 | 4 | from tkinter import messagebox
import random
import tkinter as tk
def password_generator():
#Opening a try block
try:
#declaring a variable pw as a string without initialising
pw = str()
#Getting the input from the text box
length = text_field_1.get()
if length == '':
messagebox.showerror('error', 'Enter your length of characters')
#declaring a variable called characters to hold the password characters
charactors = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%!"
#Converting the length to an integer
number = int(length)
#Looping through length
for i in range(number):
#Generating the password
pw = pw + random.choice(charactors)
return pw
#Catching a value error
except ValueError:
messagebox.showerror('error', 'Inputs should be numbers only')
#Displaying the password
def pass_display():
password = password_generator()
# display the password in a new window
password_dislay = tk.Text(master=window, height=10, width=30)
password_dislay.grid(column=0, row=3)
password_dislay.insert(tk.END, password)
def clear_button():
text_field_1.delete(0)
#--Master window--
window = tk.Tk()
window.title("Welcome to my app")
size = "400x400"
window.geometry(size)
#---Labels---
label_1 = tk.Label(text="Welcome to my Random Password Generator")
label_1.grid(column=0, row=0)
label_2 = tk.Label(text="Enter your number of characters")
label_2.grid(column=0, row=1)
#---Text fields ----
text_field_1 = tk.Entry()
text_field_1.grid(column=1, row=1)
#---Buttons----
button_1 = tk.Button(text="CLEAR", command=clear_button)
button_1.grid(column=1, row=2)
button = tk.Button(text="Get Your Password", bg="red", command=pass_display)
button.grid(column=0, row=2)
window.mainloop()
| true |
0bd4bead6a5c5b6366f09fd6ff33c670b0a64635 | Mudando/Python | /naleatorios.py | 433 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 24 14:42:57 2021
@author: gilson
"""
import random
#numero aleatório de 0 a 10
numero = random.randint(0,10)
print (numero)
#Forcar o python a selecionar sempre o mem numero
random.seed(1)
numero2 = random.randint(0,10)
print (numero2)
#Seleciona o numero aleatório de uma lista
lista = [1,2,4,6,3,7,8,9,10]
numero3 = random.choice(lista)
print (numero3)
| false |
bf82b6adb9dac5134d161d9c6978919f6dffb57b | Dhruv2550/Aspect-Ratio-Calculator | /Aspect Ratio Calculator.py | 876 | 4.28125 | 4 | def aspect_ratio(w, h, nw, nh,nratio):
if nratio == 'width':
nw = int(input("Enter the New Width\n"))
if w - h < 0:
nh = nw * (h / w)
else:
nh = nw / (w / h)
elif nratio == 'height':
nh = int(input("Enter the New Height\n"))
if w - h > 0:
nw = nh / (h / w)
else:
nw = nh * (w / h)
return nw,nh
print("Aspect Ratio Calculator")
print('-'*30)
quit=''
while quit=='':
w = int(input("What is the existing width"))
h = int(input("What is the existing height"))
nratio = input('Do you want to provide a new width or height')
nh = 0
nw = 0
dimensions = aspect_ratio(w, h, nw, nh,nratio)
print(f'The New Dimensions are {dimensions}')
print('-'*30)
quit=input('Press Enter to Calculate Another Ratio or Press any other Key to Quit')
| false |
798e45402c0a205c7ce97410213f8402e09706cb | RomanoNRG/Cisco-DevOps-MDP-02 | /Task2/Dicts_vs_List_Time_tradeoff.py | 529 | 4.28125 | 4 | # Program to demonstrate
# space-time trade-off between
# dictionary and list
# To calculate the time
# difference
import time
# Creating a dictionary
d ={'john':1, 'alex':2}
x = time.time()
# Accessing elements
print("Accessing dictionary elements:")
for key in d:
print(d[key], end=" ")
y = time.time()
print("\nTime taken by dictionary:", y-x)
# Creating a List
c =[1, 2]
x = time.time()
print("\nAccessing List elements:")
for i in c:
print(i, end=" ")
y = time.time()
print("\nTime taken by dictionary:", y-x)
| true |
118809abf08a5bdd94c9db133c55f07ae554c675 | Mullins69/SimplePYcalculator | /main.py | 1,571 | 4.25 | 4 | print("Welcome to Mullins simple Calculator")
print("Do you want to use the calc, yes or no?")
question = input("yes or no, no caps: ")
if question == "yes":
print("Which would you like to use, addition, subtraction , division or multiplication? ")
question2 = input("no caps : ")
if question2 == "addition":
input1 = int(input("Please Enter Value 1: "))
input2 = int(input("Please Enter Value 2: "))
print(str(input1) + " plus " + str(input2) + " = " + str(input1 + input2) )
print("thank you for using my addition calculator , LOL ")
if question2 == "subtraction":
input1 = int(input("Please Enter Value 1: "))
input2 = int(input("Please Enter Value 2: "))
print(str(input1) + " minus " + str(input2) + " = " + str(input1 - input2))
print("thank you for using my subtraction calculator , LOL ")
if question2 == "division":
input1 = int(input("Please Enter Value 1: "))
input2 = int(input("Please Enter Value 2: "))
print(str(input1) + " divide by " + str(input2) + " = " + str(input1 / input2))
print("thank you for using my division calculator , LOL ")
if question2 == "multiplication":
input1 = int(input("Please Enter Value 1: "))
input2 = int(input("Please Enter Value 2: "))
print(str(input1) + " multiply by " + str(input2) + " = " + str(input1 * input2))
print("thank you for using my multiplication calculator , LOL ")
else:
print("why did you have to choose no? aii... ")
| true |
5cc753ba1aeb3b148cd575fbcb57c47313e15b08 | pnkumar9/linkedinQuestions | /revstring.py | 452 | 4.1875 | 4 | #!/usr/local/bin/python3
# recursive
def reverse1(mystring):
if (len(mystring) == 0):
return("")
if (len(mystring) == 1):
return(mystring)
newstring=reverse1(mystring[1:])+mystring[0]
return(newstring)
# non-recursive without a lot of adding and subtracting
def reverse2(mystring):
newstring=""
for i in range(len(mystring)-1,-1,-1):
newstring=newstring+mystring[i]
return(newstring)
print(reverse1("foobar"))
print(reverse2("foobar"))
| true |
940dfca49d079b7fe7476807ca550de96730c0b6 | longfeili86/math487 | /Homework/HW2/funcDefs.py | 1,634 | 4.375 | 4 | # This is the starter code for homework2. Do not change the function interfaces
# and do not change the file name
#######################################################
#Problem 1
#######################################################
# write a function that solves the linear system Ax=b, where A is an n by n tridiangal matrix with -2 on the main diagnal and 1 on the diagnals above and below the main diagnal
# b is vector b=[0,0,0,.....,-2*n+(n-1)]
#
# you can have an
def solveLinearSystem(n,debug=False):
# create the matix A and right-hand side b using the methods we discussed in class
A=
b=
#solve the system Ax=b using the "solve" method scipy's linalg submodule
x=
return x
#######################################################
#Problem 2
#######################################################
# write a function to interpolate data points (xdata,ydata) using
# both linear and cubic spline interpolations.
def interpolation1d(xdata,ydata,debug=False):
# the interpolant using linear spline interpolation
f_1=
# the interpolant using cubic spline interpolation
f_3=
return f_1,f_3
#######################################################
#Problem 3
#######################################################
# write a function to interpolate data points (xdata,ydata,zdata) using
# both linear and cubic spline interpolations.
def interpolation2d(xdata,ydata,zdata,debug=False):
# the interpolant using linear spline interpolation
f_1=
# the interpolant using cubic spline interpolation
f_3=
return f_1, f_3
| true |
e45b63de61aa0edd4abf61641f145b7c5802af29 | Thunder-Ni13/python-exercicios-guanabara | /PythonTest/aula007ex005.py | 294 | 4.15625 | 4 | n = int(input('Digite um número: '))
a = n - 1
b = n + 1
print('Analisando o número {}, seu antecessor é {} e seu sucessor é {} '. format(n, a, b))
n = int(input('Digite um número: '))
print('Analisando o número {}, seu sucessor é {} e seu antecessor é {} '. format(n, (n+1), (n-1)))
| false |
c6e9d1e78e796b8475a8a215709ac84e169e4935 | PeterFriedrich/project-euler | /p4.py | 1,242 | 4.1875 | 4 | # A palindromic number reads the same both ways. The largest
# palindrome made from the product of two 2-digit numbers
# is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
# Palindrome function
def isPal(num):
numAux = num
revnum = 0
# takes number and divides by ten to pull of the right digit
while numAux > 0:
rDigit = numAux % 10
# appends the right digit to the left of a new number
revnum = revnum * 10 + rDigit
numAux = numAux // 10
# compare both numbers to see if equal
if num == revnum:
return True
else:
return False
pal = []
# loop to put all palindromes in a list
for i in range(10000,998001):
if isPal(i):
pal.append(i)
lenpal = int(len(pal))
print(lenpal)
final = []
# Function to find out if composite of two 3 digit factors
def isthree(comp):
for i in range(100,999):
check = comp//i
modcheck = comp % i
if 100 < check < 999 and modcheck == 0 :
return comp
# check the palindrome list and return list with number if true
for i in range(0,lenpal):
final.append(isthree(pal[i]))
print(final)
| true |
870e03d5aba2162f04f5ae6622d0fcee98d4daf5 | sneaker-rohit/playing-with-sockets | /multithreaded echo app/client.py | 1,094 | 4.125 | 4 | # The program is intented to get used familarised with the sockets.
# The client here sends a message to the server and prints the response received
# Client side implementation. Below are the set of steps needed for the client to connect
# 1. Connect to the address
# 2. Send a message to the server
# Author: Rohit P. Tahiliani
import socket
PORT = 1000
HOST = '127.0.0.1'
# Maximum amount of data to be received at once.
receiveBuffer = 4096
# Creating a Socket
clientSocket = socket.socket (socket.AF_INET,socket.SOCK_STREAM)
# Connect to the remote server using appropriate address
clientSocket.connect ((HOST,PORT))
print "[+] Connected to the server..."
# Send a message to the server
message = raw_input ("Enter the message/Quit: ")
while message != "Quit":
clientSocket.send (message)
data = clientSocket.recv (receiveBuffer)
print "[+] Message from server..."
if data:
print data
else:
print "No data received from the client"
message = raw_input ("Enter the message/Quit: ")
# Close the connection
print "[-] Terminating the connection to server..."
clientSocket.close ()
| true |
960443d850e10687b32b0df36aee867bdd8544d4 | AntonioFry/messing-with-python | /main.py | 738 | 4.125 | 4 | print("Welcome to my first game!")
name = input("What is your name? ")
age = int(input("What is your age? "))
health = 10
if age >= 18:
print("You are old enough!")
wants_to_play = input("Do you want to play? ").lower()
if wants_to_play == "yes":
print("Let's play!")
left_or_right = input("First choice... (left/righ)? ")
if left_or_right == 'left':
ans = input("You find a bridge. Do you cross it? (yes/no)? ")
if ans == 'yes':
print("The bridge breaks and you die...")
else:
print("You turn around and head back the way you came... good job.")
else:
print("You fell to your death...")
else:
print("Bye.")
else:
print("You are not old enough to play.")
| true |
9c91dbfc6ced145210d7fb46eee096167fc0db64 | reksHu/BasicPython | /numpyModul/stockRange.py | 402 | 4.15625 | 4 | # 练习:计算股票价格的波动范围:在一定时期内最高的最高价 - 最低的最低价
import numpy as np
def read_csv():
fileName="aapl2.csv"
high_prices, low_prices = np.loadtxt(fileName,delimiter=',',usecols=(4,5),unpack=True)
return high_prices,low_prices
high_prices,low_prices = read_csv()
stock_range = np.max(high_prices) - np.min(low_prices)
print(stock_range) | false |
e2df04dc838999bf07badb47ae8990811931f23e | makhmudislamov/coding_challanges_python3 | /module_2/last_factorial.py | 1,057 | 4.28125 | 4 | """
Prompt:
Given a non-negative number, N, return the last digit of the factorial of N.
The factorial of N, which is written as N!, is defined as the product of all of the integers from 1 to N.
Given 3 as N, the factorial is 1 x 2 x 3 = 6
Given 6 as N, the factorial is 1 x 2 x 3 x 4 x 5 x 6 = 720
Given 9 as N, the factorial is 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 = 362,880
As you can see, the number can grow to be quite large, quite quickly.
Write a function that will return only the last digit of N!, given N.
"""
def factorial_recursive(n):
"""
Return the factorial of the given int
"""
# base case
if n < 2:
return 1
else:
return n * factorial_recursive(n-1)
def last_factorial_digit(n):
# fairly easy calculation. after 5! the there is a pattern = last digit is 0
if n < 5:
factorial = str(factorial_recursive(n))
print(f"factorial is {factorial}")
return int(factorial[-1])
else:
# because there are 2 and 5 in the multiplication
return 0
print(last_factorial_digit(200))
| true |
75aa205b3e5494ce8e83effedfd0db31e08b4d98 | makhmudislamov/coding_challanges_python3 | /module_4/valid_anagram.py | 876 | 4.34375 | 4 | """
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase letters.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution?
"""
def valid_anagram(s, t):
# base case
# if lengths of two string are not equal
# not anagram
if len(s) != len(t):
return False
for char in s:
print(char)
if char not in t:
return False
for char in t:
if char not in s:
return False
return True
# iterate throgh first string
# if each char is in the second string
# return true
# else
# false
# s = "cac"
# t = "car"
s = "anagram"
t = "nagaram"
print(valid_anagram(s, t))
| true |
75ea05edc4c6fd9a65e542a5998f8cf7efb15ad6 | makhmudislamov/coding_challanges_python3 | /module_4/find_index.py | 1,001 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Examples:
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
"""
def find_index(sorted_list, target):
# iterate over the input
# if an element is equal to target
# return its index
# else
# return the index of element that is target-1
if not sorted_list or target < sorted_list[0]:
return 0
for num in sorted_list:
index = sorted_list.index(num)
if num == target:
return sorted_list.index(num)
elif sorted_list[index] < target < sorted_list[index + 1]:
return index + 1
elif target > sorted_list[len(sorted_list)-1]:
return len(sorted_list)
sorted_list = [1, 3, 5, 9]
target = 3
print(find_index(sorted_list, target))
| true |
b96f08921bedc7c0faa7810428c108fbe6b42acd | makhmudislamov/coding_challanges_python3 | /module_12_trees/balance_tree_stretch.py | 2,562 | 4.53125 | 5 | """
Given this implementation of a Binary Tree, write a function to balance the
binary tree to reduce the height as much as possible.
For example, given a tree where the nodes have been added in an order
such that the height is higher than it could be:
Nodes have been added in this order:
tree = Tree()
tree.add(Node(6))
tree.add(Node(27))
tree.add(Node(15))
tree.add(Node(10))
tree.add(Node(13))
tree.add(Node(8))
Hint:
Make sure to use the add() method in your balancing- you may have to traverse the whole tree,
and re-add all nodes to the tree in a particular order.
If so, you've probably seen this ordering somewhere before...
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
## INSTEAD, non binary
self.children = []
self.parent = None
class Tree:
def __init__(self):
self.root = None
def in_order_traversal(self):
def dfs(node):
if node:
dfs(node.left)
print(node.data)
dfs(node.right)
dfs(self.root)
def level_order_traversal(self):
if not self.root:
return
queue = [self.root]
while len(queue) > 0:
current_node = queue.pop(0)
if current_node.left:
queue.append(current_node.left)
print(current_node.data)
if current_node.right:
queue.append(current_node.right)
def add(self, node):
if not self.root:
self.root = node
return
def insert(root, node):
if root.data > node.data:
if root.left is None:
root.left = node
else:
insert(root.left, node)
else:
if root.right is None:
root.right = node
else:
insert(root.right, node)
insert(self.root, node)
def height(self):
def get_height(node):
if node is None:
return 0
else:
left_height = get_height(node.left)
right_height = get_height(node.right)
if left_height > right_height:
return left_height + 1
else:
return right_height + 1
return get_height(self.root)
def balance(self):
# write a function to reduce the height of this tree as much as possible
pass
| true |
92e2e4ebb03fae16e319447a29fe27117854d889 | jprice8/leetcode | /linked_lists/real_python.py | 1,528 | 4.15625 | 4 |
# Class to represent the Linked List
class LinkedList:
def __init__(self):
self.head = None
# method adds element to the left of the linked list
def addToStart(self, data):
# create a temp node
tempNode = Node(data)
tempNode.setLink(self.head)
self.head = tempNode
del tempNode
# method displays linked list
def display(self):
start = self.head
if start is None:
print("empty list")
return False
while start:
print(str(start.getData()), end=" ")
start = start.link
if start:
print("-->", end=" ")
print()
# method returns and removes element at received position
def removePosition(self, position):
data = self.atIndex(position)
self.remove(data)
return data
# Class to represent each node of the Linked List
class Node:
# default value of data and link is none if no data is passed
def __init__(self, data=None, link=None):
self.data = data
self.link = link
# method to set link field of Node
def setLink(self, node):
self.link = node
# method returns data field of the Node
def getData(self):
return self.data
# Main method
# create linkedlist
myList = LinkedList()
# add some elements to the start of linkedlist
myList.addToStart(5)
myList.addToStart(4)
myList.addToStart(3)
myList.addToStart(2)
myList.addToStart(1)
myList.display() | true |
ce739ae410b3bc59a42c8fa2d7952f1951d62935 | jaeyoon-lee2/ICS3U-Unit1-04-Python | /area_and_perimeter.py | 391 | 4.28125 | 4 | #!/user/bin/env python3
# Created by: Jaeyoon
# Created on: Sept 2019
# This program calculates the area and perimeter of rectangle
# with dimensions 5m x 3m
def main():
print("If the rectangle has the dimensions:")
print("5m x 3m")
print("")
print("area is {}m^2".format(3*5))
print("perimeter is {}m".format(2*(3+5)))
if __name__ == "__main__":
main()
| true |
b4b64d43aad905857456d36c61b424c53d824cc7 | TehWeifu/CoffeeMachine | /Problems/Long live the king/task.py | 233 | 4.15625 | 4 | column = int(input())
row = int(input())
if column == 1 or column == 8:
if row == 1 or row == 8:
print("3")
else:
print("5")
else:
if row == 1 or row == 8:
print("5")
else:
print("8")
| false |
67ed8715ed674b3f1ed1994989cd4650597a7226 | hemanthgr19/practise | /factorial.py | 318 | 4.125 | 4 | def fun(tea):
if tea < 0:
return 0
#print("0")
elif tea == 0 or tea == 1:
return 1
#print("the value is equal to 0")
else:
fact = 1
while (tea > 0):
fact *= tea
tea -= 1
return fact
tea = 3
print(tea, fun(tea))
#print(n)
| true |
bf24b473c81d7f6a323f440b2caf1d030ee7fa6d | khoIT/10xclub-hw | /sorting/sorting_runtime.py | 1,726 | 4.125 | 4 | from datetime import datetime
import random, sys
from merge_sort import merge_sort, merge_sort_iterative
from heapsort import heapify, heapsort
def bubble_sort(arr):
i = 0
while i < len(arr):
j = 0
while j < len(arr)-1:
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
j += 1
i += 1
return arr
def insertion_sort(arr):
i = 0
while i < len(arr):
j = 0
while arr[j] < arr[i] and j < i:
j += 1
temp = arr[i]
# could save this loop by letting j going backwards
for idx in range(j, i):
arr[j+1] = arr[j]
arr[j] = temp
i += 1
return arr
def selection_sort(arr):
idx = 0
while idx < len(arr):
min_idx = idx
for j in xrange(idx, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[idx], arr[min_idx] = arr[min_idx], arr[idx]
idx += 1
return arr
def constructin_array(size):
arr = []
for i in xrange(0, size):
# arr[i] = i
# arr[i] = size-i
arr.append(random.randrange(0, size))
return arr
def time_a_function(func, arg):
now = datetime.now()
arg = func(arg)
print "{} took {}".format(func.__name__, datetime.now() - now)
return arg
if __name__ == "__main__":
arr = constructin_array(30000)
time_a_function(merge_sort, arr)
time_a_function(merge_sort_iterative, arr)
arr = time_a_function(heapsort, arr)
time_a_function(insertion_sort, arr)
time_a_function(selection_sort, arr)
time_a_function(bubble_sort, arr)
print ("Sorted arr: First 100: {}. last 100: {}".format(arr[:100], arr[-100:]))
| false |
9199cc6e779fbd4e835a94c0f832a1121430905a | khoIT/10xclub-hw | /trie/two_strings_to_form_palindrome.py | 614 | 4.15625 | 4 | def two_strings_palindrome(arr):
reversed = {}
for string in arr:
if string in reversed:
return reversed.get(string), string
if len(string) > 1:
reversed[string[::-1]] = string
reversed[string[:-1][::-1]] = string
for string in arr:
if string in reversed:
return reversed.get(string), string
if __name__ == "__main__":
print two_strings_palindrome(['abc', 'ta', 'ba','cba'])
print two_strings_palindrome(['abc', 'cd', 'c', '123', '3', 'cba'])
print two_strings_palindrome(['abc', 'ba']) # {'cba': 'abc'; 'ba': 'abc'}
| false |
985c9b997b6a16a94014ae14bafe059812cd2621 | Creedes/HarvardCourse | /python/lambda.py | 318 | 4.1875 | 4 | #nested datastructures
people = [
{"name": "Harry", "house": "Gryffindor"},
{"name": "Cho", "house": "Ravenclaw"},
{"name": "Draco", "house": "Slytherin"},
{"name": "fungus", "house": "Ravenclaw"}
]
#lambda says what sort() have to sort
people.sort(key = lambda person: person["name"])
print(people) | false |
dd45f1114aacf040a6726aab846c68f3da42a1c9 | mraps98/ants | /src/ga.py | 2,207 | 4.125 | 4 | class SimpleGA:
"""
This is an implementation of the basic genetic algorithm.
It requires a few functions need to be overriden to handle the
specifics of the problem.
"""
def __init__(self, p):
self.p = p
def nextGen(self):
"""
Create the next generation. Returns the population.
"""
p = []
while len(p) < len(self.p):
#select mates and produce offspring
p1, p2 = self.select()
offspring = self.mate(p1, p2)
#put the offspring in the next generation (with mutation)
for child in offspring:
child=self.mutate(child)
p.append(child)
# the world belongs to the new generation
return p
def evolve(self, generations=10000):
"""
Let them evolve for generations number of steps.
"""
for gen in range(generations):
# run the tournament
self.tournament()
# generate the next generation
self.p = self.nextGen()
def getPopulation(self):
"""
Return the current population
"""
return self.p
def tournament(self):
"""
Run the competition, set scores somewhere.
The default function does nothing, this shoudl be overridden.
"""
pass
def select(self):
"""
Select two members of the population for mating and return
them.
The default function just returns the first two elements.
This should be overridden.
"""
return self.p[0], self.p[1]
def mate(self, p1, p2):
"""
Mate a pair of individuals, and then return how
they will be represented in the next generation.
By default, this just returns the parents.
This should be overridden
"""
return (p1, p2)
def mutate(self, child):
"""
Perform optional mutation on the child.
The default function just returns the child.
This should be overriden if you desire mutation.
"""
return child
| true |
f476087e70dabc6ff4d7f5311f6d71175a323225 | S1rFluffy/fogstream_courses | /Practice_1/task4.py | 1,116 | 4.1875 | 4 | """
Процентная ставка по вкладу составляет P процентов годовых,
которые прибавляются к сумме вклада. Вклад составляет X рублей Y копеек.
Определите размер вклада через год. Программа получает на вход целые числа P, X, Y и
должна вывести два числа: величину вклада через год в рублях и копейках.
Дробная часть копеек отбрасывается.
"""
# coding: utf-8
# whee1.mx@gmail.com // S1rFluffy
number_P = int(input("Введите % ставку (целое число)"))
number_X = int(input("введите данные по вкладу, рубли "))
number_Y = int(input("и копейки "))
answer_kopeika = int(((number_X * 100 + number_Y) * (1 + number_P / 100))//1)
answer_rubles = answer_kopeika // 100
print("Величина вклада в рублях = ",answer_rubles)
print("Величина вклада в копейках = ",answer_kopeika) | false |
7f720a89090fdeddbd9e406d394b61850ba815c7 | Aliot26/HomeWork | /comprehension.py | 1,500 | 4.28125 | 4 | # This program randomly makes a number from 1 to 20 for user guessing.
import random # add random module
guesses_taken = 0 # assign 0 to guesses_taken variable
print('Hello! What is your name?') # print the message
myName = input() # assign value printed by user to myName variable
number = random.randint(1, 20) # assign a random integer to number variable
# print the message
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guesses_taken < 6: # start the while loop
print('Take a guess.') # print the message
guess = input() # assign value printed by user to guess variable
guess = int(guess) # cast string to integer
guesses_taken += 1 # update counter
if guess < number: # check if guess less than number
print('Your guess is too low.') # print the message
if guess > number: # check if guess more than number
print('Your guess is too high.') # print the message
if guess == number: # check if guess equals number
break # interrupt the while loop
if guess == number: # check if guess equals number
guesses_taken = str(guesses_taken) # cast string to integer
print('Good job, ' + myName + '! You guessed my number in ' +
guesses_taken + ' guesses!') # print the message
if guess != number: # check if guess does not equal number
number = str(number) # cast integer to string
print('Nope. The number I was thinking of was ' + number) # print the message
| true |
32826a67b046670ad85a74a4ddbfdb3ec58cedfd | Aliot26/HomeWork | /reverse.py | 324 | 4.15625 | 4 | inputS = ("The greatest victory is that which requires no battle")
def reverseString(inputString):
inputString = inputString.split()
inputString = inputString[-1::-1]
output = " ".join(inputString)
return output
print("The greatest victory is that which requires no battle")
print(reverseString(inputS))
| true |
023885a61005008c9b646bf0997de90f180d8c59 | aman09031999/PythonTutorial_Basic | /list.py | 1,634 | 4.125 | 4 | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # List in Python
>>>
>>> nums = [12,45,67,56,67] # list of number
>>> nums
[12, 45, 67, 56, 67]
>>> name = ['Hello','Aman','Pradhan'] # list of String
>>> name
['Hello', 'Aman', 'Pradhan']
>>> name[2]
'Pradhan'
>>> name[1]
'Aman'
>>> nums[2:]
[67, 56, 67]
>>> nums[-2]
56
>>> nums
[12, 45, 67, 56, 67]
>>> nums[3]
56
>>> nums[-2]
56
>>> value = ['Aman',23,3.6,'hello'] # list of multiple data types
>>> value[1]
23
>>> value[3]
'hello'
>>> value[2]
3.6
>>> value[4]
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
value[4]
IndexError: list index out of range
>>> value[0]
'Aman'
>>> mil = [name,nums,value]
>>> mil
[['Hello', 'Aman', 'Pradhan'], [12, 45, 67, 56, 67], ['Aman', 23, 3.6, 'hello']]
>>> nums.append(89)
>>> nums
[12, 45, 67, 56, 67, 89]
>>> nums.insert(2,90)
>>> nums
[12, 45, 90, 67, 56, 67, 89]
>>> len(nums)
7
>>> sum(nums)
426
>>> sum(name)
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
sum(name)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> min(name)
'Aman'
>>> name
['Hello', 'Aman', 'Pradhan']
>>> name.append('abcs')
>>> min(name)
'Aman'
>>> name
['Hello', 'Aman', 'Pradhan', 'abcs']
>>> sort(name)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
sort(name)
NameError: name 'sort' is not defined
>>> name.sort()
>>> name
['Aman', 'Hello', 'Pradhan', 'abcs']
>>> nums.sort()
>>> nums
[12, 45, 56, 67, 67, 89, 90]
>>>
| false |
e55be7027d048b145d3981e2d81f7462fea954fe | ErnestoPena/Intro-Python-I | /src/13_file_io.py | 919 | 4.25 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
files = open('C:\\Python\\Intro-Python-I\\src\\foo.txt')
print(files.read())
files.close()
# Open up a file called "bar.txt" (which doesn't exist yet) for
# writing. Write three lines of arbitrary content to that file,
# then close the file. Open up "bar.txt" and inspect it to make
# sure that it contains what you expect it to contain
fileTwo = open('C:\\Python\\Intro-Python-I\\src\\bar.txt', 'w+')
fileTwo.write('I love Python.\nBut I cant forget JS\nBoth are very good programming languages')
fileTwo.close()
fileTwo = open('C:\\Python\\Intro-Python-I\\src\\bar.txt')
print(fileTwo.read())
fileTwo.close()
| true |
4d5770e312d763bbc1d43ff27f521e64cbc3e2ff | Sunnyshio/2nd-year-OOP | /1st Semester Summative Assessment.py | 1,120 | 4.375 | 4 | # program that accepts the dimensions of a 3D shape (right-cyliner and sphere) and prints its volume
class Shape:
# Constructor method to process the given object: dimension
def __init__(self, *argument):
self.dimension = argument
# printVolume method: code to process/calculate the volume of the given dimension/s
def printVolume(self):
if len(self.dimension) == 2:
volume = (3.14159 * ((self.dimension[0] / 2) ** 2) * self.dimension[1])
if volume == 0 or volume <= 0: # Prints the output if the result is equal to zero or a negative integer
print("Shape Volume Error!")
else: # Prints the output if the result is a positive integer
print("{:.1f}".format(volume))
elif len(self.dimension) == 1: # Processes the input if there is only one argument
volume = (4 / 3) * 3.14159 * ((self.dimension[0] / 2) ** 3)
print("{:.1f}".format(volume))
# Processes entered inputs that are more than 2 arguments
else:
print("Shape Volume Error!")
| true |
bd07f81e6c4b66c1422065c352832a6cd5561432 | yasirabd/udacity-ipnd | /stage_3/lesson_3.2_using_functions/secret_message/rename_files.py | 1,250 | 4.25 | 4 | # Lesson 3.2: Use Functions
# Mini-Project: Secret Message
# Your friend has hidden your keys! To find out where they are,
# you have to remove all numbers from the files in a folder
# called prank. But this will be so tedious to do!
# Get Python to do it for you!
# Use this space to describe your approach to the problem.
# step 1 - select folder
# step 2 - for files in folder
# step 2.1 - remove numbers
#
# Your code here.
import os
def rename_files():
# 1. get file names from the folder
file_list = os.listdir(r"E:\Udacity\Intro to Programming\udacity-ipnd\stage_3\lesson_3.2_using_functions\secret_message\prank")
print file_list
# check the current working directory
saved_path = os.getcwd()
# print "Current Working Directory is " + saved_path
# changes directory
os.chdir(r"E:\Udacity\Intro to Programming\udacity-ipnd\stage_3\lesson_3.2_using_functions\secret_message\prank")
# 2. for each file, rename filenames
for file_name in file_list:
print "Old name - " + file_name
print "New name - " + file_name.translate(None, "0123456789")
os.rename(file_name, file_name.translate(None, "0123456789"))
# changes back the path
os.chdir(saved_path)
rename_files()
| true |
c7348a4c84b5ef2de8d07b71c56816b052aa0d82 | nlewis97/cmpt120Lewis | /rover.py | 359 | 4.125 | 4 | # Introduction to Programming
# Author: Nicholas Lewis
#Date: 1/29/18
# Curiosityroverexercise.py
# A program that calculates how long it take a photo from Curiotsity to reach NASA.
def timecalculator():
speed = 186000
distance = 34000000
time = distance/speed
print("It will take", time, "seconds for the picture to reach NASA")
timecalculator()
| true |
2e7421cf23a1dbc4136687af7be0a67cd149d4c7 | nlewis97/cmpt120Lewis | /madlib.py | 423 | 4.15625 | 4 | # Introduction to Programming
# Author: Nicholas Lewis
# Date: 2/2/18
# madlib.py
# A program that functions as a madlib
def madlib():
name = input("enter a name:")
verb = input("enter a verb:")
adjective = input("enter an adjective:")
street = input("enter a street name:")
print(name, "started to", verb, "when the", adjective, "police officer pulled him over on", street)
madlib()
| true |
12365a6f64568bc9454cbd525e5a2b8d830d0bb4 | Churqule/python_learning | /FAQ/slice.py | 1,155 | 4.125 | 4 | #!/usr/bin/env python3
# _*_ coding:utf-8 _*_
import os
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
#取前3个元素,用一行代码就可以完成切片:
print(L[0:3])
#L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。
#如果第一个索引是0,还可以省略:
print(L[:3])
'''
类似的,既然Python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片,试试:
'''
print(L[-2:])
print(L[-2:-1])
#切片操作十分有用。我们先创建一个0-99的数列:
L = list(range(100))
print(L)
#前10个数,每两个取一个:
print(L[:10:2])
#所有数,每5个取一个:
print(L[::5])
#甚至什么都不写,只写[:]就可以原样复制一个list:
print(L[:])
'''
tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:
'''
print((0, 1, 2, 3, 4, 5)[:3])
'''
字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:
'''
print('ABCDEFG'[:3]) | false |
942fbd118ccf3d93c6b397bfb9d06c0c6ed3a971 | Churqule/python_learning | /FAQ/if_else.py | 419 | 4.28125 | 4 | #!/usr/bin/env python3
# _*_ coding:utf-8 _*_
import os
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
'''
input()返回的数据类型是str,str不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来完成这件事情:
'''
s = input('birth: ')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后') | false |
2d690cd3ff70d267947be2ee1b8f7875fa1f48a0 | medhini/ECE544-PatternRecognition | /mp1/models/support_vector_machine.py | 1,600 | 4.125 | 4 | """
Implements support vector machine.
"""
from __future__ import print_function
from __future__ import absolute_import
import numpy as np
from models.linear_model import LinearModel
class SupportVectorMachine(LinearModel):
def backward(self, f, y):
"""Performs the backward operation.
By backward operation, it means to compute the gradient of the loss
w.r.t w.
Hint: You may need to use self.x, and you made need to change the
forward operation.
Args:
f(numpy.ndarray): Output of forward operation, dimension (N,).
y(numpy.ndarray): Ground truth label, dimension (N,).
Returns:
(numpy.ndarray): Gradient of L w.r.t to self.w,
dimension (ndims+1,).
"""
z = np.zeros(self.ndims+1)
o = np.ones(self.ndims+1)
gradient = np.mean(max(z, o-y*f), axis=1)
return gradient
def loss(self, f, y):
"""The average loss across batch examples.
Args:
f(numpy.ndarray): Output of forward operation, dimension (N,).
y(numpy.ndarray): Ground truth label, dimension (N,).
Returns:
(float): average hinge loss.
"""
o = np.ones(self.ndims+1)
loss = np.mean(max(o, -y*self.x),axis=1)
return None
def predict(self, f):
"""
Args:
f(numpy.ndarray): Output of forward operation, dimension (N,).
Returns:
(numpy.ndarray): Hard predictions from the score, f,
dimension (N,).
"""
return None
| true |
98c76a84e5362b78d5e36590990ed9de3f700add | VitaliiStorozh/Python_marathon_git | /8_sprint/Tasks/s8_1.py | 2,585 | 4.21875 | 4 | # Write the program that calculate total price with discount by the products.
#
# Use class Product(name, price, count) and class Cart. In class Cart you can add the products.
#
# Discount depends on count product:
#
# count discount
# 2 0%
# 5 5%
# 7 10%
# 10 20%
# 20 30%
# more than 20 50%
# Write unittest with class CartTest and test all methods with logic
import unittest
from parameterized import parameterized
class Product:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
def discount_calc(self):
if self.count <= 2:
self.price_with_discount = self.price
elif self.count <= 5:
self.price_with_discount = round(self.price * 0.95, 2)
elif self.count <= 7:
self.price_with_discount = round(self.price * 0.9, 2)
elif self.count <= 10:
self.price_with_discount = round(self.price * 0.8, 2)
elif self.count <= 20:
self.price_with_discount = round(self.price * 0.7, 2)
elif self.count > 20:
self.price_with_discount = round(self.price * 0.5, 2)
return self.price_with_discount
class Cart:
def __init__(self):
self.product_list = []
def add_product(self, product):
self.product_list.append(product)
def totalprice(self):
self.totalprice = 0
for product in self.product_list:
self.totalprice += product.discount_calc()*product.count
return self.totalprice
class CartTest(unittest.TestCase):
def setUp(self):
self.product1 = Product("eggs", 12, 0)
self.product2 = Product("bread", 24, 5)
def test_discount(self):
self.assertEqual(self.product1.discount_calc(), 12)
self.assertEqual(self.product2.discount_calc(), 22.8)
def tearDown(self):
self.product1 = None
self.product2 = None
# product1 = Product("eggs", 12, 0)
# product2 = Product("bread", 24, 5)
# product3 = Product("ice-cream", 45, 7)
# product4 = Product("каун", 45, 10)
# product5 = Product("батерейки", 45, 20)
# product6 = Product("гайки", 45, 30)
#
# zakaz = Cart()
# zakaz.add_product(product1)
# zakaz.add_product(product2)
# zakaz.add_product(product3)
# zakaz.add_product(product4)
# zakaz.add_product(product5)
# zakaz.add_product(product6)
# print(zakaz.totalprice())
productTestSuite = unittest.TestSuite()
productTestSuite.addTest(unittest.makeSuite(CartTest))
runner = unittest.TextTestRunner(verbosity=2)
runner.run(productTestSuite) | true |
626884ee70540431a1f36f56e99afd2487171c25 | VitaliiStorozh/Python_marathon_git | /3_sprint/Tasks/s3.2.py | 326 | 4.125 | 4 | # Create function create with one string argument.
# This function should return anonymous function that checks
# if the argument of function is equals to the argument of outer function.
def create(str):
return lambda str1: str1 == str
tom = create("pass_for_Tom")
print(tom("pass_for_Tom"))
print(tom("pass_for_tom")) | true |
cdfa670aeb908033858308055aa4802dda5fc4f3 | Okreicberga/programming | /week04-flow/guess2.py | 418 | 4.25 | 4 | # Program that promts the user to guess a number
# the program tell the user if there to guess to high or too low, each time they guess.
numberToGuess = 30
guess = int(input("Please guess the number:"))
while guess != numberToGuess:
if guess < numberToGuess:
print("too low")
else:
print("too high")
guess = int(input("Please guess the number:"))
print ("Well done! Yes the number was", numberToGuess) | true |
21a98009d75c3648b6fdac4f6ac64bc9a574b917 | Okreicberga/programming | /labs/Topic09-errors/useFib.py | 218 | 4.15625 | 4 | # Author Olga Kreicberga
# This program prompts the user for a number and
# Prints out the fibonacci sequence of that many numbers
import myFunctions
nTimes = int(input('how many:'))
print (myFunctions.fibonacci(nTimes))
| true |
8937f36dbe99019123b72af1cc0e60f0e9b1f231 | AgileinOrange/lpthw | /ex32.py | 274 | 4.28125 | 4 | # Exercise 32 Loops and Lists
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print(f'This is count {number}') | true |
9ddeb98336bc7a229d71c532ff6ca1bd544c4c67 | Mr-koding/python_note | /working_with_string.py | 792 | 4.1875 | 4 | # String formatting/manipulation
# String is an array of characters/object
# A string an immutable sequence of characters
myString = "this is a string"
"this 23 is also string"
"344"
""
" "
"True"
'I can have single quote'
"@#$%#$%&^"
"[34,34,56]"
# Strings have indices
print(myString[2]) # i
# Slicing can be performed on a string
print(myString[2:8])
# String interpolation
name = "George"
print(f"My name is {name}")
# String formatting
firstname = "Joel"
age = 30
gender = "Male"
print("{1} is a {0} of {2} years old".format(firstname,gender,age))
# Named indexes
mes = "I have a very nice {house}".format(house = "Palace house")
print(mes)
#String concatenation
val1 = "i"
val2 = "phone"
val3 = "x"
full = val1 + val2 + " " + val3
print(full)
print(f"{val1}{val2} {val3}")
| true |
df50a7e0b27fc1a865fa980625ce50bafe122119 | fatimabenitez/bootcamp | /clases/dino.py | 1,248 | 4.25 | 4 | """
#funciona pero esta comentado
class Dino:
def __init__ (self):
print("----------------Naci----------------")
pepe=Dino()
"""
"""
class Dino:
ojo = 2
def __init__(self, un_nombre, un_color, canti_patas=4, un_genero=None):
self.nombre = un_nombre
self.color = un_color
self.patas = canti_patas
self.genero = un_genero
print ("--------Naci-------")
pepe= Dino ("Pepito", "Verde",4,"Macho alfa pecho peludo")
print(pepe.nombre)
"""
class Dino:
ojo = 2
def __init__(self, un_nombre, un_color, canti_patas=4, un_genero=None):
self.nombre = un_nombre
self.color = un_color
self.patas = canti_patas
self.genero = un_genero
print ("--------Naci-------")
def saludar (self):
print ("Hola me llamo", self.nombre, "tengo", self.patas,"patas y soy ",self.genero)
self.color
def cortar_pata (self, cantidad_de_patas_a_cortar=1):
self.patas = self.patas - cantidad_de_patas_a_cortar
def decir_genero(self):
print("Hola soy", self.nombre, "y me identifico como", self.genero)
pepe= Dino ("Pepito", "Verde",4,"Macho alfa pecho peludo")
print(pepe.nombre)
pepe.saludar()
pepe.decir_genero()
| false |
a05f262054a8eefcddfefdbd7e8883085aee5b9d | SURYATEJAVADDY/Assignment | /assignment/assignment1_4.py | 786 | 4.28125 | 4 | # Write a class that represents a Planet. The constructor class should accept the arguments radius (in meters) and rotation_period (in seconds).
# You should implement three methods:
# (i)surface_area
# (ii)rotation_frequency
import math
class Planet:
def __init__(self):
self.radius = int(input("Enter radius(in meters): "))
self.rotation_period = int(input("Enter rotation period (in seconds): "))
def surface_area(self):
surface_area = (4*3.14) * ((self.radius)**2)
print(surface_area,"Square Meters")
def rotation_frequency(self):
rot_frequency = (2*3.14)/(self.rotation_period)
print(rot_frequency ,"radians per second")
earth = Planet()
earth.surface_area()
earth.rotation_frequency()
| true |
370325ad5443eb93ee3179152c7b8380dbdbb6c4 | aribis369/InformationSystemsLab | /numpyhw.py | 2,133 | 4.1875 | 4 | # Program to get analysing student marks for different subjects.
import numpy as np
# Generating array for 10 students and 6 subjects
A = np.random.randint(low=0, high=101, size=(10,6))
try:
choice = int(input("Enter your choice\n"
"1) Students with highest and lowest total marks\n"
"2) Subjects with highest and lowest average score\n"
"3) Student with highest score across all subjects\n"))
except:
print("Please input an integer")
print("The matrix with random numbers is\n", A)
sumList = np.zeros(6)
topperList = np.zeros(10)
studentNum = 0
subjectNum = 0
sumList = A.sum(axis=0)
topperList = A.sum(axis=1)
def menu(mat, choice) :
if choice == 3 :
if int(np.argmin(mat)%6) is not 0:
print('Student No.{} scored the lowest in Subject No.{} ie. {}'.format(int(np.argmin(mat)/6),np.argmin(mat)%6+1,A[int(np.argmin(mat)/6),np.argmin(mat)%6]))
if int(np.argmin(mat)%6) == 0:
print('Student No.{} scored the lowest in Subject No.{} ie. {}'.format(int(np.argmin(mat)/6)+1,np.argmin(mat)%6+1,A[int(np.argmin(mat)/6),np.argmin(mat)%6]))
if int(np.argmax(mat)%6) is not 0:
print('Student No.{} scored the highest in Subject No.{} ie. {}'.format(int(np.argmax(mat)/6)+1,np.argmax(mat)%6+1,A[int(np.argmax(mat)/6),np.argmax(mat)%6]))
if int(np.argmax(mat)%6) == 0:
print('Student No.{} scored the highest in Subject No.{}'.format(int(np.argmax(mat)/6),np.argmax(mat)%6+1),A[int(np.argmax(mat)/6),np.argmax(mat)%6])
if choice == 2 :
print('Subject with lowest average is {} with an average of {}\n'
'Subject with highest average is {} with an average of {}'.format(np.argmin(sumList)+1,min(sumList)/10,np.argmax(sumList)+1,max(sumList)/10))
if choice == 1 :
print('Student No.{} has secured highest marks ie. {} out of 600'.format(np.argmax(topperList)+1,max(topperList)))
print('Student No.{} has secured lowest marks ie. {} out of 600'.format(np.argmin(topperList)+1,min(topperList)))
menu(A,choice)
| true |
fe6f064841aa0934d61dd3f11677c84fa18f4f36 | yabur/LeetCode_Practice | /Trees/Tree_Practice/Practice_Set1/IsBST.py | 1,513 | 4.15625 | 4 | # Is It A BST
# Given a binary tree, check if it is a binary search tree (BST). A valid BST does not have to be complete or balanced.
# Consider the below definition of a BST:
# 1- All nodes values of left subtree are less than or equal to parent node value
# 2- All nodes values of right subtree are greater than or equal to parent node value
# 3- Both left subtree and right subtree must be a BST
# 4- By definition, NULL tree is a BST
# 5- By definition, trees having a single node or leaf nodes are BST.
class TreeNode():
def __init__(self, val=None, left_ptr=None, right_ptr=None):
self.val = val
self.left_ptr = left_ptr
self.right_ptr = right_ptr
# complete the function below
def isBST(root, l = None, r = None):
# if tree is empty return t
if root is None:
return True
if l != None:
if l.val >= root.val:
return False
if r != None:
if r.val < root.val:
return False
return isBST(root.left_ptr, l, root) and isBST(root.right_ptr,root,r)
if __name__ == '__main__':
#root = [3,9,20,None,None,15,7]
root = TreeNode(3)
root.left_ptr = TreeNode(2)
root.right_ptr = TreeNode(5)
root.right_ptr.left_ptr = TreeNode(1)
root.right_ptr.right_ptr = TreeNode(4)
#root.right_ptr.left_ptr = TreeNode(25)
#root.right_ptr.right_ptr = TreeNode(35)
print(isBST(root))
| true |
b2d231a9a260802889ed8929c62cf81429df8636 | yabur/LeetCode_Practice | /Graphs/GraphFoundation/AdjacencyList.py | 1,337 | 4.25 | 4 | # Adjascency List representation in Python
class AdjNode:
def __init__(self, value):
self.vertex = value
self.next = None
# A class to represent a graph. A graph
# is the list of the adjacency lists.
# Size of the array will be the no. of the
# vertices "V"
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [None] * self.V
# Function to add an edge in an undirected graph
def add_edge(self, src, dest):
# Adding the node to the source node
node = AdjNode(dest)
node.next = self.graph[src]
self.graph[src] = node
# Adding the source node to the destination as
# it is the undirected graph
node = AdjNode(src)
node.next = self.graph[dest]
self.graph[dest] = node
# Print the graph
def print_agraph(self):
for i in range(self.V):
print("Vertex " + str(i) + ":", end="")
temp = self.graph[i]
while temp:
print(" -> {}".format(temp.vertex), end="")
temp = temp.next
print(" \n")
if __name__ == "__main__":
V = 5
# Create graph and edges
graph = Graph(V)
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(0, 3)
graph.add_edge(1, 2)
graph.print_agraph() | true |
36e87e1e2c56a436f958846964b43f7523603e6a | Rajpratik71/pythonTrainAppin | /Nestedif.py | 262 | 4.125 | 4 | a=int(input("enter the number for a: "))
b=int(input("enter the number for "))
c=int(input("enter a number"))
if a>b:
if a>c:
print("the greatest number is 'a'")
elif:
print("the greatest number is 'b'")
else:
print("the greattest no is 'c'") | false |
61e0ee03f7b42d02bfef3c307e1442a7fa89ad3b | wldrocha/Python | /3.py | 348 | 4.3125 | 4 | #-*- coding: utf-8 -*-
# #ejercicio #3
# Mostrar el resultado de elevar el numero 2 al cuadrado y al cubo.
numero = raw_input('Introduce el número a sacarle el cadrado y el cubo de si: ')
cuadrado = numero**2
cubo = numero**3
print "el cuadrado de "+str(numero)+" es igual a "+str(cuadrado)
print "el cubo de "+str(numero)+" es igual a "+str(cubo) | false |
97fa7bf41d2c14e3bcfc26eadbdf964f4ada08a1 | jonathasfsilva/lab-jfs-20181 | /algOrdenacao.py | 2,971 | 4.25 | 4 | u"""Algoritmos de Ordenação.
- BublleSort
- InsertSort
- MergeSort
- QuickSort
- SelectSort
"""
# dfdf
def mergeSort(lista):
"""MergeSort.
Recebe uma lista e retorna a lista ordenada por mergeSort.
"""
if len(lista) > 1:
meio = len(lista)//2
ladoDireito = lista[:meio]
ladoEsquerdo = lista[meio:]
mergeSort(ladoDireito)
mergeSort(ladoEsquerdo)
i, j, k = 0, 0, 0
while i < len(ladoEsquerdo) and j < len(ladoDireito):
if ladoEsquerdo[i] < ladoDireito[j]:
lista[k] = ladoEsquerdo[i]
i += 1
else:
lista[k] = ladoDireito[j]
j += 1
k += 1
while i < len(ladoEsquerdo):
lista[k] = ladoEsquerdo[i]
i += 1
k += 1
while j < len(ladoDireito):
lista[k] = ladoDireito[j]
j += 1
k += 1
return lista
def bublleSort(lista):
"""BublleSort.
Recebe uma lista e retorna ela ordenada por bublleSort.
"""
listaConfere = []
for j in range(len(lista)):
listaConfere = lista[::]
for i in range(len(lista)-1):
if lista[i] > lista[i+1]:
lista[i], lista[i+1] = lista[i+1], lista[i]
if listaConfere == lista:
break
return lista
def insertSort(lista):
"""InsertSort.
Recebe uma lista e retona ela ordenada por insertSort.
"""
for i in range(1, len(lista)):
chave = lista[i]
j = i
while j > 0 and lista[j-1] > chave:
lista[j] = lista[j-1]
j -= 1
lista[j] = chave
return lista
def selectSort(lista):
"""SelectSort.
Recebe uma lista e retona ela ordenada por SelectSort.
"""
n = len(lista)
for i in range(len(lista)-1):
mini = i
for j in range(i+1, n):
if lista[j] < lista[mini]:
mini = j
lista[i], lista[mini] = lista[mini], lista[i]
return lista
def quickSort(lista):
"""QuickSort.
Recebe uma lista e retorna ela orenada por QuickSort.
"""
if len(lista) <= 1:
return lista
less, equal, greater = [], [], []
pivot = lista[0]
for x in lista:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
else:
greater.append(x)
return quickSort(less) + equal + quickSort(greater)
def quickSortRev(lista):
"""QuickSort.
Recebe uma lista e retorna ela ordenada reversamente por QuickSort.
"""
if len(lista) <= 1:
return lista
less, equal, greater = [], [], []
pivot = lista[0]
for x in lista:
if x > pivot:
greater.append(x)
elif x == pivot:
equal.append(x)
else:
less.append(x)
return quickSortRev(greater) + equal + quickSortRev(less)
l = [1,2,3,4,5,6]
print(quickSortRev(l))
| false |
d29730d76c28c24a0c2be8ec32f7e9a1489b1c5a | lvonbank/IT210-Python | /Ch.03/P3_2.py | 489 | 4.125 | 4 | # Levi VonBank
## Reads a floating point number and prints “zero” if the number is zero.
# Otherwise “positive” or “negative”. “small” if it is less than 1,
# or “large” if it exceeds 1,000,000.
userInput = float(input("Enter a floating-point number: "))
if userInput == 0:
print("It's zero")
elif userInput > 0:
print("It's positive")
else:
print("It's negative")
if userInput < 1:
print("and small")
elif userInput > 1000000:
print("and large") | true |
aa4fb45cf22cf8d68e6d311cf1efc7552d42bd41 | lvonbank/IT210-Python | /Ch.04/P4_5.py | 913 | 4.125 | 4 | # Levi VonBank
# Initializes variables
total = 0.0
count = 0
# Priming read
inputStr = input("Enter a value or Q to quit: ")
# Initializes the largest and smallest variables
largest = float(inputStr)
smallest = float(inputStr)
# Enters a loop to determine the largest, smallest, and average
while inputStr.upper() != "Q" :
value = float(inputStr)
total = total + value
count = count + 1
if value > largest:
largest = value
if value < smallest:
smallest = value
inputStr = input("Enter a value or Q to quit: ")
# Makes sure the count is not zero
if count > 0 :
average = total / count
else :
average = 0.0
# Calculates the range
dataRange = largest - smallest
print()
print("The average of the values is:", average)
print("The smallest of the values is:", smallest)
print("The largest of the values is:", largest)
print("The range of the values is:", dataRange) | true |
80b94f65df7acf89744b8a1fbdbc74177e09e7ad | lvonbank/IT210-Python | /Lab07/Lab07.py | 1,144 | 4.4375 | 4 | # Levi VonBank
# Group Members: Scott Fleming & Peter Fischbach
def main():
# Obtains strings from the user
set1 = set(input("Enter a string to be used as set1: "))
set2 = set(input("Enter a string to be used as set2: "))
set3 = set(input("Enter a string to be used as set3: "))
# Determines elements that are in set1 or set2, but not both.
a = set1.union(set2) - set1.intersection(set2)
# Determines elements only in one of the three sets
diff1 = set1.difference(set2.union(set3))
diff2 = set2.difference(set1.union(set3))
diff3 = set3.difference(set1.union(set2))
b = set.union(diff1, diff2, diff3)
# Determines elements that are in exactly two of the sets
intAll = set.intersection(set1, set2, set3)
int1 = set1.intersection(set2)
int2 = set2.intersection(set3)
int3 = set3.intersection(set1)
c = set.union(int1, int2, int3) - intAll
# Prints results
print('Part A:', makeStr(a))
print('Part B:', makeStr(b))
print('Part C:', makeStr(c))
def makeStr(collection):
string = ""
for char in sorted(collection):
string += char
return string
main() | true |
295263667e05765c97cc89de5d6b54ed02109d48 | lvonbank/IT210-Python | /Ch.03/P3_21.py | 357 | 4.21875 | 4 | # Levi VonBank
## Reads two floatingpoint numbers and tests whether
# they are the same up to two decimal places.
number1 = float(input("Enter a floating-point number: "))
number2 = float(input("Enter a floating-point number: "))
if abs(number1 - number2) <= 0.01:
print("They're the same up to two decimal places")
else:
print("They're different.") | true |
ce7a6159d432f1ae5c820279cf3c77ed8d4a85fd | AsdaRD/Shakh_Intro_Python_09_06_21 | /lessons/lesson_6.2.py | 1,446 | 4.125 | 4 | # множества set - не сохраняет порядок, все элементы уникальные
# my_list = [3, 10, 10, 2, 2, "2", 3, 3, 3, 3, 3, 3]
# my_list_unique = list(set(my_list)) - убирает дубли
# my_set = set(my_list)
# print(my_set)
# my_list_unique = list(my_set)
#
# print(my_list_unique)
# new_set = {1, 2, 3, 4, 54, 54}
# print(new_set)
# my_str = 'bla BLA car'
# my_str = my_str.lower()
# res_len = len(set(my_str))
# print(res_len)
# my_str = 'qqqqqqqqqqqqqwwwwwwwwwwweeeeeeeeeeeeeeeeeeeertyy'
# for symbol in set(my_str):
# print(symbol, my_str.count(symbol))
# my_str_1 = 'qwerty'
# my_str_2 = 'qweasd'
# my_set_1 = set(my_str_1)
# my_set_2 = set(my_str_2)
#
# intersection = my_set_1.intersection(my_set_2)
# print(intersection)
#
# union = my_set_1.union(my_set_2)
# print(union)
#
# difference = my_set_1.difference(my_set_2)
# print(difference)
# словарь - dict не гарантирует сохранение порядка, все ключи уникальные
# ключи - любые неизменяемые объекты
# значения - любые объекты
# triangle = [[1, 1], [2, 3], [4, -2]]
# print(triangle[1][1])
key = (1, 2, 'qwe')
test_dict = {11: '12',
'11': 12,
key: 'test'}
print(test_dict[key])
triangle = {'A': {'x': 1, 'y': 1},
'B': {'x': 2, 'y': 3},
'C': {'x': 4, 'y': -2}}
print(triangle)
| false |
29173826db662583656792fac1fc39f18e7f2958 | NikDestrave/Python_Algos_Homework | /Lesson_3.9.py | 961 | 4.125 | 4 | """
Задание_9.Найти максимальный элемент среди минимальных элементов столбцов матрицы.
Пример:
Задайте количество строк в матрице: 3
Задайте количество столбцов в матрице: 4
36 20 42 38
46 27 7 33
13 12 47 15
[13, 12, 7, 15] минимальные значения по столбцам
Максимальное среди них = 15
"""
from random import random
height = 4
width = 3
arr = []
for i in range(width):
arr_2 = []
for j in range(height):
num = int(random() * 40)
arr_2.append(num)
print('%4d' % num, end='')
arr.append(arr_2)
print()
max = -1
for j in range(height):
min = 40
for i in range(width):
if arr[i][j] < min:
min = arr[i][j]
if min > max:
max = min
print(f'Максимальное среди них = {max}') | false |
16afd1d6f6291e39cd87abb83115dd6faee3b91a | mef14/data_structures | /binary_tree.py | 1,467 | 4.34375 | 4 | # -*- coding: utf-8 -*-
class BinaryTree(object):
"""
Binary Tree implementation.
"""
def __init__(self, key):
self.key = key
self.leftChild = None
self.rightChild = None
def insertLeft(self, newNode):
t = BinaryTree(newNode)
if not self.leftChild:
self.leftChild = t
else:
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self, newNode):
t = BinaryTree(newNode)
if not self.rightChild:
self.rightChild = t
else:
t.rightChild = self.rightChild
self.rightChild = t
def getRootKey(self):
return self.key
def setRootKey(self, newkey):
self.key = newkey
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
if __name__ == "__main__":
# create a binary tree
root = BinaryTree(1)
root.insertRight(3)
root.getRightChild().insertRight(6)
root.insertLeft(2)
root.getLeftChild().insertLeft(4)
root.getLeftChild().insertRight(5)
# print the tree
print("Binary tree representation:\n")
print(" {} ".format(root.getRootKey()))
print(" / \ ")
print(" {} {} ".format(root.getLeftChild().getRootKey(), root.getRightChild().getRootKey()))
print(" / \ \ ")
print("{} {} {}".format(root.getLeftChild().getLeftChild().getRootKey(), root.getLeftChild().getRightChild().getRootKey(), root.getRightChild().getRightChild().getRootKey())) | false |
92d19754dff461772d3e1a2e4f0d5d3a815cc4f5 | FredericVets/PythonPlayground | /helloPython.py | 1,036 | 4.28125 | 4 | """
Notes from Python Programming
https://www.youtube.com/watch?v=N4mEzFDjqtA
by Derek Banas
"""
print("Hello Python")
print('Hello Python') # single or double quotes are treated the same.
'''
I'm a multiline comment.
'''
name = "Frederic"
print(name)
name = 10
print(name)
# 5 main data types : Numbers Strings Lists Tuples Dictionaries.
# 7 Arithmetic operators : + - * / % ** //
print("5 + 2 = ", 5 + 2)
print("5 - 2 = ", 5 - 2)
print("5 * 2 = ", 5 * 2)
print("5 / 2 = ", 5 / 2)
print("5 % 2 = ", 5 % 2)
print("5 ** 2 = ", 5 ** 2)
print("5 // 2 = ", 5 // 2)
# As in all programming languages order of mathematical operation matters.
print("1 + 2 - 3 * 2 = ", 1 + 2 - 3 * 2)
print("(1 + 2 - 3) * 2 = ", (1 + 2 - 3) * 2)
x = 1
y = 2
print("x:", x, "y:", y)
x, y = y, x
print("x:", x, "y:", y)
quote = "\"Always remember you are unique"
multi_line_quote = ''' just
like everyone else'''
print("%s %s %s" % ("I like the quote", quote, multi_line_quote))
print("I don't like ", end="")
print("newlines")
print("repeat" * 5)
| true |
08035695d95b28c86e07a4b858270c15b88a7ec4 | FredericVets/PythonPlayground | /conditionals.py | 292 | 4.15625 | 4 | # keywords : if, else; elif
# conditionals : == != > >= < <=
# logical operators : and or not
age = 15
if age >= 21:
print("You are old enough to drive a tractor trailer")
elif age >= 16:
print("You are old enough to drive a car")
else:
print("You are not old enough to drive")
| false |
c99a6a6246a88c7c55e13de677c4b0d9dde09c84 | eveminggong/Python-Basics | /7. Tuples.py | 924 | 4.28125 | 4 | tuple1 = (1,2,3)
tuple2 = (5,6,7)
tuple3 = ('Red', 'Blue', 'Black')
print(f'Tuple1: {tuple1}')
print(f'Tuple2: {tuple2}')
print(f'Tuple3: {tuple3}')
def add_tuple(Tuple1, Tuple2):
FinalTuple = Tuple1 + Tuple2
print(f'The tuples are added {FinalTuple}')
add_tuple(tuple1,tuple2)
def duplicate_tuple(Tuple1, Tuple2):
FinalTuple = Tuple1 * 4
print(f'The tuples are multiplied. {FinalTuple}')
LargeTuple = duplicate_tuple(tuple1, tuple2)
def count_item(Tuple1, item):
counts = Tuple1.count(item)
print(f'The count of {item} on the Tuple 1 is {counts}')
items = 1
count_item(tuple1, items)
def index_of_item(Tuple, item):
index = Tuple.index(item)
print(f'The index of {item} on the Tuple 2 is {index}')
item_to_index = 6
index_of_item(tuple2, item_to_index)
def reiterate_tuple(Tuple3):
for color in (Tuple3):
print(f'The color is {color}')
reiterate_tuple(tuple3)
| true |
ec61070b91028fe626d24645c354dea9364199be | ramanathanaspires/learn-python | /basic/ep13_iterators_comprehensions_genfunc_genexp/generator_expressions.py | 223 | 4.125 | 4 | double = (x * 2 for x in range(10))
print("Double:", next(double))
print("Double:", next(double))
print("Double:", next(double))
print("Double:", next(double))
print("Double:", next(double))
for num in double:
print(num) | true |
dc2ab7aa13e66dfd39cf9f523e4a0a7320326f51 | ramanathanaspires/learn-python | /basic/ep4_string_functions/acronym_generator.py | 287 | 4.21875 | 4 | # Ask for a string
string = "Random Access Memory"
ACR = ""
# Convert the string to uppercase
string = string.upper()
# Convert the string into a list
string = string.split()
# Cycle through the list
for i in string:
# Get the 1st letter of the word
print(i[0], end="")
print() | true |
f7d3deda15f5fa65cb0dfbfce4d9cba884c3eb6c | IamP5/Python---Loops | /Question3.py | 354 | 4.28125 | 4 | """ Make a program that receive a float number "n". If the number is greater than 157, print "Goal Achieved" and break the loop.
Else, print "Insufficient" and read a new number "n". You should read at most 5 numbers """
for i in range(5):
i = float(input())
if i > 157:
print("Goal Achieved")
break
else:
print("Insufficient")
| true |
44252d3a22878ea2f3f669d944f73e2992d627cf | amirobin/prime | /home_study/missing2.py | 324 | 4.125 | 4 | def find_missing(list1,list2):
missingout = 0
if len(list1) > len(list2):
longer_list = list1
shorter_list = list2
else:
longer_list = list2
shorter_list = list1
for val in longer_list:
if val not in shorter_list:
missingout = val
print missingout
find_missing([1,6,7,8,9],[1,6,8,9]) | true |
4b3a5c066c3f2417a58c4318f9119aeaf5bd916f | mbreault/python | /algorithms/check_permutations.py | 618 | 4.1875 | 4 | ## given two strings check if one is a permutation of the other
## method 1 using built-in python list methods
def sorted_chars(s):
## sort characters in a string
return sorted(set(s))
def check_permutation(a,b):
if a == b:
return True
elif len(a) != len(b):
return False
else:
return sorted_chars(a) == sorted_chars(b)
print(check_permutation('x','y')) ## False
print(check_permutation('xx','y')) ## False
print(check_permutation('radar','radar')) ## True
print(check_permutation('abcdefgh','xyzzy')) ## False
print(check_permutation('sent','nest')) ## True
| true |
001ec9b81f35b566172d5acad526457c670df3e5 | Shaw622/Introducing_Python | /Chapter03/HW.py | 839 | 4.28125 | 4 | years_list = [1991, 1992, 1993, 1994, 1995, 1996]
print(years_list[3])
print(years_list[-1])
things = ["mozzarella", "cinderella", "salmonella"]
print(things)
print(things[1].capitalize())
print(things)
things[1] = things[1].capitalize()
print(things)
things[0] = things[0].upper()
print(things)
del things[-1]
print(things)
surprise = ["Groucho", "Chico", "Harpo"]
surprise[-1] = surprise[-1].lower()
surprise[-1] = surprise[-1][::-1]
surprise[-1].capitalize()
print(surprise[-1])
e2f = {"dog": "chien", "cat": "chat", "walrus": "morse"}
print(e2f["walrus"])
life = {
"animals": {
"cats": [
'Henri', 'Grumpy', 'Lucy'
],
"octopi": {},
"emus": {}
},
"plants": {},
"other": {}
}
print(life.keys())
print(life['animals'].keys())
print(life['animals']['cats'])
| false |
1f92c8e71474d67e720967c544bca4fa1b9ba8dd | ajayvenkat10/Competitive | /slidingwindow.py | 1,657 | 4.4375 | 4 | # Python3 program to find the smallest
# window containing
# all characters of a pattern
from collections import defaultdict
MAX_CHARS = 256
# Function to find smallest window
# containing
# all distinct characters
def findSubString(str):
n = len(str)
# Count all distinct characters.
dist_count = len(set([x for x in str]))
# Now follow the algorithm discussed in below
# post. We basically maintain a window of characters
# that contains all characters of given string.
# https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/
count, start, start_index, min_len = 0, 0, -1, 9999999999
curr_count = defaultdict(lambda: 0)
for j in range(n):
curr_count[str[j]] += 1
# If any distinct character matched,
# then increment count
if curr_count[str[j]] == 1:
count += 1
# Try to minimize the window i.e., check if
# any character is occurring more no. of times
# than its occurrence in pattern, if yes
# then remove it from starting and also remove
# the useless characters.
if count == dist_count:
while curr_count[str[start]] > 1:
if curr_count[str[start]] > 1:
curr_count[str[start]] -= 1
start += 1
# Update window size
len_window = j - start + 1
if min_len > len_window:
min_len = len_window
start_index = start
# Return substring starting from start_index
# and length min_len """
return str[start_index: start_index + min_len]
# Driver code
if __name__=='__main__':
print("Smallest window containing all distinct characters is {}"
.format(findSubString("aabcbcdbca")))
# This code is contributed by
# Subhrajit
| true |
bd2737365d163236c1640be6973584bd194e48ea | dstada/Python | /test2.py | 1,230 | 4.28125 | 4 | """
Tests whether a matrix is a magic square.
If it is, prints its magic number.
INPUT INSTRUCTIONS: Either just press
"Submit" or enter EACH ROW IN A NEW LINE.
Separate entries by comma and/or space.
Example 1:
1, 2, 3
4, 5, 6
7, 8, 9
Example 2:
7 12 1 14
2 13 8 11
16 3 10 5
9 6 15 4
"""
import numpy as np
def is_magic(a):
n = a.shape[0]
if np.unique(a).size != a.size:
print("\nIt does not have distinct entries, so it is not a magic square :(")
return
d1 = sum(a[i][i] for i in range(n))
d2 = sum(a[i][n-i-1] for i in range(n))
if d1==d2 and np.all(a.sum(axis=0)==d1) \
and np.all(a.sum(axis=1)==d1):
print("\nIt is a magic square! The magic sum is", d1)
else:
print("\nIt is not magic square :(")
try:
r1 = list(map(int,
input().replace(",", " ").split()))
d = len(r1)
ms = np.empty([d, d], dtype = int)
ms[0] = r1
for r in range(1, d):
ms[r] = list(map(int,
input().replace(",", " ").split()))
print("Your matrix is:", *ms, sep="\n")
except:
ms = np.array([[8,1,6],
[3,5,7],
[4,9,2]])
print("Invalid input. Working with the matrix", *ms, sep="\n")
is_magic(ms) | true |
94fb53db05943459330902864360926149c3d610 | dstada/Python | /Is that an IP address.py | 1,384 | 4.21875 | 4 | """Is That an IP Address?
Given a string as input, create a program to evaluate whether or not it is a valid IPv4 address.
A valid IP address should be in the form of: a.b.c.d where a, b, c and d are integer values ranging from 0 to 255 inclusive.
For example:
127.0.0.1 - valid
127.255.255.255 - valid
257.0.0.1 - invalid
255a.0.0.1 - invalid
127.0.0.0.1 - invalid
"""
import socket
ip = input("Give IP:")
def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_aton(address)
except socket.error:
return False
return address.count('.') == 3
except socket.error: # not a valid address
return False
return True
if is_valid_ipv4_address(ip) is False:
print("Not a valid IP")
else:
print("Valid IP")
# -----------------------------------------------------------------------
def check_ip(ip):
try:
parts = ip.split('.')
# Must be four parts and all parts 0-255
return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
except ValueError:
return False # Not convertible to integer
except (AttributeError, TypeError):
return False # No string
if check_ip(ip) is False:
print("Not valid")
else:
print("Valid")
| true |
0bc0a586aca6cc1a7d1a02df1b898a753b40f893 | dstada/Python | /[Challenge] Prime Strings.py | 950 | 4.1875 | 4 | """Prime Strings
A String is called prime if it can't be constructed by concatenating multiple (more than one) equal strings.
For example:
"abac" is prime, but "xyxy" is not ("xyxy" = "xy" + "xy").
Implement a program which outputs whether a given string is prime.
Examples
Input: "xyxy"
Output: "not prime"
Input: "aaaa"
Output: "not prime"
Input: "hello"
Output: "prime"
By: Dick Stada, NL
June, 2018
"""
test = "abdabda"
# test = "xyxy"
# test = "aaaa"
length = len(test)
if length % 2 != 0: # Odd, so Not prime if all letters are the same:
counter = 1
for i in range(1, length):
if test[0] == test[i]:
counter += 1
if counter == length:
print("Not prime")
else: # Even amount of letters
for j in range(0, length//2):
test_str = test[0:2]
print(test_str)
# print("sssdaf")
#
# if test[0] in test[1:4]:
# print("Komt voor")
#
# if test == "abd"*2:
# print("Yes") | true |
eb38f1c9a63f9d009a1236af993ecdfd08bc0672 | dstada/Python | /rgb to hex.py | 1,437 | 4.5 | 4 | """
RGB to HEX Converter
RGB colors are represented as triplets of numbers in the range of 0-255, representing the red, green and blue components
of the resulting color.
Each RGB color has a corresponding hexadecimal value, which is expressed as a six-digit combination of numbers
and letters and starts with the # sign.
The numbers and letters in a hex value can be in the range [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F].
The hexadecimal is basically a base 16 representation of the RGB value, which is a base 10 value.
Write a program that takes an RGB color value as input and converts it to its Hexadecimal equivalent.
For Example:
Input: (66, 134, 244)
Hex equivalent: #4286f4
Input: (119, 119, 119)
Hex equivalent: #777777 or #777
By: Dick Stada, NL
November 2018
See: https://www.w3schools.com/colors/colors_picker.asp
and see: https://pypi.org/project/colour/
"""
import colour as colour
color = [256, 256, 256]
while color[0] > 255 or color[1] > 255 or color[2] > 255:
color = list((map(int, input("Give rgb by three numbers 0-255, separated by a space:").split())))
print(color)
def rgb_to_hex(rgb):
hexa = ""
for i in rgb:
if len(str(hex(i))) < 4:
hexa = hexa + "0" + str(hex(i))[2]
else:
hexa = hexa + str(hex(i))[2:4]
hexa = "#" + hexa
return hexa
hx = rgb_to_hex(color)
print(hx)
print(colour.Color(hx)) # prints name of the colour if it exists
| true |
3344e55d98db5c3825de7bd85e21155d10bf84a6 | sridharbe81/python_sample_program | /String Formating.py | 421 | 4.15625 | 4 |
dict = {'Name':'Vivek', 'Age':'33'}
print('My Name is {} and I am {} Old.'.format(dict['Name'],dict['Age']))
print('My name is {Name} and I am {Age} years old'.format(**dict))
pi = 3.14378
print('The Value of pi is {:.02f}'.format(pi))
import datetime
my_date = datetime.datetime(2017,4,17, 7,16,15)
print('{:%B %d, %Y }'.format(my_date))
for i in range(11):
print("The Value is {:02}".format(i)) | false |
7d3386351d9205a438cf9876d0408f7f3c2e9652 | anamarquezz/BegginerPythonEasySteps | /hello/hello/for_loop_excercises.py | 1,324 | 4.1875 | 4 | print("\n ....prime numbers......... \n")
def is_prime(number):
# check if number is divisible by 2 to numner =1,2,3,4
if(number < 2):
return False
for divisor in range(2, number):
if number % divisor == 0:
return False
return True
print("is prime? 5 \n")
print(is_prime(5))
print("is prime? 6 \n")
print(is_prime(6))
print("is prime? 7 \n")
print(is_prime(7))
print("\n ....sum up tp......... \n")
def sum_upto_n(number):
sum = 0
for i in range(1, number+1):
sum = sum + i
return sum
print("Sum up to 3 \n")
print(sum_upto_n(3))
print("Sum up to 5 \n")
print(sum_upto_n(5))
print("Sum up to 10 \n")
print(sum_upto_n(10))
print("\n ....sum of devices ......... \n")
def calculate_sum_of_divisors(number):
# check if number is divisible by 2 to numner =1,2,3,4
sum = 0
if(number < 2):
return sum
for divisor in range(1, number+1):
if number % divisor == 0:
sum = sum + divisor
return sum
print(calculate_sum_of_divisors(6))
print(calculate_sum_of_divisors(15))
print("\n .... print a triangle ......... \n")
def print_a_number_triangle(number):
for j in range(1, number + 1):
for i in range(1, j+1):
print(i, end = " ")
print()
print_a_number_triangle(5)
| false |
d4df46d410ba8a5da505b799aa070dbc651fb258 | AbinayaDevarajan/google_interview_preparation | /dynamic_programming/fibonacci.py | 937 | 4.1875 | 4 |
import timeit
"""
Top down approach by using the recursion:
"""
def fibonacci(input):
if input ==0:
return 1
elif input ==1:
return 1
else:
return fibonacci(input-1) + fibonacci(input -2 )
"""
memoization usage of cache
"""
def fibonacci_memo(input, cache=None):
if input ==0:
return 1
if input ==1:
return 1
if cache is None: cache ={}
if input in cache: return cache[input]
result = fibonacci_memo(input-1,cache) + fibonacci_memo(input-2,cache)
cache[input] = result
print(cache) # this cache grows at each level and the recursive computations are avoided if it is already in cache
return result
"""
Bottom up by using the tabulation method
"""
def fibonacci_tablulation(n):
dp = [0, 1]
for i in range(2, n + 1):
dp.append(dp[i - 1] + dp[i - 2])
return dp[n]
print(fibonacci_memo(10))
print(fibonacci_tablulation(10)) | true |
1cddccfcd681221093b1a367335b5fa41c1c6271 | victoire4/Some-few-basic-codes-to-solve-the-problem | /3.The Longest word.py | 583 | 4.375 | 4 | def longest(N): # We define the function
A = N.split(' ') # A is a list. Each element of A is one word of N
L = 0 # Initialisation of the size for the comparison
for i in range(0,len(A)):
if (len(A[i]) > L):
W= A[i]
L = len(A[i]) # We compare lement by element. When lenght of A[i] is the biggest, L take this values and the result W take the word A[i]
# Then, gradualy, we find the longest word of N
return W
#For example
print (longest("today is my birthday"))
| true |
b093714348f4756585e4a329323f58b7a2c28af9 | doxmx/dojo | /katas/leapyear/py/test.py | 1,975 | 4.15625 | 4 | import unittest
# Import the function(s) to test, e.g.:
from kata import is_leap_year
# Implement tests here
class TestTemplate(unittest.TestCase):
# Define as many tests cases as needed
def test_case(self):
"""
Test Case 1
"""
data = [True]
result = data[0]
self.assertEqual(result, data[0])
def test_disivisible_by_400_is_leap(self):
"""
All years divisible by 400 ARE leap years
"""
years = [400, 800, 1200, 1600, 2000]
for year in years:
result = is_leap_year(year)
self.assertEqual(result, True)
def test_disivisible_by_100_and_not_by_400_is_not_leap(self):
"""
All years divisible by 100 but not by 400 are NOT leap years
"""
years = [300, 900, 1300, 1500, 1900]
for year in years:
result = is_leap_year(year)
self.assertEqual(result, False)
def test_divisible_by_4_and_not_by_100_is_leap(self):
"""
All years divisible by 4 but not by 100 ARE leap years
"""
years = [ 1996, 2004, 2008, 2012, 2016, 2020, 2024 ]
for year in years:
result = is_leap_year(year)
self.assertEqual(result, True)
def test_not_divisible_by_4(self):
"""
All years not divisible by 4 but
"""
years = [2017, 2018, 2019, 2001, 2011, 1995]
for year in years:
result = is_leap_year(year)
self.assertEqual(result, False)
def test_not_digits(self):
"""
Validate not using digits
"""
digits = ['1', '2', 'd', '%' ]
for digit in digits:
result = is_leap_year(digit)
self.assertEqual(result, False)
if __name__ == '__main__':
unittest.main()
# Run the test with any of these options:
# - python test.py
# - python -m unittest test
# - python -m unittest -v test
# - python -m unittest discover
| false |
6fe7e5516c8a1b0052f41b8f944151b971e840e0 | MillicentMal/alx-higher_level_programming-1 | /0x07-python-test_driven_development/0-add_integer.py | 533 | 4.15625 | 4 | #!/usr/bin/python3
"""
This is the "0-add_integer" module.
The 0-add_integer module supplies one function, add_integer().
"""
def add_integer(a, b=98):
"""My addition function
Args: a: first integer b: second integer
Returns: The return value. a + b """
if (a is None or (not isinstance(a, int) and not isinstance(a, float))):
raise TypeError("a must be an integer")
if (not isinstance(b, int) and not isinstance(b, float)):
raise TypeError("b must be an integer")
return int(a) + int(b)
| true |
8287ac8f2d458302a9de577d017bace013f74246 | Mauricio-KND/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,904 | 4.46875 | 4 | #!/usr/bin/python3
"""Module that creates an empty square."""
class Square:
__size = 0
"""Square with value."""
def __init__(self, size=0, position=(0, 0)):
"""Initialize square with size and position."""
if not isinstance(size, int):
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
else:
self.__size = size
if (not isinstance(position, tuple)):
raise TypeError("position must be a tuple of 2 positive integers")
elif (len(position) != 2):
raise TypeError("position must be a tuple of 2 positive integers")
elif(not isinstance(position[1], int)):
raise TypeError("position must be a tuple of 2 positive integers")
elif (position[0] < 0 or position[1] < 0):
raise TypeError("position must be a tuple of 2 positive integers")
else:
self.__position = position
def area(self):
"""Initialize the current square area."""
return self.__size * self.__size
@property
def size(self):
"""Retrive the square's size."""
return self.__size
@size.setter
def size(self, value):
"""Change the square's size."""
if not isinstance(value, int):
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
def my_print(self):
"""prints in stdout the square with the char #."""
"""If size is 0, print an empty line."""
if self.__size is 0:
print()
else:
for i in range(self.__position[1]):
print()
for i in range(self.__size):
for j in range(self.__position[0]):
print(" ", end="")
for j in range(self.__size):
print("#", end="")
print()
@property
def position(self):
"""Get the value of private position."""
return self.__position
@position.setter
def position(self, value):
"""Set value of private position."""
if (not isinstance(position, tuple)):
raise TypeError("position must be a tuple of 2 positive integers")
elif (len(position) != 2):
raise TypeError("position must be a tuple of 2 positive integers")
elif (not isinstance(position[0], int)):
raise TypeError("position must be a tuple of 2 positive integers")
elif(not isinstance(position[1], int)):
raise TypeError("position must be a tuple of 2 positive integers")
elif (position[0] < 0 or position[1] < 0):
raise TypeError("position must be a tuple of 2 positive integers")
else:
self.__position = position
| true |
9a99e019e0277ed5cbf5b89f497e623aa880ea03 | c212/spring2021-a310-labs | /march/lecture-march-08/BST-tests.py | 627 | 4.15625 | 4 | from BST import *
num = 6
a = BST(num)
print("Start from empty, insert ", num)
a.display()
num = 3
print("----Now insert ", num)
a.insert(BST(num))
a.display()
print("---And insert 2:")
a.insert(BST(2))
a.display()
numbers = [7, 9, 0, 8, 1, 4, 5]
print("---And insert (in order): ", numbers)
for num in numbers:
a.insert(BST(num))
a.display()
# Start from empty, insert 6
# 6
# ----Now insert 3
# 6
# /
# 3
# ---And insert 2:
# 6
# /
# 3
# /
# 2
# ---And insert (in order): [7, 9, 0, 8, 1, 4, 5]
# __6
# / \
# 3 7_
# / \ \
# _2 4 9
# / \ /
# 0 5 8
# \
# 1
| false |
70f61d6b99a071e58621ce3f570badb3d26ac767 | chenjb04/fucking-algorithm | /LeetCode/字符串/387字符串中的第一个唯一字符.py | 904 | 4.15625 | 4 | """
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
提示:你可以假定该字符串只包含小写字母。
Related Topics 哈希表 字符串
"""
"""
hash: 遍历字符串,如果字符不在hash中,加入hash,key为字符:value为索引
如果字符存在hash中,那么value可以设为长度,最后返回最小索引
"""
def firstUniqChar(s: str) -> int:
if not s:
return -1
hash_map = {}
n = len(s)
for i in range(n):
if s[i] not in hash_map:
hash_map[s[i]] = i
else:
hash_map[s[i]] = n
if min(hash_map.values()) == n:
return -1
return min(hash_map.values())
if __name__ == '__main__':
s = "leetcode"
print(firstUniqChar(s))
s = "loveleetcode"
print(firstUniqChar(s))
s = "aadadaad"
print(firstUniqChar(s)) | false |
c624af739fddb8f72a59134c74a13ecfebecbe21 | chenjb04/fucking-algorithm | /LeetCode/栈和队列/用递归函数和栈操作逆序一个栈.py | 1,653 | 4.125 | 4 | """
一个栈依次压入1、2、3、4、5,那么从栈顶到栈底分别为5、4、3、2、1。将这个栈转置后,
从栈顶到栈底为1、2、3、4、5,也就是实现栈中元素的逆序,
但是只能用递归函数来实现,不能用其他的数据结构。
"""
"""
解题思路:
需要两个递归函数,get_remove_last将栈底元素返回并移除; reverse栈的逆序
get_remove_last:
先pop出栈顶元素
然后弹出并返回少了一个元素的栈的栈底元素
最后把value压入栈顶
reverse:
调用get_remove_last获取栈底元素
然后调用reverse对少了一个元素的栈进行逆序处理
最后把value压入栈, 就实现了栈元素的逆序
"""
class ReverseStack:
def __init__(self, stack):
self.stack = stack
def get_remove_last(self):
"""栈顶元素返回并移除"""
value = self.stack.pop()
if self.stack.empty():
return value
res = self.get_remove_last()
self.stack.push(value)
return res
def reverse(self):
if self.stack.empty():
return
value = self.get_remove_last()
self.reverse()
self.stack.push(value)
if __name__ == '__main__':
class Stack:
def __init__(self):
self.stack = []
def push(self,x):
self.stack.append(x)
def pop(self):
return self.stack.pop()
def empty(self):
if len(self.stack) == 0:
return True
return False
def traverse(self):
while self.stack:
print(self.pop(), end=' ')
print()
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
# stack.traverse()
reverse_stack = ReverseStack(stack)
reverse_stack.reverse()
stack.traverse() | false |
77f20853645d1d5657a674aaead9aefd37feefb8 | chenjb04/fucking-algorithm | /LeetCode/栈和队列/232用栈实现队列.py | 2,838 | 4.3125 | 4 | # 使用栈实现队列的下列操作:
#
#
# push(x) -- 将一个元素放入队列的尾部。
# pop() -- 从队列首部移除元素。
# peek() -- 返回队列首部的元素。
# empty() -- 返回队列是否为空。
#
#
#
#
# 示例:
#
# MyQueue queue = new MyQueue();
#
# queue.push(1);
# queue.push(2);
# queue.peek(); // 返回 1
# queue.pop(); // 返回 1
# queue.empty(); // 返回 false
#
#
#
# 说明:
#
#
# 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
#
# 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
# 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
#
# Related Topics 栈 设计
# leetcode submit region begin(Prohibit modification and deletion)
# from collections import deque
#
#
# class Stack:
# def __init__(self):
# self.items = deque()
#
# def push(self, val):
# return self.items.append(val)
#
# def pop(self):
# return self.items.pop()
#
# def empty(self):
# return len(self.items) == 0
#
# def top(self):
# return self.items[-1]
"""
解题思路:
用两个栈实现队列,一个栈作为压入数据使用,一个栈作为弹出数据使用。
push操作:
直接往stack1 push数据
pop操作:
把stack1中的数据全部pop出去 push到stack2中,那么顺序就像队列一样了
注意:如果stack2中不为空,stack1中的数据是不能push到stack2中的,如果push了,会出现顺序问题
peek操作:
返回stack2中的栈顶元素
empty操作:
stack1和stack2不为空 则返回Fasle 反之 返回True
"""
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack1 = []
self.stack2 = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.stack1.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if len(self.stack2) == 0:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if len(self.stack2) == 0:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2[-1]
def empty(self):
"""
:return:
"""
return len(self.stack2) == 0 and len(self.stack1) == 0
| false |
1b9ed4be63989a054f4c3866ef9fa35c4927c1ac | livneniv/python | /week 2/assn2.py | 446 | 4.1875 | 4 | #Write a program to prompt the user for hours and rate per hour to compute gross pay
user_name=raw_input('Hi Sir, Whats your name? ')
work_hours=raw_input('and how many hours have you been working? ')
work_hours=float(work_hours) #converts type from string to float
rate=raw_input('pardon me for asking, but how much do you earn per hour? ')
rate=float(rate)
pay=(rate*work_hours)
print "Well hi there ",user_name
print "your earnings are: ",pay | true |
9c695f5445161a76936e72ac336a9253d9113541 | s4git21/Two-Pointers-1 | /Problem-1.py | 1,086 | 4.15625 | 4 | """
Approach:
1) if you were to sort the first and last flag, your middle flag is automatically sorted
2) use two pointers to keep track of the sorted indices for 0 and 2
3) you'd need to have a 3rd pointer to make comparisons from left to right
4) swap elements at 3rd moving pointer with either left/right pointer if 0/2 is found
5) keep in mind that you'd have to make two comparisons at each index. you'd make the second comparison even if you
have swap after the first comparison
"""
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
left = 0
right = len(nums) - 1
curr = 0
while curr <= right:
if nums[curr] == 0:
nums[curr], nums[left] = nums[left], nums[curr]
left += 1
curr += 1
elif nums[curr] == 2:
nums[curr], nums[right] = nums[right], nums[curr]
right -= 1
else:
curr += 1
"""
TC: O(n)
SC: O(1)
"""
| true |
50bc005b9baea7ad7e64f4ec4f95149c94ab2b0c | grogsy/python_exercises | /csc232 proj/encrypt.py | 2,898 | 4.28125 | 4 | import random
import string
import sys
symbols = list(string.printable)[:94]
def encrypt(text):
"""Add three chars after every char in the plaintext(fuzz)
After, substitue these chars with their hex equivalent(hexify)
input: string sentence
returns: string
>>> encrypt('secret message')
'733450606535326d63455b0723f4a7365383b5974396b78
6d6378666564434573b3860733c2c296137416367317e72654f3e62'
"""
cipher = fuzz(text)
return hexify(cipher)
def fuzz(text):
"""Obfuscate a message by adding three letters after evey char in string.
Input gets fed to the fuzz_word function which performs the actual
fuzzing of words.
input: string
returns: string
>>> fuzz('hello')
'h0"Ze:~sl3~^l2a[o;D>'
>>> fuzz('secret message')
'sD6jeSH$c|\\erf7Fe^<%t4}k m_s(e*Sesgvtse2+a\\>@g$;YehW^'
"""
return ' '.join([fuzz_word(word) for word in text.split()])
def fuzz_word(word):
"""Function which takes input from the fuzz function. This is where
the actual obfuscating logic takes place. We take random ascii chars
and symbols from the built-in string module's printable attribute.
Then we concatenate them to every letter in the word.
input: single word string
returns: string
"""
res = []
for c in word:
for i in range(3):
c += random.choice(symbols)
res.append(c)
return ''.join(res)
def hexify(text):
"""Sub all the chars in the string into its hex equivalent.
This function feeds individual words to the hexify_word
function which performs the actual logic.
input: string
returns: string
>>> hexify('I am a secret message!!')
'49 616d 61 736563726574 6d6d573736167652121'
"""
return ' '.join([hexify_word(word) for word in text.split()])
def hexify_word(word):
"""Helper to the hexify function, translates words to their
hex equivalent individually. Every word will be appended to
a list of words to be joined into a sentence.
input: string of hex characters
returns: string
"""
return ''.join([str(hex(ord(c))[2::]) for c in word])
if __name__=='__main__':
#>>>sys.argv
# ['encrypt.py', <file_to_encrypt>]
#so we'll set our readfile var to open as the actual file supplied in command line
readfile = sys.argv[1]
#trims the extension from the name of the file
writefile = readfile.split('.')[0] + "_encrypt.txt"
with open(readfile) as plaintext, open(writefile, 'w+') as ciphertext:
#does not return single string, returns a list of lines from the file
contents = plaintext.readlines()
encrypted_contents = []
for line in contents:
encrypted_contents.append(encrypt(line))
ciphertext.write('\n'.join(encrypted_contents))
print("encrypted file: %s" % readfile)
print("check directory.") | true |
2f0fbbe6d72d54c7ca98ed12821a1b12e59a2313 | grogsy/python_exercises | /datastructures/merge_sort.py | 768 | 4.1875 | 4 | def merge_sort(arr):
if len(arr) <= 1:
return arr
left = []
right = []
midpoint = len(arr) // 2
for i, element in enumerate(arr):
if i < midpoint:
left.append(element)
else:
right.append(element)
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
def merge(left, right):
res = []
while left and right:
if left[0] <= right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
remaining = left or right
return res+remaining
if __name__ == '__main__':
from random import choice
a = [choice(range(50)) for _ in range(20)]
print("Before: ", a)
print("After: ", merge_sort(a))
| true |
34445e45fd10f8a252f743c9410099857c8ca96d | kiksnahamz/python-fundamentals | /creating_dictionary.py | 1,040 | 4.75 | 5 | #Creating a dictionary from a list of tuples
'''
Creating a list of tuples which we name "users"
'''
users = [
(0, "Bob", "password"),
(1, "Rolf", "bob123"),
(2, "Jose", "longp4assword"),
(3, "username", "1234"),
]
'''
we are transcribing the data from users into a dictionaries. The first is a username mapping which will take the
username as the key which will map to it's corresponding tuple. The key of each of the key:value pairs will consist of
the [1]st element of each tuple in the list of users. In this case this refers to the names "Bob","Rolf","Jose" etc.
The value will then consist of the tuple associated with the key. If we print username mapping we are returned this newly
created dictionary of k:v pairs with name:associated tuple. This dictionary called "username_mapping" can be used like a
normal dictionary
'''
username_mapping = {user[1]: user for user in users}
userid_mapping = {user[0]: user for user in users}
print(username_mapping)
print(username_mapping["Bob"])
| true |
46104a9824c0c549577b73a45c048bc7009936ca | rsheftel/raccoon | /raccoon/sort_utils.py | 1,828 | 4.15625 | 4 | """
Utility functions for sorting and dealing with sorted Series and DataFrames
"""
from bisect import bisect_left, bisect_right
def sorted_exists(values, x):
"""
For list, values, returns the insert position for item x and whether the item already exists in the list. This
allows one function call to return either the index to overwrite an existing value in the list, or the index to
insert a new item in the list and keep the list in sorted order.
:param values: list
:param x: item
:return: (exists, index) tuple
"""
i = bisect_left(values, x)
j = bisect_right(values, x)
exists = x in values[i:j]
return exists, i
def sorted_index(values, x):
"""
For list, values, returns the index location of element x. If x does not exist will raise an error.
:param values: list
:param x: item
:return: integer index
"""
i = bisect_left(values, x)
j = bisect_right(values, x)
return values[i:j].index(x) + i
def sorted_list_indexes(list_to_sort, key=None, reverse=False):
"""
Sorts a list but returns the order of the index values of the list for the sort and not the values themselves.
For example is the list provided is ['b', 'a', 'c'] then the result will be [2, 1, 3]
:param list_to_sort: list to sort
:param key: if not None then a function of one argument that is used to extract a comparison key from each
list element
:param reverse: if True then the list elements are sorted as if each comparison were reversed.
:return: list of sorted index values
"""
if key is not None:
def key_func(i):
return key(list_to_sort.__getitem__(i))
else:
key_func = list_to_sort.__getitem__
return sorted(range(len(list_to_sort)), key=key_func, reverse=reverse)
| true |
115a859802940f367926d1487f65bb874e075d41 | xatlasm/python-crash-course | /chap4/4-10.py | 267 | 4.25 | 4 | #Slices
cubes = [cube**3 for cube in range(1,11)]
print(cubes)
print("The first three items in the list are: ")
print(cubes[:3])
print("Three items from the middle of the list are: ")
print(cubes[3:6])
print("The last three items in the list are: ")
print(cubes[-3:]) | true |
16bd7425b8d794c6ccdb22fbb12d1f764c4ccd7e | Jayoung-Yun/test_python_scripts | /repeating_with_loop.py | 903 | 4.28125 | 4 | word = 'lead'
print word[0]
print word[1]
print word[2]
print word[3]
print '========================'
word = 'oxygen'
for char in word:
print char # space is necessar!
length = 0
for vowel in 'aeiou' :
length = length +1
print (' In loop : There are'), length, ('vowels')
print ('There are'), length, ('vowels')
print '========================'
letter = 'z'
for letter in 'abc':
print letter
print ('after the loop, letter is'), letter
print len('aeiou')
print '====[ From 1 to N ]===='
for i in range(1, 10, 2) :
print (i)
for i in range(3, 10, 3) : print (i)
print "====[ Computing Powers With Loops ]===="
print 5**3
exp = 1
for i in range(0,3) :
exp = exp * 5
print i, exp
print exp
print "====[ Reverse a String ]===="
rev_word = ''
org_word = 'Newton'
for char in org_word:
#rev_word = rev_word + char
rev_word = char + rev_word
print char
print rev_word
| true |
9d10008f588fe46246752758f08b27d66cde8ba8 | leonardlan/myTools | /python/list_tools.py | 936 | 4.28125 | 4 | '''Useful functions for lists.'''
from collections import Counter
def print_duplicates(my_list, ignore_case=False):
'''Print duplicates in list.
Args:
my_list (list): List of items to find duplicates in.
ignore_case (bool): If True, case-insensitive when finding duplicates.
Returns:
None
Example:
>>> print_duplicates([1, 2, 3, 3, 3, 'a', 'a', 'b', 'B', 'b', 'c'], ignore_case=True)
3 appears 3 times
b appears 3 times
a appears 2 times
'''
# Handle ignore_case.
if ignore_case:
my_list = [item.lower() if hasattr(item, 'lower') else item for item in my_list]
counter = Counter(my_list)
duplicated_count = 0
for item, count in counter.most_common():
if count == 1:
break
print('{} appears {} times'.format(item, count))
duplicated_count += 1
print('Found {} duplicate(s)'.format(duplicated_count))
| true |
de7566c719dd416848d89a6a1710cd12a534230e | sabil62/Python-and-Data-Analysis | /matplotlib.py | 353 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 10 22:15:24 2019
@author: User
"""
import matplotlib.pyplot as plt
x= [0,1,2,3,4,5,6]
y= [i**2 for i in x]
z= [i**3 for i in x]
plt.plot(x,y,'r',label='square')
plt.plot(x,z,':',label='cubic')
plt.legend()
#this is just to show axes comment this out
plt.xlim(-1,7)
plt.ylim(-50,300)
plt.show()
print (y) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.