blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
bd518c71964b3fa7e781c99a875f45d185d3e247 | akshaypawar2508/Coderbyte-pythonSol | /19-second-greatlow.py | 693 | 4.15625 | 4 | # Have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space. For example: if arr contains [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and will contain at least 2 numbers. It can get tricky if there's just two numbers!
# Use the Parameter Testing feature in the box below to test your code with different arguments.
def SecondGreatLow(arr):
newArr = sorted(set(arr))
return "%d %d" %(newArr[1], newArr[-2])
# keep this function call here
# to see how to enter arguments in Python scroll down
print SecondGreatLow(raw_input())
| true |
d11a452772714eed086ceb911cd0fab19c945c84 | akshaypawar2508/Coderbyte-pythonSol | /50-three-five-multiple.py | 244 | 4.21875 | 4 | def ThreeFiveMultiples(num):
return sum(i for i in range(num) if i % 3 == 0 or i % 5 == 0)
# keep this function call here
# to see how to enter arguments in Python scroll down
print ThreeFiveMultiples(raw_input())
| true |
99364aa2876cf534ed45a313d6da945047a6c77c | dondreojordan/cs-guided-project-python-basics | /src/demonstration_2.py | 1,800 | 4.5 | 4 | """
You have been asked to implement a line numbering feature in a text editor that
you are working on.
Write a function that takes a list of strings and returns a new list that
contains each line prepended by the correct number.
The numbering starts at 1 and the format should be `line_number: string`. Make
sure to put a colon and space in between the `line_number` and `string` value.
Examples:
number([]) # => []
number(["a", "b", "c"]) # => ["1: a", "2: b", "3: c"]
"""
######################################### My Attempt, FIX ###############################################
# line_number = [1, 2, 3, 4]
# string_value = ["a", "b", "c", "d"]
# def number(list_values):
# # Create an empty list for numbers
# numbers = []
# # Create a for loop that takes the indeces of list_values and puts the line_number in front, seperated by a ":"
# for i in range(0, len(string_value)):
# numbers.append(i+1)
# # When you have two lists, insert in indexed position (not i +1) with the semi-colon":"
# string_value.insert(i, numbers[i])
# return string_value
# # Returns a list (e.g. ["1: a", "2: b", "3: c"])
# print(number(string_value))
############################################################################################################
string_value = ["a", "b", "c", "d"]
# # One Way
def number(lines):
output = []
line_number = 1
for line in lines:
output.append(f"{line_number}: {line}")
line_number += 1
return output
print("First Function", number(string_value))
# Second Way
def numbers(lines):
output = []
for index, line in enumerate(lines):
output.append(f"{index + 1}: {line}")
return output
if __name__ == '__main__':
print("Second Function", numbers(string_value)) | true |
9db9306349d2159e68a24c5551b5bd4a13744d38 | CodetoInvent/interviews | /word_search.py | 1,649 | 4.125 | 4 | # Word Search
# Given a 2D board and a word, find if the word exists in the grid.
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
# Example:
board = [
["A","B","C","E"],
["S","F","E","S"],
["A","D","E","E"]
]
# Given word = "ABCCED", return true.
# Given word = "SEE", return true.
# Given word = "ABCB", return false.
def word_search(board, word):
if not board: return False
if not word: return True
starts = find_first_letters(board, word[0])
if not starts: return False
for start in starts:
if traverse_board(board, word, 1, [], *start):
return True
return False
def find_first_letters(board, letter):
starts = []
for row in range(len(board)):
for column in range(len(board[row])):
if board[row][column] == letter:
starts.append((row, column))
return starts
def traverse_board(board, word, next_index, seen, row, column):
if next_index > len(word) - 1:
return True
letter = word[next_index]
seen.append((row, column))
out_of_bounds = lambda row, column, board: \
(row >= len(board) or row < 0) or \
(column >= len(board[0]) or column < 0)
neighboring = [
(row-1, column),
(row+1, column),
(row, column-1),
(row, column+1)
]
for (r, c) in neighboring:
if out_of_bounds(r, c, board): continue
if board[r][c] == letter and (r, c) not in seen:
print letter
if traverse_board(board, word, next_index+1, seen, r, c):
return True
seen.remove((row, column))
return False
print word_search(board, "ABCESEEEFS") | true |
96673d4a338e8307c98a90b85d4a6716a63a0465 | CodetoInvent/interviews | /reverse_array.py | 493 | 4.21875 | 4 |
arr = [1, 4, 3, 2]
def reverse(array):
for i in range(len(array)//2):
array[i], array[-i-1] = array[-i-1], array[i]
return array
print reverse(arr)
word = 'hello'
def reverse_recursive(word):
def helper(array, index):
if index == len(array)//2: return array
array[index], array[-index-1] = array[-index-1], array[index]
return helper(array, index+1)
reverse = helper(list(word), 0)
return ''.join(reverse)
print reverse_recursive(word)
| false |
ce5a10d97819eca62d024f5194e1915256e0785b | gabriellaec/desoft-analise-exercicios | /backup/user_223/ch45_2020_04_13_03_52_08_299793.py | 285 | 4.1875 | 4 | numbers=[]
numbers_input=int(input("Insira um número inteiro positivo: "))
numbers.append(numbers_input)
while numbers_input>0:
numbers_input=int(input("Insira um número inteiro positivo: "))
numbers.append(numbers_input)
for i in range(len(numbers)-2, -1, -1):
print (numbers[i]) | false |
776e6918df16e428538af1208f50337a55477a4a | gabriellaec/desoft-analise-exercicios | /backup/user_224/ch45_2020_10_07_11_51_24_545173.py | 233 | 4.125 | 4 | numeros_positivos = int(input('Digite numero inteiro positivo '))
lista = []
while numeros_positivos > 0 :
lista.append(numeros_positivos)
numeros_positivos = int(input('Digite outro numero '))
lista.reverse()
print(lista)
| false |
c6ced3da1e382caf542177707d59fddce9cfc99c | gabriellaec/desoft-analise-exercicios | /backup/user_167/ch4_2019_02_26_15_39_31_097108.py | 210 | 4.125 | 4 | a= int(input("digite a sua idade : "))
if a <= 11:
print ("você é um crianca")
if a>11 and a<= 17:
print ("você é um adolescente")
if a > 18:
print ("você é um adulto")
| false |
7e87f68fbe09ef897945e34ae60237f3c4602921 | gabriellaec/desoft-analise-exercicios | /backup/user_042/ch35_2020_10_05_12_06_20_179554.py | 242 | 4.15625 | 4 | pergunda_número = input('Digiete um número:')
while True:
if pergunda_número != 0:
soma += pergunda_número
pergunda_número = input('Digiete um número:')
print (soma)
else:
return False
| false |
0fdd0b2278957db19092956048cb67bc8f6133cf | marcobravociencias/Redes2017 | /Practica01/Code/Calculator.py | 1,186 | 4.21875 | 4 | #
#Clase calculadora que cuenta con las operaciones de Suma y Resta
#
class calculator:
# -*- coding: utf-8 -*-
#
#Metodo que realiza la suma de 2 valores
# @param num1 primer operando
# @param num2 segundo operando
# @return suma de los valores, error en otro caso
#
def suma(self, num1, num2):
if self.verifica(num1, num2):
return float(num1)+float(num2)
else:
return 'Error'
#
#Metodo que realiza la resta de 2 valores
# @param num1 primer operando
# @param num2 segundo operando
# @return resta de los valores, error en otro caso
#
def resta(self, num1, num2):
if self.verifica(num1, num2):
return float(num1)-float(num2)
else:
return 'Error'
#
#Metodo que verifica que la cadena que se pasa a la interfaz sea
# un numero
# @param num1 primer operando
# @param num2 segundo operando
# @return True en caso de que sean numeros, False en otro caso
#
def verifica(self, num1, num2):
if num1.isdigit() and num2.isdigit():
return True
else:
try:
float(num1)
float(num2)
return True
except ValueError:
print 'Son letras : '+num1+' '+num2
return False
#cal = calculator();
#c = cal.resta('2','3')
#print c
| false |
ad246fd89117552e84c3a63900b0767fd9a17532 | SarmenSinanian/Sorting | /src/insertion_sort.py | 826 | 4.15625 | 4 | def insertion_sort(items):
# Split the list into sorted and unsorted
# For each element in unsorted...
counter = 0
for i in range(1, len(items)):
# Insert that element into the correct place in sorted
# Store the elements in a temp variable
temp = items[i]
# Shifting all larger sorted elements to the right by 1
j = i
while j > 0 and temp < items[j - 1]:
print('**********************')
counter += 1
print(items)
items[j] = items[j - 1]
j -= 1
print(items)
# Insert the element after the first smaller element
items[j] = temp
print(items)
print(f'Counter = {counter}')
return items
l = [7, 4, 9, 2, 6, 3, 0, 8, 5, 1]
insertion_sort(l) | true |
bdae5a540d52899874f83a56c7ebb42e1199a3d4 | Ebi-aftahi/Python_Solutions | /Print multiplication table/multi_table.py | 514 | 4.1875 | 4 | user_input= input()
lines = user_input.split(',')
# This line uses a construct called a list comprehension, introduced elsewhere,
# to convert the input string into a two-dimensional list.
# Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ]
mult_table = [[int(num) for num in line.split()] for line in lines]
for item in mult_table:
for index, digit in enumerate(item):
if(index != len(item)-1):
print(digit, end='')
print(' | ', end='')
else:
print(digit)
| true |
0a11b0f40cd3576d71a598dd2a695851ddf4ed16 | kawasaki2013/Python-4 | /Python Basic Syntax/Quotation in Python.py | 368 | 4.125 | 4 |
#****************** Quotation in Python **********************
# Python accepts single ('), double (") and triple (''' or """)
# For example
print(' Quotation ')
print(" Quotation ")
# The triple quotes are used to span the string across multiple lines
print("""
Quotation
Python
""")
# Never used to ' " And " ' And ""' ''"
| true |
49e68d5ca9c735490ef321c1e8e89d561455641e | kawasaki2013/Python-4 | /File Writting.py | 609 | 4.15625 | 4 |
# File writing in python
# ' W ' Open file write only
# ' Wb' Opens a file for writing only in binary format
#----------------------- Now Create a Text.txt File ----------------------@
'''
file = open('Text.txt', 'w')
file.write('Jibon\n')
file.write('Ahmed\n')
file.write('Kurigram\n')
file.write('Dhaka\n')
file.write('Bangladesh\n')
'''
#---------------------- Another way to write file----------------------------@
with open('Jibon.txt', 'w') as wf:
wf.write('I am learning......\n')
wf.write('Python Programming\n')
wf.write('Web Design\n')
| false |
998f84ccbe72d5052defff47d5851ce4d4fe368d | karthikaManiJothi/PythonTraining | /Assignment/Day2Assignment/exec1.py | 263 | 4.15625 | 4 | n=int(input("Enter a number"))
if n>0:
if n%2!=0:
print("Weird")
elif n>=2 and n<=5:
print("Not Weird")
elif n>=6 and n<=10:
print("Weird")
elif n>20:
print("Not Weird")
else:
print("enter only positive number") | false |
5b0c97eb2fd86ee037ba92440b8d96e027f07a79 | karthikaManiJothi/PythonTraining | /Assignment/Day3Assignment/exec11.py | 224 | 4.21875 | 4 | #fibonaaci value of nth number
def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
num=int(input("enter a number:"))
print("Fibonacci of",num,":")
print(fibonacci(num-1)) | false |
8e122e1a7bf635f0333301f95ac9b9b14ecb691b | karthikaManiJothi/PythonTraining | /Assignment/19-06-2021Assignment/BMIvalidation.py | 911 | 4.1875 | 4 | from BMIcal import BMI
class validation:
@staticmethod
def validate(weight,height):
# by using bmical module
bmi_value = BMI.bmi_calculate(weight, height)
if bmi_value < 18.5:
print("your BMI is",bmi_value,"which means you are underweight person")
elif bmi_value >= 18.5 and bmi_value <= 24.9:
print("your BMI is", bmi_value, "which means you are healthy")
elif bmi_value > 25.0 and bmi_value <= 29.9:
print("your BMI is", bmi_value, "which means you are overweight person")
elif bmi_value>=30.0:
print("your BMI is", bmi_value, "which means you are obese")
if __name__ =='__main__':
name =input("What is your Name:")
string="Hi "+name+", What is your height in metres?"
height =float(input(str(string)))
weight =float(input("What is your weight:"))
val =validation()
val.validate(weight,height)
| true |
0c747d40c741dfeb05d56af4ddd0ddc2311b52fa | DeanChurch1/portfolio | /calculator.py | 1,664 | 4.125 | 4 |
def addition(x, y):
return x + y
def subtract(x, y):
return x - y
def divide(x, y):
if x or y == 0:
print("Cant divide by zero")
return x / y
def multiply(x, y):
return x * y
def calculator():
print("choose if you want to add 1, subtract 2, divide 3, or multiply 4")
choice=input("choose choice 1/2/3/4")
num1=int(input("what is your 1st number"))
num2=int(input("what is your 2nd number"))
if choice == '1':
print(num1, "+", num2, "=", addition(num1,num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1,num2))
elif choice == '3':
print(num1, "/", num2, "=", divide(num1,num2))
elif choice == '4':
print(num1, "*", num2, "=", multiply(num1,num2))
else:
print("not possible")
calculator()
def addition(x, y):
return x + y
def subtract(x, y):
return x - y
def divide(x, y):
if x or y == 0:
print("Cant divide by zero")
return x / y
def multiply(x, y):
return x * y
def calculator():
print("choose if you want to add 1, subtract 2, divide 3, or multiply 4")
choice=input("choose choice 1/2/3/4")
num1=int(input("what is your 1st number"))
num2=int(input("what is your 2nd number"))
if choice == '1':
print(num1, "+", num2, "=", addition(num1,num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1,num2))
elif choice == '3':
print(num1, "/", num2, "=", divide(num1,num2))
elif choice == '4':
print(num1, "*", num2, "=", multiply(num1,num2))
else:
print("not possible")
calculator()
| false |
cb4943dee987a69256fab4c643b299e097b3e2c2 | sinderpl/CodingExamples | /python/Data Structures/Linked Lists/reorderList.py | 923 | 4.25 | 4 | def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
slow = fast = head
# Find the middle of a linked list
# o(n)
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
prev = None
curr = slow.next
# Reverse second half
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
slow.next = None
print(head)
print(prev)
# merge the two lists
head1, head2 = head, prev
while head2:
next = head1.next
head1.next = head2
# swap the ordering around so they swap
head1 = head2
head2 = next | true |
863c46ba2cc016aa8a89bf8767dbd21b6b20fc86 | archeranimesh/Geeks4Geeks-Python | /SRC/01_Array/04_array_rotation.py | 851 | 4.34375 | 4 | # Program to cyclically rotate an array by one
# https://www.geeksforgeeks.org/c-program-cyclically-rotate-array-one/
# 4. Program to cyclically rotate an array by one
def rotate(arr):
n = len(arr)
temp = arr[n - 1]
for x in range(n-1, 0, -1):
arr[x] = arr[x - 1]
arr[0] = temp
def another_rotate(arr):
n = len(arr)
temp = arr[0]
for i in range(n - 1):
arr[i] = arr[i + 1]
arr[n - 1] = temp
# Print the array
def print_array(arr, msg="The array is ="):
print(msg, end=" ")
for i in range(len(arr)):
print(arr[i], end=" ")
print("\n")
if __name__ == "__main__":
arr = [1,2,3,4,5]
print_array(arr)
rotate(arr)
print_array(arr, msg="The rotated array is =")
arr = [1,2,3,4,5]
another_rotate(arr)
print_array(arr, msg="The another rotated arrar is =")
| false |
3f319fde3e7d1756eaa97164d4308d6aee7651ef | clairefan816/PythonExcercises | /lab02/angle.py | 304 | 4.1875 | 4 | import math
def main():
angle = float(input('Please enter an angle: '))
cosine_angle = math.cos(math.radians(angle))
sine_angle = math.sin(math.radians(angle))
print('The cosine of {} is {}'.format(angle, cosine_angle))
print('The sine of {} is {}'.format(angle, sine_angle))
main() | false |
6e4fd37c170a4fbc4e65d2c0f742e5b7c05b2f12 | clairefan816/PythonExcercises | /hw04/password.py | 2,255 | 4.3125 | 4 | # Author: Yu Fan (fan.yu@husky.neu.edu)
# For homework 4
# Generate username and passwords
import random
import math
# collect informations from the user, and the origianal case is kept.
print('Welcome to the username and password generator!')
first_name = input('Please enter your first name: ')
last_name = input('Please enter your last name: ')
word = input('Please enter your favoriste word: ')
def new_last(last_name):
"""
rebuilt the last_name if its length less than 7
And switch all characters into lower cases.
"""
new_last = last_name.ljust(7, '*')
new_last = new_last.lower()
return new_last
def main():
"""
Generate username through string concatenation
Generate three passwords
"""
user_last = new_last(last_name) # invocate the new_last function for getting new qualified last name
username = (first_name[0] + user_last + str(random.randint(0, 99))).lower() # concatenate all strings together for consituting the username
print('Thanks,', first_name, ', your username is ',username)
print('Here are three suggested passwords for you to consider: ')
first_password = first_name + last_name + str(random.randint(0, 99))
final_first_password = '' # initiate a string parameter for storing qualified password
for i in first_password: # iterate all characters in first_password and replace specific items with needed
if i == 'o':
i == '0'
if i == i:
i == '1'
if i == 's':
i == '$'
final_first_password = final_first_password + i # the new qualified item is stored in final_first_password through assignment statement
print('Password 1:', final_first_password)
# computing the second password
second_password = '' # initiate a string paratemer
second_password = first_name[0].lower() + first_name[-1].upper() + last_name[0].lower() + last_name[-2].upper() + word[0].lower() + word[-1].upper()
print('Password 2:', second_password)
# computer the third password
third_password = last_name[0:random.randint(1, len(last_name))] + word[0: random.randint(1, len(word))] + first_name[0:random.randint(1, len(first_name))]
print('Password 3: ', third_password)
main()
| true |
d9aebcf78c5cc0b94cc98e25cf1c8fb7b86c6bf3 | rkillough/riskPlanningBDI | /BDIPlanning/decisionRule/Rinduction.py | 1,374 | 4.4375 | 4 | #resources - set of amounts of remaining resources
#weights - corresponding value of the resources
#requirments - corresponding amounts of resources needed to complete the goal from this point
'''
The procedure is to calculate a "scarcity measure" from the amoutn we have vs the amount we need, this is then modulated by the weight assigned, giving an indication of how much we value the resource. The values for each resource are then combined and constrained to within a 0 to maxR range. Where maxR is the maximum useful R, i.e. the point at which the probability of success is maximised.
'''
class resource():
__init__(supply, demand, weight, scarcity):
self.supply = supply #amount of the resource available
self.demand = demand #amount of resource required to reach goal
self.weight = weight #the external value of this resource (as a [0,1] where all weights add to 1)
self.scarcity = self.calcScarcity() #a measure of the scarcity based on supply & demand
def calcScarcity():
if self.demand == 0: return 0 #no demand, no scarcity
elif self.demand > self.supply: return 0 #demand exceeds supply, give up
else: return 1/(self.supply/self.demand)
def getR(resources, maxR):
total = 0
for r in resources:
total += (r.value * maxR) * r.scarcity
R = total
print R
maxR = 5
resources = [3,10]
weights = [0.6, 0.1]
getR(weights, resources, maxR)
| true |
626416c09b0a0584ddb49530bbcbf283fa7ea218 | tayvionne/CTI110 | /M5T1_KilometerConverter_TayVionneCarey.py | 719 | 4.375 | 4 | #Kilometer Converter
#June 29, 2017
#CTI-110 M5T1_KilometerConverter
#TayVionne Carey
#
#The main fucntion gets a distance in kilometers and calls
#the show_miles function to convert it.
conversion_factor = 0.6214
def main ():
#Get the distance in kilometers.
kilometers = float(input('Enter a distance in kilometers: '))
#Display the distance converted to miles.
show_miles(kilometers)
#The show_miles function converts the parameter km from
#kilometers to miles and displayes the result.
def show_miles (km):
#Calculate miles.
miles = km * conversion_factor
#Display the miles.
print(km, 'kilometers equals', miles, 'miles.')
#Call the main function.
main ()
| true |
d0298e41a28a3f32764d9c67bff84c439c79ea0c | andreicoada/repo1 | /07102020.py | 1,241 | 4.28125 | 4 | print("primul meu mesaj") #nu necesita paranteze 2.7
#a = input('apasa tasta r') #raw_input pt python 2.7
#print(a)
print("Elevul 'x' nu si-a realizat tema")
print('Elevul "X" nu si-a realizat tema')
# print("Elevul "x" nu si-a realizat tema") #nu functioneaza
print("elevul ''''' nu si-a realizat tema")
print('elevul """""" nu si-a realizat teama')
print("""
\tAna are mere
Maria are BMW
nu plange ana""")
variabila1 = 1
variabila2 = 2
variabila3 = f" Ana are {variabila1} mar si {variabila2} pere."
print(variabila3)
variabila4 = "Ana are {} mar si {} pere".format(variabila1,variabila2)
print(variabila4)
variabila3 = f" Ana are {1} mar si {2} pere.".format(variabila1,variabila2)
print(variabila3)
variabila5 = "Ana are {1} mar si {1} pere.".format(variabila1,variabila2)
print(variabila5)
variabila2 = 3
print("variabila4 =>>", type(variabila4))
print("variabila2 =>>", type(variabila2))
print(type(variabila4))
print(type(variabila2))
variabila6 = "Ana are " + str(variabila2) + " mere."
print(variabila6)
print(variabila1 + variabila2)
print(str(variabila1)+ str(variabila2))
print(variabila2 - variabila1)
variable_number_1 = 3 - 2j
print(variable_number_1.real)
print(variable_number_1.imag)
print(variable_number_1.conjugate()) | false |
2b38bcff563c1ad62c37ba72c3e02d969d35a46f | frclasso/turma1_Python3_2018 | /cap04/imposto-de-renda.py | 844 | 4.125 | 4 | '''Normalmente, pagamos o Imposto de renda por faixa de salário.
Imagine que para salarios menores que R$1.000,00 nao teriamos imposto a
pagar, ou seja, alíquota 0%. Para salários entre R$1.000,00 e R$3.000,00
pagamos 20%. Acima desses valores ,a alíquota seria de 35%.
Esse problema se pareceria muito com o anterior, salvo se o
imposto não fosse cobrado diferentemente para cada faixa,
ou seja, quem ganha R$4.000,00 tem os primeiros R$1.000,00
isentos de impostos; com o montante entre R$1.000,00 e R$3.000,00
pagando 20%, e restante pagando os 35%.
'''
salario = float(input("Digite salario: "))
base = salario
imposto = 0
if base > 3000:
imposto = imposto + ((base -3000) * 0.35)
base = 3000
if base > 1000:
imposto = imposto + ((base - 1000) * 0.20)
print("Salrio: R$%.2f Imposto a pagar R$%.2f " % (salario, imposto)) | false |
1983f1cc44564d01a3eb62336609eaf2b7e9218e | frclasso/turma1_Python3_2018 | /cap04/exercicio-4-9.py | 789 | 4.21875 | 4 | #!/usr/bin/env python3
'''Escreva um programa para aprovar o empréstimo bancário para comprar de uma casa.
O programa deve perguntar o valor da casa a comprar, o salário e a quantidade de anos
a pagar. O valor da prestação mensal, não pode ser superior a 30% do salário.
Calcule o valor da prestação como sendo o valor da casa a comprar dividido pelo
número de meses a pagar.
'''
valor=float(input("Digite valor da casa: "))
salario=float(input("Digite salario: "))
qtdAnos=int(input("Anos do financiamento: "))
meses = qtdAnos * 12
prestacao= valor / meses
if prestacao > salario * 0.3:
print('Emprestimo negado')
else:
print('Emprestimo Aprovado, valor da prestacao R$%6.2f ' % prestacao)
#print(f'Emprestimo Aprovado, valor da prestacao R${prestacao:6.2f} ') | false |
ebd024b9ba0c1d93ad22404ec67995760c6d2c65 | frclasso/turma1_Python3_2018 | /cap07/exercicio-7-8.py | 1,660 | 4.1875 | 4 | '''Exercício 7.8 Modifique o jogo da forca de forma a utilizar uma lista de palavras.
No início, pergunte um número e calcule o índice da palavra a utilizar pela fórmula:
índice = (número * 776) % len(lista_de_palavras).'''
palavras= [
'Ubuntu',
'JavaScript',
'Django',
'C++',
'Java',
'computador',
'Python',
'Go',
'Perl'
]
indice = int(input('Digite um numero: '))
palavra = palavras[(indice * 776) % len(palavras)].lower().strip()
for x in range(100):
print()
digitadas = []
acertos = []
erros = 0
while True:
senha = ""
for letra in palavra:
senha += letra if letra in acertos else "."
print(senha)
if senha == palavra:
print("Você acertou!")
break
tentativa = input("\nDigite uma letra:").lower().strip()
if tentativa in digitadas:
print("Você já tentou esta letra!")
continue
else:
digitadas += tentativa
if tentativa in palavra:
acertos += tentativa
else:
erros += 1
print("Você errou!")
print("X==:==\nX : ")
print("X O " if erros >= 1 else "X")
linha2 = ""
if erros == 2:
linha2 = " | "
elif erros == 3:
linha2 = " \| "
elif erros >= 4:
linha2 = " \|/ "
print("X%s" % linha2)
linha3 = ""
if erros == 5:
linha3 += " / "
elif erros >= 6:
linha3 += " / \ "
print("X%s" % linha3)
print("X\n===========")
if erros == 6:
print("Enforcado!")
print('A palavra secreta era: ', palavra)
break
| false |
9094a8eea38ee2571bb015924a3762c4f9907a82 | scouvreur/hackerrank | /python/python_functionals/map_and_lambda_function.py | 379 | 4.15625 | 4 | def fibonacci(n):
"""
Returns a list of fibonacci numbers of length n
Parameters
----------
n : int
Number in fibonacci suite desired
Returns
-------
fib_list : list[ints]
List of integers
"""
memo = [0, 1]
for i in range(2, n):
memo += [memo[i - 2] + memo[i - 1]]
return memo[:n]
print(fibonacci(5))
| true |
99786df582fab3a67d802c32b6d636503bc5f77a | bunmiaj/CodeAcademy | /Python/Tutorials/File-IO/4.py | 589 | 4.46875 | 4 | # Reading
# Excellent! You're a pro.
# Finally, we want to know how to read from our output.txt file. As you might expect, we do this with the read() function, like so:
# print my_file.read()
# Instructions
# Declare a variable, my_file, and set it equal to the file object returned by calling open() with both "output.txt" and "r".
# Next, print the result of using .read() on my_file, like the example above.
# Make sure to .close() your file when you're done with it! All kinds of doom will happen if you don't.
my_file = open("output.txt", "r")
print my_file.read()
my_file.close() | true |
43a7a0f57ecb78f05eb45bad6ddd514b132b39fb | bunmiaj/CodeAcademy | /Python/Tutorials/Loops/enumerate.py | 796 | 4.625 | 5 | # Counting as you go
# A weakness of using this for-each style of iteration is that you don't know the index of the thing you're looking at.
# Generally this isn't an issue, but at times it is useful to know how far into the list you are.
# Thankfully the built-in enumerate function helps with this.
# enumerate works by supplying a corresponding index to each element in the list that you
# pass it. Each time you go through the loop, index will be one greater, and item will be the next item
# in the sequence. It's very similar to using a normal for loop with a list,
# except this gives us an easy way to count how many items we've seen so far.
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index + 1, item | true |
809636212d2d6d91ea8845950c114a81add6e4b1 | DrakeData/automate-the-boring-stuff | /Chapter2/littleKid.py | 269 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 18:44:57 2018
@author: Nicholas
"""
name = 'Alice'
age = 13
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, Kiddo.')
else:
print('You are neither Alice nor a little kid.') | false |
9ffad92645406b273a85cd54d5d286af4969ee7a | DrakeData/automate-the-boring-stuff | /Chapter3/collatzSequence.py | 424 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 21:14:51 2018
@author: Nicholas
"""
#collatz
#creating the function
def collatz(number):
#even number
if number % 2 == 0:
print(number // 2)
return number // 2
#odd number
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Enter a number: ")
while n != 1:
n = collatz(int(n)) | true |
ffe946410024fdc959b86df27b446e68bb3e639c | KobiBeef/pythonlearn | /pay.py | 626 | 4.15625 | 4 |
def compute_pay():
while True:
hours = input("Enter hours: ")
rate = input("Enter rate: ")
try:
if len(hours) == 0 or len(rate) == 0:
print ('enter a value')
else:
num_hours = float(hours)
num_rate = float(rate)
if num_hours > 40:
overtime_hours = num_hours - 40
overtime_pay = overtime_hours * (num_rate * 1.5)
regular_pay = (num_hours - overtime_hours) * num_rate
pay = overtime_pay + regular_pay
print (pay)
break
else:
regular_pay = num_hours * num_rate
print (regular_pay)
break
except:
print('Enter numeric numbers only')
compute_pay() | true |
1d416ff3026b4104ad80653968f4f1b6dcb4b717 | dsuz/techacademy-python3 | /more-exercise/is_prime.py | 1,891 | 4.46875 | 4 | """
ユーザー定義関数 is_prime() を作り、それを使って素数判定をするプログラムを作りましょう。
is_prime 関数の仕様は次の通りに作ってください。
1. 引数 n をとる。n は「素数判定の対象となる自然数」とする
2. 戻り値は bool で、n が素数の時 True を返す
"""
def is_prime(n):
"""
与えられた数を素数であるか判定する。アルゴリズムは「エラトステネスのふるい」
Parameters
----------
n : int
素数判定をする数
Returns
-------
result: bool
n が素数である時は True、合成数である時は False
"""
# 自明なケースに対してはすぐ結果を返す
# ここでは判定対象が 2 以下の数と偶数である時に自明なケースとする
if n < 2:
return False
elif n == 2:
return True
elif n % 2 == 0:
print(n, 'is even.')
return False
# 自明でないケースに対して素数判定をする
# ここでは 3 以上の奇数に対して判定をする
odd = 3 # odd は奇数で 3, 5, 7, 9,... と大きくなる
while odd**2 <= n:
if n % odd == 0: # 割り切れたらその時点で素数ではない
print(odd, 'can divide', n)
return False
odd = odd + 2
# 全ての odd で割り切れなかったら、素数である
return True
while True:
buf = input('input number for prime testing: ')
if not buf: # 何も入力がなければプログラムを終了する
print('exit.')
break
try:
input_number = int(buf)
if is_prime(input_number):
print(buf + ' is a prime number.')
else:
print(buf + ' is NOT a prime number.')
except ValueError:
print('invalid value.')
| false |
adcb4a001b4184f59f5bef67bd88a8dd7f4afde7 | Victor-opus/Python-together | /4月29日Chapter12/5dictionary.py | 513 | 4.25 | 4 | dictionaries={}
while True:
opt=raw_input("Add or look up a word(a/l)? ")
if opt=='a':
word=raw_input("Type the word: ")
definition=raw_input("Type the definition: ")
dictionaries[word]=definition
print "Word added!"
elif opt=='l':
word=raw_input("Type the word: ")
if word in dictionaries:
print dictionaries[word]
else:
print "That word isn't in the dictionary yet."
else:
print "enter error"
break
| false |
e9bd0190561d080088645b911fc0de8e2866f6cf | TosinJia/pythonFiles | /c805.py | 289 | 4.21875 | 4 | # 必须参数
# 形式参数 在函数定义的过程中
def add(x, y):
result = x + y
return result
# 实际参数 函数调用的过程中
print(add(1, 2))
# 关键字参数 函数调用过程中指定实参、形参对应关系,提供代码可读性
print(add(y=1, x=2))
| false |
cf76909b9eb508006b9f36296bf720af4de75f81 | nikrasiya/PreCourse_2 | /Exercise_3.py | 1,861 | 4.3125 | 4 | # Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self) -> None:
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Function to get the middle of
# the linked list
def printMiddle(self) -> None:
# cur = self.head
# count = 0
# while cur:
# count += 1
# cur = cur.next
# mid = count // 2 + 1
# cur = self.head
# while count > mid:
# cur = cur.next
# count -= 1
# print(cur.data)
"""
Logic: The fast pointer moves two steps at time
while the slow pointer takes one step.
For instance if there were 50 nodes, when the fast pointer
reaches the last node, the slow pointer would be at the 25th position.
Time Complexity - O(n) Linear
Since we need to go through all the elements once
Space Complexity - O(1) Constant
We always require only two nodes (slow and fast)
"""
if not self.head:
print('Invalid')
slow = fast = self.head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
print(slow.data)
def printList(self) -> None:
cur = self.head
result = []
while cur:
result.append(f'{cur.data}')
cur = cur.next
print(' -> '.join(result))
if __name__ == '__main__':
# Driver code
list1 = LinkedList()
list1.push(5)
list1.push(4)
list1.push(2)
list1.push(3)
list1.push(1)
list1.printList()
list1.printMiddle()
| true |
c41d730eb29ba8d255f72243ab483082c572afcd | rmartind/ctci | /ctci/chapter1/unique.py | 533 | 4.21875 | 4 | """Solution to 1.1 Is Unique."""
def is_unique(string):
"""Determines if a string is unique.
Args:
string: any string of characters.
Returns:
a Boolean value dependant on the uniqueness
Raises:
ValueError: Empty string value given as an argument
"""
temp = list()
if string:
for character in string:
if character in temp:
return False
temp.append(character)
return True
raise ValueError('string: value is empty') | true |
3844564d342532a4a14e4a55c697ff3203488e97 | olehyarmoliuk/Yarmoliuk-Oleh.-Pythone-Core.-Homework | /homework_3/task2.py | 599 | 4.21875 | 4 | from math import pi
q = input('Choose a rectangle, a triangle, or a circle: ')
if q == 'rectangle':
length_1 = float(input('What is the length? '))
width_1 = float(input('What is the width? '))
print("Square of the rectangle is", length_1 * width_1)
elif q == 'triangle':
h = float(input('What is the leg length? '))
b = float(input('What is the base length? '))
print ("Square of the triangle is", 0.5 * h * b)
elif q == 'circle':
r = float(input('What is the radius length? '))
print('Square of the circle is', pi * r**2)
else:
print('Invalid option')
| true |
d0788135b111a928a7a28906d056caa33630937c | olehyarmoliuk/Yarmoliuk-Oleh.-Pythone-Core.-Homework | /homework_8/task4.py | 398 | 4.15625 | 4 | def is_prime(number):
if number == 1:
return False
elif number == 2:
return True
else:
for d in range(2, number):
if number % d == 0:
return False
return True
n = int(input('Enter a number '))
res = is_prime(n)
if res == True:
print(res, '\nYour number is prime')
else:
print(res, '\nYour number is composite') | false |
c81ffc24ca56ae252a5d3b0dc93e02f216068e57 | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/3_StackQueues/3_6.py | 2,640 | 4.125 | 4 | # Animal Shelter: An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis.
# People must adopt either the "oldest" (based on arrival time) of all animals at the shelter,
# or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type).
# They cannot select which specific animal they would like.
# Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat.
from collections import deque
class AnimalShelter():
def __init__(self):
self.queueDog = deque()
self.queueCat = deque()
self.oldest = 0
def enqueue(self, item, animal):
if animal == 'dog':
self.queueDog.append((item, self.oldest))
elif animal == 'cat':
self.queueCat.append((item, self.oldest))
else:
print('We only accept dog and cat')
return
self.oldest += 1
def dequeueAny(self):
# if there are no animals
if not self.queueDog and not self.queueCat:
print('There are no animals currently')
return
# if there are no dogs
if not self.dequeueDog:
first_cat = self.queueCat.popleft()
return first_cat[0]
# if there are no cats
if not self.dequeueCat():
first_dog = self.queueDog.popleft()
return first_dog[0]
first_cat = self.queueCat.popleft()
first_dog = self.queueDog.popleft()
# check if cat arrived earlier
if first_cat[1] < first_dog[1]:
return first_cat[0]
return first_dog[0]
def dequeueDog(self):
if not self.dequeueDog:
print('There are no dogs, sorry')
return
first_dog = self.queueDog.popleft()
return first_dog[0]
def dequeueCat(self):
if not self.dequeueCat:
print('There are no cats, sorry')
return
first_cat = self.queueCat.popleft()
return first_cat[0]
if __name__ == "__main__":
# create empty AnimalShelter
animalSh = AnimalShelter()
animalSh.enqueue(5, 'cat')
animalSh.enqueue(6, 'dog')
animalSh.enqueue(62, 'dog')
animalSh.enqueue(17, 'dog')
animalSh.enqueue(2, 'cat')
print(animalSh.dequeueAny())
animalSh.enqueue(9, 'cat')
animalSh.enqueue(3, 'cat')
print(animalSh.dequeueAny())
animalSh.enqueue(91, 'dog')
animalSh.enqueue(51, 'cat')
print(animalSh.dequeueDog())
animalSh.enqueue(10, 'dog')
print(animalSh.dequeueCat())
| true |
8e7daff7193b0cf13c6d067d24393665653b7088 | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/8_Recursion and Dynamic Programming/8_10.py | 1,757 | 4.1875 | 4 | # Paint Fill: Implement the "paint fill" function that one might see on many image editing programs.
# That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color,
# fill in the surrounding area until the color changes from the original color.
def paint_fill(screen, init_color, color, pc, pr):
if pc >= len(screen[0]) or pc < 0 or pr >= len(screen) or pr < 0:
return
# if not already painted in other color or our color
if screen[pr][pc] == init_color and screen[pr][pc] != color:
screen[pr][pc] = color
paint_fill(screen, init_color, color, pc-1, pr)
paint_fill(screen, init_color, color, pc+1, pr)
paint_fill(screen, init_color, color, pc, pr-1)
paint_fill(screen, init_color, color, pc, pr+1)
return screen
if __name__ == "__main__":
size_r = 3
size_c = 4
# initial screen with 0 color
screen = [[0 for _ in range(size_c)] for _ in range(size_r)]
# insert points of another color
screen[0][1] = 1
screen[0][2] = 1
screen[0][3] = 1
screen[1][2] = 1
screen[2][1] = 1
screen[2][2] = 1
# choose color and starting point to paint screen
color = 2
r, c = 1, 2
init_color = screen[r][c]
print('Screen to paint: ', screen)
print('Painted screen: ', paint_fill(screen, init_color, color, r, c))
screen = [[0 for _ in range(size_c)] for _ in range(size_r)]
# insert points of another color
screen[0][1] = 1
screen[0][2] = 1
screen[0][3] = 1
screen[1][2] = 1
screen[2][1] = 1
screen[2][2] = 1
r, c = 0, 0
init_color = screen[r][c]
print('Screen to paint: ', screen)
print('Painted screen: ', paint_fill(screen, init_color, color, c, r))
| true |
1e3ef3f1875f571f32d260d3ada230640144b13b | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/1_Arrays/1_6.py | 950 | 4.46875 | 4 | # String Compression: Implement a method to perform basic string compression using the counts of repeated characters.
# For example, the string aabcccccaaa would become a2blc5a3.
# If the "compressed" string would not become smaller than the original string, your method should return
# the original string. You can assume the string has only uppercase and lowercase letters (a - z).
# perform string compression
def stringCompression(s):
counter = 1
res = ''
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
counter += 1
else:
res = res + s[i] + str(counter)
counter = 1
# the last char was not added, add it now
res = res + s[-1] + str(counter)
return res
if __name__ == "__main__":
s = 'aabcccccaaba'
#s = input()
if len(s) <= 1:
print(s)
else:
#arr_s = [ch for ch in s]
print(stringCompression(s))
#print(*arr, sep='')
| true |
7bff6f91d506d341f0631dfa0e9b628b88fc2868 | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/5_Bit_Manipulation/5_2.py | 818 | 4.25 | 4 | # Binary to String: Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double,
# print the binary representation.
# If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR:"
def binaryToString(num):
if num > 1 or num < 0:
return "ERROR"
ans = "0" + "."
while num > 0:
if len(ans) >= 32: # check condition on 32 characters
print(ans)
return "ERROR"
num *= 2 # *2 to check if the next digit is 1:
if num >= 1:
ans += "1"
num -= 1 # remove 1 from num to allow next multiplications
else:
ans += "0"
return ans
if __name__ == "__main__":
num = 0.625
print(binaryToString(num))
num = 0.72
print(binaryToString(num))
| true |
36c0fea933b27d423ca99566d2008aaf5ed270e1 | Margarita89/AlgorithmsAndDataStructures | /Cracking the Coding Interview/1_Arrays/1_9.py | 445 | 4.40625 | 4 | # String Rotation: Assume you have a method isSubstring which checks if one word is a substring of another.
# Given two strings, sl and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring
# (e.g.,"waterbottle" is a rotation of"erbottlewat").
def StringRotation(a, b):
s = a + a
return isSubstring(s, b)
s1 = input()
s2 = input()
if len(s1) != len(s2):
print(False)
else:
StringRotation(s1, s2)
| true |
379974e7dbd465ff7ca3b4cd015184c0a153d86c | SP18-Introduction-Computer-Science/map-and-lists-Katherinemwortmano | /Homework 2.py | 514 | 4.34375 | 4 | #Maps and Lists Homework
#List Questions
MyList=["Assignment", "Number Two", "Intro to computer science", "Katherine", "WortmanOtto"]
for Words in MyList :
print(Words)
#Map Questions
myMap = {0:"Assignment", 1: "Number Two", 2: "Intro to computer science", 3: "Katherine" , 4: "WortmanOtto"}
print(myMap)
for loopVar in myMap:
print(loopVar)
for loopVar in myMap:
print(myMap[loopVar])
print(myMap.keys())
print(list(myMap.keys()))
| true |
8fba7c0a7f0ddfcb6b6aaa906d858ed951ddd0e4 | Jownao/codigos_aps | /Fer-nome do produto.py | 1,808 | 4.1875 | 4 | #Questão 3
def linha():
print('=-='*20)
desc=0
produto = input('\nDigite o nome do produto:\n')
linha()
quant = float(input('\nDigite a quantidade do produto:\n'))
linha()
print('\nColoque "." em vez de "," Ex: 10.3')
preco = float(input('\nDigite o preço do produto:\n'))
linha()
if quant <= 10:
desc= 0.00
elif quant <= 20:
desc= 0.10
elif quant <= 50:
desc= 0.20
else:
desc= 0.25
total= quant*preco*(1-desc)
print(f'O produto comprado foi: {produto}.')
print(f'O total a pagar é {total}.')
#Questão 4
salario= float(input('Digite seu salário para obter o desconto do INSS:\n'))
inss=''
if salario < 200:
inss= 8.0
elif salario <500:
inss= 8.5
elif salario <1000:
inss= 9.0
elif salario >=1000:
inss= 9.5
print(f'O desconto do seu INSS é {inss} %.')
#Questão 8
numero=[]
numeros=1
while numeros !=30:
numero.append(numeros)
numeros+=1
soma=sum(numero)
print(f'A soma dos números entre 0 e 30 é {soma}.')
#Questão 9
import sys
quant=0
media=''
idades=[]
loop=True
while loop:
resposta=(input('Você quer digitar sua idade ?(Responda com S ou N)\n'))
if resposta == '1':
idades.append(int(input('Digite sua idade:\n')))
quant+=1
if resposta == '0':
sys.exit()
media=(sum(idades)/quant)
print(f'A média de idades foi: {media}')
#QUestão 10
numeros=[]
escolha=0
escolha=(int(input('Quantos números quer digitar ?\n')))
for i in range (escolha):
i+=1
numeros.append(int(input(f'Digite o número para posição {i}\n')))
max=max(numeros)
min=min(numeros)
soma=max+min
produto=max*min
print(f'O maior número foi {max} e o menor foi {min} a soma entre ele é {soma} e o produto é {produto}.')
| false |
594405aef72cb574acfeab7dcf0ff701ad7bec92 | PyGameTest1/Python | /Ex_5_calc.py | 1,531 | 4.21875 | 4 | # CALCULATOR
'''
a=float(input("Num1 = "))
b=float(input("Num2 = "))
sign=input("SignOfOperation = ")
if sign=="+":
print(a+b)
elif sign=="-":
print(a-b)
elif sign=="*":
print(a*b)
elif sign=="/":
print(a/b)
else:
print("TheWrongSignOfOperation")
# or
print("or")
print("1)+\n2)-\n3)*\n4)/")
a=float(input("Num1 = "))
b=float(input("Num2 = "))
sign=int(input("NumberOfSignOfOperation = "))
if sign==1:
print(a+b)
elif sign==2:
print(a-b)
elif sign==3:
print(a*b)
elif sign==4:
print(a/b)
else:
print("TheWrongSignOfOperation")
'''
# or
print("or")
print("1)+\n2)-\n3)*\n4)/")
sign=int(input("NumberOfSignOfOperation = "))
if sign==1:
print("x+y=z")
x=float(input("Num1 = "))
y=float(input("Num2 = "))
z=x+y
print("Answer: "+str(z))
print("1)+\n2)-\n3)*\n4)/")
sign=int(input("NumberOfSignOfOperation = "))
if sign==2:
print("x-y=z")
x=float(input("Num1 = "))
y=float(input("Num2 = "))
z=x-y
print("Answer: "+str(z))
print("1)+\n2)-\n3)*\n4)/")
sign=int(input("NumberOfSignOfOperation = "))
if sign==3:
print("x*y=z")
x=float(input("Num1 = "))
y=float(input("Num2 = "))
z=x*y
print("Answer: "+str(z))
print("1)+\n2)-\n3)*\n4)/")
sign=int(input("NumberOfSignOfOperation = "))
if sign==4:
print("x/y=z")
x=float(input("Num1 = "))
y=float(input("Num2 = "))
z=x/y
print("Answer: "+str(z))
else:
print("Debil")
| false |
74562f7ffda3842ff0263097f7a2db34f13a556e | hehlinge42/machine_learning_bootcamp | /day00/ex03/std.py | 1,407 | 4.25 | 4 | import numpy as np
from math import sqrt as sqrt
def mean(x):
"""Computes the mean of a non-empty numpy.ndarray, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The mean as a float.
None if x is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if x.size == 0:
return None
summed = 0.0
nb_elem = 0
for elem in x:
try:
summed += elem
nb_elem += 1
except:
return None
return summed/nb_elem
def variance(x):
"""Computes the variance of a non-empty numpy.ndarray, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The variance as a float.
None if x is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if x.size == 0:
return None
original_mean = mean(x)
nb_elem = 0
gaps_vector = np.array([])
for elem in x:
gap = (elem - original_mean) ** 2
gaps_vector = np.append(gaps_vector, gap)
return mean(gaps_vector)
def std(x):
"""Computes the standard deviation of a non-empty numpy.ndarray, using a
for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The standard deviation as a float.
None if x is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
return sqrt(variance(x))
X = np.array([0, 15, -9, 7, 12, 3, -21])
print(std(X))
Y = np.array([2, 14, -13, 5, 12, 4, -19])
print(std(Y))
| true |
339130991ed9cc3908c90ca898ba445d799af90e | VazMF/cev-python | /PythonExercicio/ex080.py | 1,099 | 4.25 | 4 | #Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma lista. já na posição correta de inserção (sem usar sort()). Mostrar lista ordenada.
print('-' * 30)
numList = [] #inicia uma lista vazia
for c in range(0, 5): #repeat 5 vezes para ler os números
num = int(input("Digite um número: ")) #input dos números
if c == 0 or num > numList[-1]: #se o num for o primeiro valor lido ou num for maior que o último valor da lista
numList.append(num) #adiciona o valor a lista
print('\033[33mAdicionado ao final da lista.\033[m')
else: #senão
pos = 0 #posição recebe 0
while pos < len(numList): #enquanto posição for menor que a lista
if num <= numList[pos]: #se o valor lido é menor ou igual
numList.insert(pos, num) #insere o num lido na posição pos.
print(f'\033[33mAdicionado na posição {pos} da lista.\033[m')
break #quebra de enquanto
pos += 1 #variavel para mudar a posição
print('-' * 30)
print(f'LISTA ORDENADA: {numList}')
| false |
6a843f41723dcdaacaa54a5f569a37cbdd139880 | VazMF/cev-python | /PythonExercicio/ex093.py | 1,645 | 4.1875 | 4 | #Crie um programa quue gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e
#quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será
#guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.
print('-' * 50)
print(f'{"< CADASTRO JOGADOR DE FUTEBOL >":^50}') #titulo
print('-' * 50)
jogador = dict() #inicializa um dicionario
partidas = list() #inicializa um lista
jogador['nome'] = str(input('Nome do Jogador: ')) #input do nome do jogador
tot = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) #input do total de partidas jogadas
for c in range(0, tot): #repeticao de 0 ate o valor da variavel total
partidas.append(int(input(f'Quantos gols {jogador["nome"]} fez na {c+1}° partida? '))) #append do gols de cada partida
jogador['gols'] = partidas[:] #jogador no indice gols recebe uma copia de partidas
jogador['total'] = sum(partidas) #jogador no indice total recebe a soma das partidas
print('-' * 50)
print(jogador) #print o dicionario jogador
print('-' * 50)
for k, v in jogador.items(): #repeticao para cada chave e valor nos itens de jogador
print(f'{k.upper()}: {v}') #print da chave e valor
print('-' * 50)
print(f'O jogador {jogador["nome"]} jogou {len(jogador["gols"])} partidas.') #print formatado com as informacoes do jogador
for i, v in enumerate(jogador['gols']): #repeticao para cada indice e valor na lista do dicionario gols
print(f'-> Na {i+1}° partida fez {v} gols.') #print dos gols em cada partida
print(f'Foi um total de {jogador["total"]}.') #print do total de gols do jogador
| false |
1d856bd93fc14565827ca151ec9411203183d0ee | VazMF/cev-python | /PythonExercicio/ex086.py | 873 | 4.4375 | 4 | #crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com a formatação correta.
print('-' * 40)
print(f'{"-= MATRIZ =-":^40}') #titulo
print('-' * 40)
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] #inicializa uma lista matriz com 3 listas iternas com 3 numeros cada
for l in range(0, 3): #repeticao para cada linha
for c in range(0, 3): #repeticao para cada coluna
matriz[l][c] = int(input(f'Digite um valor para a posição [{l}, {c}]: ')) #input do valor mostrando na a posicao de insercao
print('-' * 40) #print para resultado
for l in range(0, 3): #repeticao para cada linha
for c in range(0, 3): #repeticao para cada coluna
print(f'[{matriz[l][c]:^5}]', end='') #print a coluna e linha da matriz sem quebrar linha
print() #quebra linha no final
print('-' * 40)
| false |
704031f94253e95f6146673b1987dca5da25f50b | VazMF/cev-python | /PythonExercicio/ex077.py | 773 | 4.15625 | 4 | #crie um programa que tenha uma tupla com várias palavras (não usar acentos). depois disso, você dever mostrar para cada palavra, quais são as sua vogais.
print('-' * 40)
print(f'{"- CONTADOR DE VOGAIS -":^40}') #titulo
print('-' * 40)
palavras = ('aprender', 'programar', 'linguagem', 'python',
'curso', 'gratis', 'estudar', 'praticar',
'trabalhar', 'mercado', 'progamador', 'futuro') #tupla com as palavras
for p in palavras: #repeticao para cada palavra em palavras
print(f'\nNa palavra \033[34m{p.upper()}\033[m temos ', end='') #print a palavra em maiusculas
for letra in p: #para cada letra em palavra
if letra.lower() in 'aeiou': #se a letra em minusculas estiver em aeiou
print(letra, end=' ') #print a letra
| false |
e703b3b5bba7f5a7add0502bf3f1ebf517dc5412 | VazMF/cev-python | /PythonExercicio/ex081.py | 1,570 | 4.1875 | 4 | #Crie um programa que val ler vários números e colocar em uma lista. Depois mostre: a)quanros numeros foram digitados; b)a lista ordenada decrescente; c)se o valor 5 foi digitado.
print('-' * 45)
print(f'{"- ADD NÚMEROS -":^45}') #titulo
print('-' * 45)
lista = list() #inicia lista vazia
while True: #looping infinito
num = int(input('Digite um número: ')) #input do numero da variavel num
lista.append(num) #append do numero lido na lista
print(f'\033[33mO número {num} foi adicionado a lista.\033[m') #confirmacao de add
res = str(input('Deseja adicionar mais números a lista? [S/N] ')).strip().upper()[0] #input da variavel resposta
while res not in 'SN': #enquanto a resposta nao for s ou n
print('\033[31mInválido, tente novamente.\033[m') #print do erro
res = str(input('Deseja adicionar mais números a lista? [S/N] ')).strip().upper()[0] #pede o input da resposta novamente
if res == 'N': #se a resposta for nao
print('-' * 45) #print de resultado
break #interrompe o while
print(f'A lista contém {len(lista)} valores') #print de quantos numeros tem a lista por meio do lenght
lista.sort(reverse=True) #ordenando a lista em ordem descrescente
print(f'Lista em ordem descrescente: {lista}') #print da lista em ordem decrescente
if 5 in lista: #se a lista tiver o numero 5
print(f'A lista \033[33mCONTÉM\033[m o número 5.') #print que a lista contém o numero 5
else: #senao
print(f'A lista \033[31mNÃO CONTÉM\033[m o número 5') #print que a lista nao contem o numero 5
print('-' * 45)
| false |
c17bd0bd263a32b11c893fa1910a43bf94d4bf61 | vkvikaskmr/ud036_StarterCode | /media.py | 921 | 4.21875 | 4 |
class Movie():
"""This class is used to store and display Movie related informations"""
VALID_RATINGS = {
"General": "G",
"Parental_Guidance": "PG",
"Parents_Strongly_Cautioned": "PG-13",
"Restricted": "R"
}
def __init__(
self,
movie_title,
movie_storyline,
poster_image,
trailer_youtube,
rating):
""":param movie_title: title of the movie
:param movie_storyline: a small description about the movie
:param poster_image: url of the movie poster
:param trailer_youtube: youtuble link to the movie trailer
:param rating: preferred audience of the movie."""
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
self.rating = rating
| true |
ea96241a3fcb200bc6089d6abd9559e699bdbab9 | dmoitim/pos_ciencia_dados | /01 - Introdução à programação com Python/015_aula05_exercicio_calculadora.py | 759 | 4.25 | 4 | '''
Caculadora:
Recebe dois números (inteiros ou decimais) digitados pelo usuário
e realiza a soma, subtração, multiplicação e divisão de ambos,
permitindo a seleção da operação
e exibe o resultado na tela
'''
num1 = float(input("Digite o primeiro número: "))
num2 = float(input("Digite o segundo número: "))
operacao = int(input("Digite a operação (1) Soma - (2) Subtração - (3) Multipicação - (4) Divisão: "))
if operacao == 1:
resultado = num1 + num2
elif operacao == 2:
resultado = num1 - num2
elif operacao == 3:
resultado = num1 * num2
else:
if num2 == 0:
resultado = "Impossível realizar divisão por 0."
else:
resultado = num1 / num2
print("resultado: " + str(resultado)) | false |
9db2e4818a541fac4646889b2cfe36af3dea7119 | yw652/Euler-Problem | /EulerProblem/isFibo.py | 686 | 4.125 | 4 | '''
You are given an integer, N. Write a program to determine if N is an element of the Fibonacci Sequence.
'''
import sys
def isFibo():
list = []
num = int(raw_input())
for i in range(0,num):
i = int(raw_input())
list.append(i)
for next in list:
if next in fibonacci():
print 'IsFibo'
else:
print 'IsNotFibo'
def fibonacci():
fib0 = 0
fib1 = 1
fib = fib0 + fib1
list = []
list.append(fib1)
list.append(fib)
while(fib < 10000000000):
fib0 = fib1
fib1 = fib
fib = fib0 + fib1
list.append(fib)
return list
if __name__ == '__main__':
isFibo()
| true |
43d9339652882c3227d449ba2ef4a7e89a4de29a | br80/lambda_cs | /timing.py | 2,225 | 4.1875 | 4 | # Find the number of seconds it takes to run any operation
# Output it in a format that can be graphed in google sheets
from time import time
import random
# STRETCH: implement the Bubble Sort function below
def bubble_sort( arr ):
# Repeat this until you make it through an entire pass without any swaps.
is_sorted = False
while not is_sorted:
is_sorted = True
# Walk through the array
for i in range(len(arr) - 1):
# comparing each element to its right neighbor.
# If it's smaller than that neighbor,
if arr[i] > arr[i + 1]:
# swap the elements.
arr[i], arr[i+1] = arr[i+1], arr[i]
is_sorted = False
# return arr
# TO-DO: implement the Insertion Sort function below
def insertion_sort( arr ):
# For each element after the first
for i in range(1, len(arr)):
# Find the right spot for the element in the sorted sub-array on the left
# Insert it there:
# Store the current element
current_element = arr[i]
# walk backwards through the sublist, shifting elements to the right by 1
j = i - 1
while j >= 0 and current_element < arr[j]:
arr[j + 1] = arr[j]
j -= 1
# Until we reach a smaller or equal element, then put the current element in that place
arr[j+1] = current_element
return arr
l = [random.randint(0, 1000) for i in range(0, 10000)]
start_time = time()
# Run our code
bubble_sort(l)
# Store the ending time
end_time = time()
print (f"Quadratic runtime: {end_time - start_time} seconds")
l = [random.randint(0, 1000) for i in range(0, 10000)]
inputSizes = [i * 100 for i in range(1, 30)]
times = []
for inputSize in inputSizes:
print(f"running: {inputSize}")
l = [random.randint(0, 1000) for i in range(0, inputSize)]
# Store a starting time
start_time = time()
# Run our code
insertion_sort(l)
# Store the ending time
end_time = time()
# Print out the ending time - starting time
times.append(end_time - start_time)
print("LENGTHS")
for element in inputSizes:
print(element)
print("TIMES")
for t in times:
print(t)
| true |
37542db4542de3492ad901821f73a6e2b0e8a28f | yosef-kefale/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 1,848 | 4.53125 | 5 | #!/usr/bin/python3
class Square:
"""initializes square, determines size, calculates area, prints"""
def __init__(self, size=0, position=(0, 0)):
"""initializes instance of square
Args:
size: size of square
position: position to indent square
"""
self.size = size
self.position = position
def area(self):
"""Determines area"""
return(self.__size ** 2)
@property
def size(self):
"""gets size"""
return self.__size
@size.setter
def size(self, value):
"""sets size"""
if type(value) is not int:
raise TypeError('size must be an integer')
elif value < 0:
raise ValueError('size must be >= 0')
else:
self.__size = value
@property
def position(self):
"""gets position"""
return self.__position
@position.setter
def position(self, value):
"""sets position
Args:
value: value of position
"""
if type(value) is not tuple or len(value) != 2:
raise TypeError('position must be a tuple of 2 positive integers')
elif type(value[0]) is not int or type(value[1]) is not int:
raise TypeError('position must be a tuple of 2 positive integers')
elif value[0] < 0 or value[1] < 0:
raise ValueError('position must be a tuple of 2 positive integers')
else:
self.__position = value
def my_print(self):
"""prints square offsetting it by position with symbol #"""
if self.size == 0:
print('')
return
for i in range(self.__position[1]):
print('')
for i in range(self.__size):
print("{}{}".format(' ' * self.__position[0], '#' * self.__size))
| true |
72fa534dfd63853657ec4e71088bf0b5cb0d8887 | Carter-Co/she_codes_python | /loops/loops_playground.py | 1,332 | 4.125 | 4 | # for num in range(10):
# print(num)
# # for num in range(1, 11):
# # print(num)
# # for num in range(0, 11, 2):
# # print(num)
# # for num in range(100):
# # print(num)
# # # for num in range(0, 101, 5):
# # # print(num)
# # guess = ""
# # while guess != "a":
# # guess = input("Guess a letter:")
# # counter = 5
# # while counter <= 5:
# name = input("What is your name?")
# hobby = input ("Do you have a favourite hobby?")
# print(f"This is {name}, likes {hobby}.")
# age = input (f"Hi {name}, how old are you? ")
# # years_until_100 = int (age)
# # print(f"Wow, {name}! You'll be 100 in {years_until_100} years!")
# number1 = input("enter a number")
# number2 = input("enter another number")
# total1 = int(number1) + int(number2)
# print(f"these two numbers add up to = {total1}")
# number1 = input ("enter a number")
# number2 = input("enter another number")
# total1 = int(number1) * int(number2)
# print(f"these two numbers multiplied add up to = {total1}")
# dist_1 = input ("How many kilometres did you run")
# metres = int (dist_1) * (1000)
# centrimetres = (dist_1) * (100000)
# print(f"Wow - did you know that {dist_1} * {metres} = metres or {dist_1} * {centrimetres}!!!")
name = input("What is your name?")
height = input("How tall are you (cm)?")
print(f"{name} is {height} tall!") | false |
c16abb148afecc330405f48f4d3927cf4d080983 | Carter-Co/she_codes_python | /databases/books.py | 846 | 4.125 | 4 |
#Relational Database - tables and rows
#SQL language to interat with databases
#Every row gets its own ID
import sqlite3
connection = sqlite3.connect("books.db")
cursor = connection.cursor()
#below would be fields / headers
cursor.execute("""
CREATE TABLE IF NOT EXISTS book (
id INTEGER PRIMARY KEY,
title TEXT,
pages INTEGER,
current_page INTEGER
)
""")
#below are the rows in the spreadsheet
# cursor.execute("""
# INSERT INTO book VALUES (
# 0, 'A Great Book', 213, 27
# )
# """)
# cursor.execute("""
# INSERT INTO book VALUES (
# 1, 'Another Great Book', 222, 33
# )
# """)
connection.commit()
rows = cursor.execute("""
SELECT title, pages, current_page FROM book
""")
for row in rows:
print(row)
connection.close()
#schema - blueprint
| true |
c5177b0fd0e8fc2a46297fa359b9b91fe355f83f | Carter-Co/she_codes_python | /conditionals/conditionals_playground.py | 1,111 | 4.1875 | 4 | #boolean
is_raining = False
is_cold = True
# print(type(is_raining))
# print(type(is_cold))
# print(is_raining)
# print(not is_raining)
# print(is_raining and is_cold)
# print(is_raining)
# print(not is_raining)
# print(is_raining and is_cold)
# print(is_raining and not is_cold)
# print(is_raining or not is_cold)
# print(not is_raining and not is_cold)
temperature = 16
wind_chill = 3
print(temperature < 18)
# print(wind_chill > 4)
# print(temperature - wind_chill < 16)
# name = "Abby"
# print(name =="Abby")
# print(name!= "Hayley")
## if statements
# if
if is_raining:
print("Take an umbrella.")
else:
print("Do not take an umbrella")
# if, elif, else
if temperature - wind_chill < 16:
print("Take a jumper.")
elif temperature - wind_chill > 30:
print("Yuck, it's hot today, stay home.")
else:
print("Wow, what a lovely day!")
#nested if statements
if temperature- wind_chill < 16 and is_raining:
print("Just stay home.")
else:
if is_raining:
print("You'll need an umbrella today.")
if temperature - wind_chill < 16:
print("you'll need a jumper today.")
| true |
386707d21dffe754c288d9572b54d038fb0ee597 | WuQianyong/Spider_demo | /algorithm_demo/mountanin_h.py | 638 | 4.25 | 4 | #!/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @Name : mountanin_h
# @Author : qianyong
# @Time : 2017-02-06 9:25
import sys
import math
# The while loop represents the game.
# Each iteration represents a turn of the game
# where you are given inputs (the heights of the mountains)
# and where you have to print an output (the index of the mountain to fire on)
# The inputs you are given are automatically updated according to your last actions.
import random
# game loop
for i in range(8):
# mountain_h = int(input()) # represents the height of one mountain.
mountain_h = random.randint(0,9)
print(mountain_h) | true |
461edcd59169810bec0e42a163fd9fc6984ee4a5 | jbailey430/The_Tech_Academy_Basic_Python_Projects | /test_database.py | 1,152 | 4.125 | 4 |
import sqlite3
connection = sqlite3.connect("test_database.db")
c = connection.cursor()
c.execute("INSERT INTO People VALUES('Ron', 'Obvious', 42)")
connection.commit()
connection.close()
with sqlite3.connect("test_database.db") as connection:
c = connection.cursor()
c.executescript("""DROP TABLE IF EXISTS People;
CREATE TABLE People(FirstName TEXT, LastName TEXT, Age INT);
INSERT INTO People VALUES('Ron', 'Obvious', '42');
""")
peopleValues = (('Luigi', 'Vercotti', 43 ), ('Arthur', 'Belling', 28))
c.executemany("INSERT INTO People VALUES(?, ?, ?)", peopleValues)
# get personal data from user
firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")
age = int(input("Enter your age: "))
personData = (firstName, lastName, age)
# execute insert statement for supplied person data
with sqlite3.connect('test_database.db') as connection:
c = connection.cursor()
line = ("INSERT INTO People VALUES (?, ?, ?)", personData)
c.execute("UPDATE People SET Age=? WHERE FirstName=? AND LastName=?",
(45, 'Luigi', 'Vercotti'))
| true |
56658a479cc3eac8d4848915243b03eec72cda72 | cmdellinger/ProjectEuler | /Problem 23 - Non-abundant sums/problem 23-python3.py | 2,035 | 4.1875 | 4 | # -*- coding: UTF-8 -*-
"""
ProjectEuler Problem 23: Non-abundant sums
Written by cmdellinger
A perfect number is a number for which the sum of its proper divisors is exactly
equal to the number. For example, the sum of the proper divisors of 28 would be
1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n
and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
number that can be written as the sum of two abundant numbers is 24. By
mathematical analysis, it can be shown that all integers greater than 28123 can
be written as the sum of two abundant numbers. However, this upper limit cannot
be reduced any further by analysis even though it is known that the greatest
number that cannot be expressed as the sum of two abundant numbers is less than
this limit.
Find the sum of all the positive integers which cannot be written as the sum of
two abundant numbers.
"""
## ------
## solution
## ------
import time as t
def divisors(number):
''' returns the divisors (factors - self) for the input number'''
factors = [1]
for integer in range(2, int(number**0.5) + 1):
if number % integer == 0:
factors.extend([integer, int(number/integer)])
return set(factors)
def is_abundant(number):
''' returns whether the number passed is abundant '''
if number < 12:
return False
return sum(divisors(number)) > number
limit = 28123
abundant_numbers = set(number for number in range(12,limit+1) if is_abundant(number))
def is_abundant_sum(i):
''' returns whether the number passed is the sum of abundant numbers '''
return any(i-a in abundant_numbers for a in abundant_numbers)
sum_of_non_abundant_sums = sum(number for number in range(1,limit+1) if not is_abundant_sum(number))
print('sum of valid positive integers:', sum_of_non_abundant_sums)
# print runtime of script
print("script runtime:", t.clock())
| true |
68a9a16db25f83f2085a54bf7a3190b50849d362 | mishrabhi/Python-Learning | /calc.py | 277 | 4.4375 | 4 | #We can use python as a calculator using print function:
#you can use these some of the operators:
# addition=> +
#substraction => -
#multiply => *
#float division => /
#Integer division => //
#Module(it gives remainder) => %
#exponent => **
print(2+3)
print(2+3*5)
print(2**3) | true |
740791e24aeb483c8de25832c5737dbc88ef777f | mishrabhi/Python-Learning | /string_method.py | 1,396 | 4.625 | 5 | #String Methods:
name = "AbhISHeK MIsHra"
# 1.len() function => It counts the character in string.It includes spaces too.
print(len("Abhishek")) #//8
print(len(name)) #//15 (with space)
print(len("AbhishekMishra")) #//14 (Without space)
# 2.lower() method => It converts all characters into lower cases.
print(name.lower()) #// abhishek mishra
lower = name.lower()
print(lower) #// abhishek mishra
# 3.upper() method => It converts all characters into upper cases.
print(name.upper()) #// ABHISHEK MISHRA
# 4.title() method => It converts only first letter of string in upper case.
print(name.title()) #//Abhishek Mishra
# 5.count() method => It counts a particular character in a string.
print(name.count("H")) #//2
#6.strip() method => It removes spaces from left or right in the string.
# lstrip() => to remove spaces from left side.
# rstrip() => to remove spaces from right side.
place = " Prayagraj "
dots = "................"
print(place + dots) #// Prayagraj .............
print(place.lstrip() + dots) #//Prayagraj ............
print(place.rstrip() + dots) #// Prayagraj...........
print(place.strip() + dots) #//Prayagraj...........
# 7. replace() method: It is used for replacements.
#syntax => string.replace("old content" , "new content"
string = "Capital of India is Delhi."
print(string.replace(" " , "_")) #//Capital_of_India_is_Delhi. | true |
bc2e151f43088a16e74f43fa5f5c46ddf7e0ce78 | redx14/LeftOrRightArrow | /LeftorRightArrow.py | 1,420 | 4.15625 | 4 | #Andrey Ilkiv midterm exam question 2
direction = input("Please enter a direction ( l / r ): ")
cols = int(input("Please enter an integer (>=0): "))
while(direction != "l" and direction != "r"):
print("Invalid Entry! Try Again!")
direction = input("Please enter a direction ( l / r ): ")
while(cols < 0):
print("Invalid Entry! Try Again!")
cols = int(input("Please enter an integer (>=0): "))
cols = cols - 1
if cols != 0:
if direction == "r" :
#upper
for i in range(0 , cols):
for j in range(0 , i):
print(" ", end="")
for k in range(1 , 2):
print("*" , end="")
print()
#lower
for i in range(0 , cols + 1):
for j in range(0 , cols - i):
print(" " , end="")
for k in range(1 , 2):
print("*" , end="")
print()
if direction == "l" :
#lower
for i in range(0 , cols + 1):
for j in range(0 , cols - i):
print(" " , end="")
for k in range(1 , 2):
print("*" , end="")
print()
#upper
for i in range(1 , cols+1):
for j in range(0 , i):
print(" ", end="")
for k in range(1 , 2):
print("*" , end="")
print()
| false |
3d74070dedd234df53c0af78c0ac4eee585ffa64 | siddhantmahajani/Basic-python-concepts | /10. Data-Structures-Set.py | 347 | 4.1875 | 4 | # Set
# Set contains unique non-duplicate elements
_set = {1, 2, 2, 3, 4, 5, 6, 7, 8, 9}
print(_set)
# _set.add(10) : used to add an element in the set
# _set.remove(2) : used to remove an element in the set
# _set.pop() : will remove the first element from the set
# print(_set.pop()) : will print the first element that is removed from the set
| true |
d0d12e833764e83ea94ae640578d5635afe75d31 | dcurry09/machine_learning_intro | /linear_regression/lin_regession.py | 1,239 | 4.28125 | 4 | # David Curry
# Gradient Descent using SciKit - Machine Learning
import pylab as pl
import numpy as np
from sklearn import datasets, linear_model
print '---> Importing the Dataset'
data = np.loadtxt('mlclass-ex1-005/mlclass-ex1/ex1data1.txt', delimiter=',')
x = data[:, 0]
y = data[:, 1]
# Create linear regression object
regr = linear_model.LinearRegression()
# Data must be in numpy matrix form: [num samples, num features]
xx = x.reshape((x.shape[0],-1))
yy = y.reshape((y.shape[0],-1))
print '---> Performing Gradient Descent. Training on Dataset'
# Train the model using the training sets
regr.fit(xx, yy)
print ' Coefficent = ', regr.coef_
print ' Intercept = ', regr.intercept_
theta = [regr.intercept_, regr.coef_]
#Add a column of ones to X (interception data)
it = np.ones(shape=(x.size, 2))
it[:, 1] = x
# the final fit answer is a dot product between theta matrix and x matrix
fit = it.dot(theta)
#predicting some values
print 'If the population is 12,000, the house value(int thousands) = ', regr.predict(12)
print '---> Plotting the Dataset'
pl.scatter(x, y, marker='o', c='b')
pl.plot(x, fit)
pl.title('Profits distribution')
pl.xlabel('Population of City in 10,000s')
pl.ylabel('Profit in $10,000s')
pl.show()
| true |
dc8180f9355697e77128740f4da27650be554591 | FokhrulAlam/Programming-with-Python | /Tutorial/Exercises/Miscellaneous/Fibonacci_series.py | 431 | 4.21875 | 4 | def fibonacci(n):
first_number=0
second_number=1
previous_number=0
current_number=1
if n==1:
print(first_number,end='')
else:
print(first_number,second_number,end='')
for i in range(n-2):
next_number=current_number+previous_number
print('',next_number,end='')
previous_number=current_number
current_number=next_number
fibonacci(12) | false |
4a95f4e68ed70d175839aff6818246479e676b7f | FokhrulAlam/Programming-with-Python | /Tutorial/Exercises/Miscellaneous/array_2.py | 334 | 4.125 | 4 | from array import *
arr=array('i',[])
n=int(input("Enter the length of the array:"))
for i in range(n):
x=int(input("Enter the value:"))
arr.append(x)
print(arr)
value=int(input("Enter a value to know its index: "))
for i in arr:
if value==arr[i]:
index=[i]
print("Index of value is ",index)
break | true |
f21ce2fb5a2b071358a911d9e7183597e260f50d | FokhrulAlam/Programming-with-Python | /Starting Out with Python By Tony Gaddis/6.8. Random Number File Reader.py | 1,381 | 4.46875 | 4 | #This exercise assumes you have completed Programming Exercise 7, Random Number File Writer. Write another program
# that reads the random numbers from the file, display the numbers, and then display the following data:•
# The total of the numbers•
# The number of random numbers read from the file
def display_numbers(file_tobe_read):
try:
random_number_file=open(file_tobe_read,'r')
except Exception as error:
print("Warning: Problem with opening the file mentioned: ",error)
else:
lines=random_number_file.readline()
number_of_random_numbers=0
total_of_numbers=0
print("The random numbers are: ")
while lines != "":
new_line= lines.strip() #Stripping the line \n character
for numbers in map(int,new_line.split()): #separating the integers
print(numbers)
number_of_random_numbers+=1
total_of_numbers=total_of_numbers+numbers
lines=random_number_file.readline()
print("\nThe total of the numbers is ",total_of_numbers)
print("There are total",number_of_random_numbers,"random numbers in the file")
finally:
print("\nCongratulations! You successfully read the numbers.")
def main():
display_numbers("RandomNumbers.txt")
main() | true |
b7071f0ee77ada99eaeaad306da96d0f2e8dd8c6 | degutos/unuteis | /method.py | 283 | 4.28125 | 4 | # Methods
# Creating a list
mylist = [1,2,3]
print(mylist)
# appending new value to a list
mylist.append(4)
print(mylist)
mylist.append(5)
print(mylist)
# pop the last item in the list (delete)
mylist.pop()
print(mylist)
help(mylist.insert)
mylist.insert(1,5)
print(mylist)
| true |
c771b076b6f2d2e1af82170b9b110b81dc63819b | degutos/unuteis | /rock-paper-scisor.py | 1,703 | 4.5 | 4 | # This code is to learn Python by Andre Gonzaga
# This code is the simulator for Rock, Paper, Scissor
import random
def print_options():
print('Lets play this... ')
print('')
print(' Rock ')
print(' Paper ')
print(' Scissor ')
print('')
def ask_option():
user_option=input('Your option now is: ')
return user_option.lower()
def robot():
options=['rock','paper','scissor']
robot_option=random.choice(options)
print('The computer chooses {}' .format(robot_option))
return robot_option
def user_rock(user_option,robot_option):
if robot_option == 'paper':
print('The computer wins!')
else:
print('You win!!')
def user_paper(user_option,robot_option):
if robot_option == 'rock':
print('You win!!')
else:
print('The computer wins!')
def user_scissor(user_option,robot_option):
if robot_option == 'rock':
print('The computer wins!')
else:
print('You win!!')
def check_win(user_option,robot_option):
if user_option == robot_option:
print('The game draw')
else:
if user_option == 'rock':
user_rock(user_option,robot_option)
elif user_option == 'paper':
user_paper(user_option,robot_option)
elif user_option == 'scissor':
user_scissor(user_option,robot_option)
else:
print('User choose wrong option')
def check_continue():
import os
play=input('Do you wish to play again: ')
os.system('clear')
return play
play = 'y'
while play != 'n':
print_options()
user_option=ask_option()
robot_option=robot()
check_win(user_option,robot_option)
play=check_continue()
| true |
634455d793227c382c8d6f92e223713e7de276f8 | kaushiks90/PythonPrograms | /PythonPrograms/BasicPrograms/Anagrams.py | 644 | 4.1875 | 4 | #Given 2 strings find whether the string is Anagram
#Example NAB and BAN
def ReverseString(originalString,n):
reversedString=""
for x in range(n,0,-1):
reversedString=reversedString+originalString[x-1]
return reversedString
def FindIsAnagram(string1,string2):
isAnagram=False
if(len(string1)!=len(string2)):
return isAnagram
else:
revstring1=ReverseString(string1,len(string1))
for x in range(0,len(revstring1)):
if(revstring1[x]!=string2[x]):
return isAnagram
isAnagram=True;
return isAnagram
print("IsAnagram?",FindIsAnagram("NAB","BAN")) | true |
08bd3014908d206cc2240699524006616ec99b3c | benhassenwael/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 750 | 4.28125 | 4 | #!/usr/bin/python3
""" Module implementing a single function append_after """
def append_after(filename="", search_string="", new_string=""):
""" Inserts a line of text to a file,
after each line containing a specific string
Args:
filename: a string representing the file name
search_string: string to insert in the line after
new_string: the text to be written in the file
"""
if filename:
with open(filename, "r", encoding="utf8") as f:
text = [line for line in f]
with open(filename, "w", encoding="utf8") as f:
for line in text:
if line.find(search_string) >= 0:
line = line + new_string
f.write(line)
| true |
02ea6e9060b713878723f8903bb65d13b445d0b4 | kitiarasr/LC-101 | /Chapter_1-5/Chapter2Hw.py | 549 | 4.40625 | 4 |
# !/usr/bin/env python
#Write a program that calculates the temperature based on how much the dial
#has been turned. You should prompt the user for a number of clicks-to-the-right
#(from the starting point of 40 degrees). Then you should print the current
#temperature.
# By how many clicks has the dial been turned?
#>>> -1
#The temperature is 89
baseTemp = 40
fullCycle = 50
clicks_str = input("By how many clicks has the dial been turned?")
clicks = int(clicks_str)
result = clicks % fullCycle + baseTemp
print("The temperature is ", result)
| true |
2d4a0ffc57e3bb6698e90efea0baa8b6c0383107 | pirate765/bridgelabzbootcamp | /day3/cos.py | 233 | 4.15625 | 4 | import math
x = float(input("Enter the angle in radians"))
x = x % (2 * math.pi)
a = -1
cosx = 1
for i in range(1,15):
cosx += ((a)*(pow(x,2*i))/math.factorial(2*i))
a *= -1
print("The value of cos is {}".format(round(cosx, 3))) | true |
f3186cd2b5b45f1095a93ac0d67a03c8c64f0257 | dblitz21/coding | /cubes.py | 245 | 4.15625 | 4 |
#Get the cube of the first 10 numbers
cubes = []
for value in range(1, 11):
cubes.append(value**3)
print(cubes)
#Get the cube of the first 10 numbers shorthand (list comprehension)
cubes2 = [value**3 for value in range(1, 11)]
print(cubes2)
| true |
65b044b7d31b1225b56d346adbfa189094698a13 | dblitz21/coding | /cars.py | 382 | 4.21875 | 4 | cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars)) #Temporarily sort
#reverse the list
print("\nHere is the reversed list:")
cars.reverse()
print(cars)
numberofcars = len(cars)
print("\nThere are " + str(numberofcars) + " cars in the list.")
#Sort the list
cars.sort()
print(cars)
| true |
090c223991c48e21272017687dae604afb7a7de7 | sanketkothiya/Learn-Python | /Ex-1.py | 201 | 4.21875 | 4 | #create dictionary and take user input
dict1 = {"true":"false" , "right":"left" , "upper":"lower" , "up":"down"}
print(dict1)
print("Select your word in Dictionary")
word = input()
print(dict1[word]) | true |
6636b72b7e2279b3efa4d87359e60441735a93e4 | niupuyue/python_demo01 | /06_string.py | 2,377 | 4.40625 | 4 | # Python的字符串
'''
字符串是 Python 中最常用的数据类型。我们可以使用引号( ' 或 " )来创建字符串。
创建字符串很简单,只要为变量分配一个值即可
'''
# Python中访问字符串的值
var1 = "abcdefghjiklmn"
print("var1[2] = " + var1[2])
print("var1[1:3] = " + var1[1:3])
del var1
# Python中更新字符串
var1 = "hello world!"
print("更新后的内容:" + var1[:6] + "Python!")
del var1
# Python的转义字符
'''
\ 在行尾 换行符
\\ 反斜杠符号
\' 单引号
\" 双引号
\a 响铃
\b backspace按键
\000 空
\n 换行
\r 回车
\v 纵向制表符
\t 横向制表符
\f 换页
如果我们想要某一个字符串不要进行转移,则可以使用r,如下
'''
var1 = "abcdefg\n"
var2 = r"abcdefg\n"
print(var1)
print(var2)
del var1, var2
# Python字符串格式化
'''
Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
'''
var1 = "ab%sdefghijklmn"
print(var1 % (" hahah "))
var2 = "ab%defghijklmn"
print(var2 % (100))
del var1, var2
'''
1. %c 格式化字符串以及ASCII码
2. %s 格式化字符串
3. %d 格式化整数
4. %u 格式化无符号整数
5. %o 格式化无符号八进制数
6. %x 格式化无符号十六进制数
7. %f 格式化浮点数,可指定符号后精确度
8. %e 用科学计数法格式化浮点数
9. %p 用十六进制数格式化地址
'''
# Python的字符串内建函数
'''
1. capitalize() 将字符串首字母变成大写
2. center(width, fillchar) 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
3. isdigit() 是否只包含数字
4. islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
5. isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False
6. len() 返回字符串的长度
7. lstrip() 截掉字符串左边的空格或指定字符。
8. max() 返回字符串 str 中最大的字母。
9. replace(old, new [, max]) 把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。
10. rstrip() 删除字符串字符串末尾的空格.
'''
| false |
00c305247f0aff89cd28dc16c2f904c5630b6cca | joelranjithjebanesan7/Python-Programs | /sessionTwo/lab3.py | 218 | 4.15625 | 4 | def is_vowel(letter) :
if letter in('a','e','i','o','u','A','E','I','O','U'):
return True
else:
return False
letter=input("enter the alphabet:")
print(is_vowel(letter)) | false |
14be6120c2da64ca210f584de5986aff9d081c34 | mohan78/ProjectEuler | /problem4.py | 761 | 4.28125 | 4 | # Largest 3 digit Palindrome number
"""
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.
"""
first_num = 999
second_num = 999
palindrome = []
def isPalindrome(num):
num = str(num)
if num == num[::-1]:
return True
else:
return False
for i in range(first_num,0,-1):
for j in range(second_num,0,-1):
num = i * j
if isPalindrome(num):
palindrome.append((num,i,j))
largest_palindrome = max([i for i in palindrome])
print("The Largest palidrome made by product of 3 digit numbers {} and {} is {}".format(largest_palindrome[1],largest_palindrome[2],largest_palindrome[0]))
| true |
d6219f91cba1e92c615d1550f31b1fa3f4cb6a8d | Mingda-Rui/python-learning | /head_first_python/ch02/panic.py | 647 | 4.15625 | 4 | phrase = "Don't panic!"
# we turn the String into a list
plist = list(phrase)
print(phrase)
print(plist)
for i in range(4):
plist.pop()
plist.pop(0)
plist.remove("'")
# Swap the two objects at the end of the list by
# first popping each object from the list, then using
# the popped objects to extend the list. This is a
# line of code that you'll need to think about for a
# little bit. Key point: the pops occur *first* (in
# the order shown), then the extend happens.
plist.extend([plist.pop(), plist.pop()])
plist.extend([plist.pop(), plist.pop()])
plist.insert(2, plist.pop(3))
new_phrase = ''.join(plist)
print(plist)
print(new_phrase) | true |
948895f015ac17e33b089407a8d64ac3bb6370fa | MilesYeah/ASimpleSummary-Python | /DataStructure,数据结构/list.列表/codes/反向迭代序列.1.py | 320 | 4.34375 | 4 |
#如果是一个list,最快的方法使用reverse
tempList = [1,2,3,4]
tempList.reverse()
for x in tempList:
print(x)
templist = [1,2,3,4]
for i in templist[::-1]:
print(templist[i])
#如果不是list,需要手动重排
templist = (1,2,3,4)
for i in range(len(templist)-1,-1,-1):
print(templist[i])
| false |
8ecf4bcf2ee268a9410b809718702bf732197a3b | VishnuSai/Python-games-coursera | /Guess the number.py | 2,227 | 4.1875 | 4 | # "Guess the number" mini-project
# modules required
import random
import simplegui
# initialize global variables
secret_number = 0
guesses = 0
# helper function to start and restart the game
# decrements the total guesses left
# prints the guesses
def guess_left():
global guesses
guesses = guesses - 1
print "Number of remaining guesses is ", guesses
# start new game
def new_game():
range100()
return
# event handler for button
# button that changes range to range [0,100) and restarts
def range100():
global secret_number
secret_number = random.randrange(0,100)
global guesses
guesses = 7
print
print "New Game. Range is from 0 to 100"
print "Number of remaining guesses is 7"
print
return
# event handler for button
# button that changes range to range [0,1000) and restarts
def range1000():
global secret_number
secret_number = random.randrange(0,1000)
global guesses
guesses = 10
print
print "New Game. Range is from 0 to 1000"
print "Number of remaining guesses is 10"
print
return
# event handler for input field
def input_guess(guess):
# main game logic
guess_number = int(guess)
print "Guess was ",guess_number
guess_left()
if(guesses > 0):
if(guess_number < secret_number):
print "Higher!"
print
elif(guess_number > secret_number):
print "Lower!"
print
elif(guess_number == secret_number):
print "Correct!"
print
new_game()
else:
if(guess_number == secret_number):
print "Correct!"
print
new_game()
else:
print "You ran out of guesses. The number was ",secret_number
new_game()
# create frame
frame = simplegui.create_frame("Guess_the_number", 200, 200)
# register event handlers for control elements
button1 = frame.add_button("Range in 0-100", range100, 200 )
button1 = frame.add_button("Range in 0-1000", range1000, 200 )
inp = frame.add_input('Guess number', input_guess, 50)
# call new_game and start frame
frame.start()
new_game()
| true |
3ad967c8b9676e0168e17561a18112bc07945120 | MuhammadTayyab1/learning-Python | /Basic concepts/3-conversions.py | 425 | 4.25 | 4 | # In order to convert string into int, float or convert int, float we use this
# Convert string into int
num= int(input('enter number'))
print('number in int = ',num)
# Convert string into float
num1= float(input('enter number'))
print('number in float = ',num1)
# Convert int into string
a = str(92)
print('Number in string = ',a)
# Number in string means we cannot applay mathematical operations on it
| true |
f7bf0a1c0880bad489e87beb767688c0e3995556 | RushikeshSP/Yay-Python-Basics | /Assignment1/A1_problem2.py | 375 | 4.34375 | 4 | # Wrire a python program to convert a tuple of string values to a tuple of integer values.
tup = ("1","22","333","4444","55555") #Taking a constant string input.
Result = []
print("Input String Tuple : ",tup)
# for i in tup:
# Result.append(int(i))
Result = [int(i) for i in tup]
print("Output Integer Tuple : ",tuple(Result))
| true |
d8be6440090216e4d9a61041f99dd0fc67ccf9f6 | pitordoan/devops | /prime.py | 417 | 4.125 | 4 | #!/usr/bin/python
import math
def is_prime(number):
if number > 1:
if number == 2:
return True
if number % 2 == 0:
return False
for current in range(3, int(math.sqrt(number) + 1), 2):
if number % current == 0:
return False
return True
return False
for i in range(10):
print 'Is {0} a prime: {1}'.format(i, is_prime(i)) | false |
9c8c85401715f863e64320396c365e9902bd0e7d | pitordoan/devops | /reverse-string.py | 335 | 4.4375 | 4 | #!/usr/bin/python
#Different ways to print a string in reverse order of its characters
s = 'abc'
print s[::-1]
print ''.join(reversed(s))
print s[slice(None, None, -1)]
def reverse(string):
n = len(string)
new_string = ''
for i in range(n-1, -1, -1):
new_string += string[i]
print new_string
reverse(s) | true |
f97c31786938fce30c11c760e4dc16cf5eb9f860 | AnkurPokhrel8/BankManagementSystem | /automate1.py | 1,680 | 4.21875 | 4 | import shelve
class Bank:
def __init__(self):
print("Welcome to the BANK")
self.account_holder = []
db = shelve.open('database')
for i in list(db.keys()):
self.account_holder.append(i)
db.close()
def createAccount(self, name, address, balance):
if name not in self.account_holder:
self.account_holder.append(name)
db = shelve.open('database')
db[name] = [address, balance]
db.close()
print("Your account is created!")
else:
print("You already have an account!")
def showAccount(self, name):
if name in self.account_holder:
db = shelve.open('database')
print(list(db[name]))
db.close()
else:
print("You need to create an account first!")
def printdatabase(self):
db = shelve.open('database')
print(list(db.keys()))
print(list(db.values()))
db.close()
bank = Bank()
while True:
print("Enter 1 for making account.")
print("Enter 2 for showing account.")
print("Enter 3 for printing database.")
print("Enter 'quit' for exiting the program.")
print()
action = input('What do you want to do? ')
print()
if action == 'quit':
print("Exiting")
print()
break
elif action == '1':
print("Enter your personal details.")
name = input("Enter your name: ")
add = input("Enter your address: ")
balance = int(input("Enter you balance: "))
bank.createAccount(name, add, balance)
print()
print()
elif action == '2':
name = input("Enter your name: ")
bank.showAccount(name)
print()
print()
elif action == '3':
bank.printdatabase()
print()
print()
else:
print("Invalid input, try again!")
print()
print()
| true |
cb9fb122ebf11fc9e0f0a7197f0a2b43a68ded8b | sharevong/algothrim | /remove_elem.py | 854 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
问题描述:原位删除数组中的指定数值,返回移除数值后的数组长度
https://leetcode-cn.com/problems/remove-element/
eg:
输入 nums=[3,2,2,3] elem=3 输出nums=[2,2,2,3] len=2
输入 nums=[0,1,2,2,3,0,4,2] elem=2 输入nums=[0,1,3,0,4,0,4,2] len=5
"""
def remove_elem(nums, elem):
"""
算法思路:使用快慢双指针,快指针找到非移除元素时,赋值给慢指针,并移动慢指针
"""
if len(nums) == 0:
return 0
slow = 0
fast = 0
while fast < len(nums):
if nums[fast] != elem:
nums[slow] = nums[fast]
slow = slow + 1
fast = fast + 1
# print(nums)
return slow
if __name__ == '__main__':
print(remove_elem([3,2,2,3], 3))
print(remove_elem([0,1,2,2,3,0,4,2], 2))
| false |
3fa647b0853cad6d57ffc56cad4d76a49fc7e163 | Emilyevee/COM404 | /1-basics/3-decisions/6-counter/bot.py | 449 | 4.125 | 4 | number1 = int(input ("please enter the first number"))
number2 = int(input ("please enter the second number"))
number3 = int(input ("please enter the third number"))
evenCount = 0
oddCount = 0
if number1 % 2 == 0:
evenCount+=1
else:
oddCount+=1
if number2 % 2 == 0:
evenCount+=1
else:
oddCount+=1
if number3 % 2 == 0:
evenCount+=1
else:
oddCount+=1
print ("there were "+ str(evenCount)+" even and"+ str(oddCount)+ " odd")
| false |
d2bb378511bc70359cca142fbc38cb727350ede1 | jonathancox1/Python102 | /day_of_the_week.py | 580 | 4.5 | 4 | #prompt user for a number 0-6 to be converted to a day of the week
day = int(input('Enter a day as a number (0-6) and Ill tell you the day of the week '))
#create a default prompt
prompt = 'Your chosen day is:'
#determin the numerical value of the day from the user input
if day == 0:
print(f'{prompt} Sunday')
elif day > 5:
print(f'{prompt} Saturday')
elif day > 4:
print(f'{prompt} Friday')
elif day > 3:
print(f'{prompt} Thursday')
elif day > 2:
print(f'{prompt} Wednesday')
elif day > 1:
print(f'{prompt} Tuesday')
else:
print(f'{prompt} Monday') | true |
861f3669052b8b1d98e6d9c801574afa5af405eb | Qinpeng96/leetcode | /173. 二叉搜索树迭代器.py | 2,092 | 4.4375 | 4 | """
173. 二叉搜索树迭代器
实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false
提示:
next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。
你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-search-tree-iterator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):#初始化,定义每次循环的序号,输出列表,并且执行中序遍历
self.index = -1
self.res = []
self.__inorder(root)
# self.len = len(self.res)
def __inorder(self, root):#定义中序遍历,输出res在初始化的时候定义过了
if not root: return
self.__inorder(root.left)
self.res.append(root.val)False
self.__inorder(root.right)
def next(self) -> int:#调用next函数,返回对应的res列表值
"""
@return the next smallest number
"""
self.index += 1
return self.res[self.index]
def hasNext(self) -> bool:#如果此次index超过res的长度,返回False
"""
@return whether we have a next smallest number
"""
return self.index + 1 < len(self.res)
| false |
da82bde56fd37bfa43f5272463df6757ecff3014 | dgallegos01/Python-Course | /Functions/Reusable_Function.py | 743 | 4.28125 | 4 | # we are gonna convert our Emoji program into a function
# Here is the original code:
"""
message = input(">")
words = message.split(' ')
print(words)
message = input(">")
words = message.split(' ')
emojis = {
":)": "🙂",
":(": "🙁"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
print(output)
"""
# Now here is the code as the function:
def emoji_converter(meeage):
words = message.split(' ')
print(words)
message = input(">")
words = message.split(' ')
emojis = {
":)": "🙂",
":(": "🙁"
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
message = input(">")
print(emoji_converter(message)) | true |
83b06381984e6c202d38bf89077a713f4ebdf91e | dgallegos01/Python-Course | /Classes/class.py | 1,203 | 4.46875 | 4 | # we will learn how to use classes in python
# classes are used to define new types. they are very important not just to python but to programming in general
# simple types are the methods we have used so far
"""
example:
Numbers
Strings
Booleans
Lists
Dictionaries
"""
# classes are used to make complex types like defining objects
# we use them to model real concepts
# it is also similar to making a function
# example:
class Point: # unlike functions or variable, we capitalize the name of our class. we don't use underscores to separate words either, only capitalize every word
def move(self): # this is a methed not a function
print("move")
def draw(self):
print("draw")
# now we can make an instance of an object
# *an object is an instance of a class
point1 = Point() # we set the class to the variable or object
point1.draw() # here we are able to call the class via the '.' method and grab the method within the class
# when we run the program, the output should be "draw"
point1.x = 10 # this is an attribute
print(point1.x)
point2 = Point() # this is a new object that is set to the class
point2.x = 1 # this creates a new attribute to that object
print(point2.x) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.