blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b433ed328d118c05a67b42d8085391af87955ba7 | isaolmez/core_python_programming | /com/isa/python/chapter7/SetOperators.py | 899 | 4.21875 | 4 | ## 1. Standard Type Operators
set1 = set([1, 2, 3, 3]) # Removes duplicates
print set1
set2 = set("isa123")
print set2
print 1 in set1
print "i" in set2
print "---- Equality test"
set1Copy = set(set1)
print "set1 == set1Copy", set1 == set1Copy
print "set1 < set1Copy", set1 < set1Copy # Strictly must be smaller. Equal sets return False with < (smaller than)
print "set1 <= set1Copy", set1 <= set1Copy # Less Strict. Equal sets return True with <=
set3 = set([1, 2, 3, 4, 5, 6])
print set1 < set3 # All of the == < > could return False. Interesting
print set1 == set3
## Set Type Operators
# union, instersection, difference, symmetric difference: | & - ^
# No + operator
print "---- Set type operators"
set1 = set([1, 2, 3, 4])
set2 = set([4, 5, 6])
print set1 | set2 # union
print set1 & set2 # intersection
print set1 - set2 # difference
print set1 ^ set2 # symmetric difference, XOR
| true |
fade8fcd236ccbf30038d4ca49cd11dd18dae898 | isaolmez/core_python_programming | /com/isa/python/chapter6/ShallowCopy.py | 1,228 | 4.28125 | 4 | ## SHALLOW COPY
person = ["name", ["savings", 100.00]]
print id(person), id(person[:])
print "---- Slice copy"
husband = person[:]
print id(person), id(person[:])
print id(person), id(husband)
# They both refer to the same string "name" as their first element and so on.
print "id() of names:", id(person[0]), id(husband[0])
print "id() of savings:", id(person[1]), id(husband[1])
husband[0] = "isa"
print person, "\n", husband
print "---- Factory function copy"
wife = list(person)
wife[0] = "hilal" # Assign new object, so one change cannot effect other. No magic
print id(person), id(person[:])
print id(person), id(wife)
print "---- All three\n", id(person), id(husband), id(wife)
print person, "\n", husband, "\n", wife
## Notes till now:
# We have shallow copies. Only references are copied for the inner objects, not the object itself.
# The object copied itself is new, but the contents are not.
# Lets see what this means.
husband[1][1] = 50.00 # Assign new value to the state of aliased object. This is state modification for aliased object, not a new object assignment.
print person, "\n", husband, "\n", wife # This line has changed inner list in all 3 objects. All are mutated.
| true |
0c2c06e78b487259157082a78e21bdcf951a457b | Supython/SuVi | /+or-or0.py | 287 | 4.5 | 4 | #To Check whether the given number is positive or negative
S=int(input("Enter a number: "))
if S>0:
print("Given number {0} is positive number".format(S))
elif S<0:
print("Given number {0} is negative number".format(S))
else:
print("Given number {0} s Zero".format(S)) | true |
c139098a2859b272f95868d767b9c108f04d7f8f | Utkarsh811/workclass | /ASSIGNMENT_9/9.py | 1,421 | 4.375 | 4 | #for matrix addition matrix should have equal dimensions , means equal number of rows and columns
row=int(input('Enter the number of rows of matrix-1'))
cols=int(input('Enter the number of cols of matrix-1'))
row1=int(input('Enter the number of rows of matrix-2'))
cols1=int(input('Enter the number of columns of matrix-2'))
if(row==row1 and cols==cols1):
matrix_1=[]
matrix_2=[]
matrix_3=[]
for i in range(row):
a=[]
for j in range(cols):
a.append(int(input(f'Enter the element [{i},{j}]-')))
matrix_1.append(a)
print(matrix_1)
for i in range(row):
for j in range(cols):
print(matrix_1[i][j],end=' ')
print('\n')
#creating matrix -2
for i in range(row1):
a=[]
for j in range(cols1):
a.append(int(input(f'Enter the element [{i},{j}]-')))
matrix_2.append(a)
print(matrix_2)
for i in range(row1):
for j in range(cols1):
print(matrix_2[i][j],end=' ')
print('\n')
#adding
for i in range(row1):
a=[]
for j in range(cols1):
a.append(matrix_1[i][j]+matrix_2[i][j])
matrix_3.append(a)
print(matrix_3)
for i in range(row1):
for j in range(cols1):
print(matrix_3[i][j],end=' ')
print('\n')
| false |
528e345293daabc200c244daa47bbd0ed62ce033 | Izavella-Valencia/programacion | /Talleres/Taller2.py | 1,296 | 4.375 | 4 | #------preguntas------
MENSAJE_INTRODUCCION = "procederemos a hacer operaciones con numeros escogidos por ti"
NUMERO_A = "escoja un numero entero del 1 al 20 :"
NUMERO_B = "escoja un numero entero del 1 al 20 :"
#-------codigos--------
print ("#"*15, "insertar numeros", 15*"#")
print (MENSAJE_INTRODUCCION)
numeroA = int(input(NUMERO_A))
numeroB = int(input(NUMERO_B))
#----comparaciones entre los números------
print ("#"*15, "comparacion entre los numeros", 15*"#")
isMayorNumero = numeroA > numeroB
print (isMayorNumero)
isMenorNumero = numeroA < numeroB
print (isMenorNumero)
isDiferenteNumero = numeroA != numeroB
print (isDiferenteNumero)
isIgualNumero = numeroA == numeroB
print (isIgualNumero)
#------operaciones entre números-----
print ("#"*15, "operaciones entre los numeros", 15*"#")
sumar = numeroA + numeroB
print (f"la suma entre los dos numeros dio {sumar} exitosamente")
restar = numeroA - numeroB
print (f"la resta entre los dos numeros dio {restar} exitosamente")
multiplicar = numeroA * numeroB
print (f"la multiplicacion entre los dos numeros dio {multiplicar} exitosamente")
dividir = numeroA / numeroB
print (f"la division entre estos numeros dio {dividir} exitosamente")
exponente = numeroA**numeroB
print (f"la potenciacion tiene un resultado de {exponente}")
| false |
7c52c9f202315ffc5d90cb6b81118d92051240d1 | Izavella-Valencia/programacion | /Clases/Listas.py | 1,763 | 4.1875 | 4 | nombres = []
print (type(nombres))
print (nombres)
nombres = ['Santiago', 'Samuel', 'Alejandra', 'Elsa']
print (nombres)
print (nombres[2])
nombres.append ('Mauricio')
print (nombres)
print (nombres [2])
edades = [18,19,20,17]
estaturas = [1.62, 1.80, 1.67, 1.98]
#el ultimo numero
print (edades [-2])
print (edades [0:2])
print (edades[:3])
print (edades [2:])
print (edades [:])
#para ordenarlas
edades.sort () #menor-mayor
print (edades)
edades.sort (reverse=True) #mayor-menor
print (edades)
#mayor y menor de la lista
mayor = max (edades)
print = (mayor)
menor = min (edades)
print = menor
#numero de elemtos
largosListasEdades = len (edades)
print (largoListasEdades)
#Suma
sumaEdades = sum (edades)
print (sumaEdades)
#promedio
promedioEdades = sumaEdades/largosListasEdades
print (promedioEdades)
#eliminar un elemento de la lista
edades.pop(2) #solo es poner la posicion de la lista
print (edades)
#ciclo for y las listas
largosListasEdades = len (edades)
for indice in range (largosListasEdades):
print ('Estoy en la posicion',
indice, 'valgo',
edades [indice])
largoListaNombres = len (nombres)
for indice in range (largoListaNombres):
print (nombres [indice])
posicionesConValorPar = []
largoListaEdades = len (edades)
for posicion in range (largoListaEdades):
if (edades [posicion]%2 == 0):
posicionesConValorPar.append (posicion)
print (edades)
print (posicionesConValorPar)
#Solo cuando me interese mostrar la lista
for edad in edades:
print (edad)
for nombre in nombres:
print (nombre)
print (posicion)
posicion+=1
posicion = 0
posicionesPares = []
for edad in edades:
if (edad %2 ==0):
posicionesPares.appende (posicion)
posicion +=1
print (posicionesPares)
| false |
d4c1b4e64302f1f0a851ed7fa7061142b687320d | chisoftltd/PythonFilesOperations | /PythonWriteFile.py | 1,443 | 4.375 | 4 | # Write to an Existing File
import os
f = open("demofile2.txt", "a")
f.write("Now the file has more content! TXT files are useful for storing information in plain text with no special formatting beyond basic fonts and font styles.")
f.close()
myfile = open("Tutorial2.txt", "w")
myfile.write("Python Programming Tutorials \n")
myfile.write("Coding Challenge \n")
myfile.write("Java Programming Tutorial")
myfile.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content! The file is commonly used for recording notes, directions, and other similar documents that do not need to appear a certain way. If you are looking to create a document with more formatting capabilities, such as a report, newsletter, or resume, you should look to the .DOCX file, which is used by the popular Microsoft Word program.")
f.close()
#open and read the file after the appending:
f = open("demofile.txt", "r")
print(f.read())
# Create a New File
if os.path.exists("myfile5.txt") or os.path.exists("myfile4.txt"):
os.remove("myfile4.txt")
os.remove("myfile5.txt")
else:
print("The file does not exist")
f = open("myfile4.txt", "x")
f = open("myfile5.txt", "w")
# The mkdir() Method
os.mkdir("myfiles")
# The getcwd() Method()
os.getcwd()
# The chdir() Method
# os.chdir("C:/data")
# The rmdir() Method
os.rmdir("myfiles")
| true |
937fd7ed313414abdcf79356bd51f06a2571f0e2 | EvelynMC/intro-python | /intro-python/controlFlujo.py | 1,101 | 4.40625 | 4 | # ----IF Control de Flujo-----
# if 2 < 5:
# print('2 es menor que 5')
# a == b
# a < b
# a > b
# a != b
# a <= b
# a >= b
# if 2 == 2:
# print('2 es igual a 2')
# if 2 ==3:
# print('2 es igual a 3')
# if 2 > 5:
# print('2 es mayor que 5')
# if 5 > 2:
# print('5 es mayor a 2')
# if 2 != 2:
# print('2 es distinto a 2')
# if 3 !=2:
# print('3 es distinto a 2')
# if 3<=3:
# print('3 es menor o igual a 3')
if 2 > 5:
print('dos es menor a 5 en if')
elif 2 > 5:
print('2 es menor a 5 en elif')
else:
print('Yo me imprimo solo si todo lo anterior evalua en falso')
if 2 > 5:
print('dos es menor a 5 en if')
else:
print('Yo me imprimo solo si todo lo anterior evalua en falso 2')
#----- IF Ternarios ----
if 2 < 5: print('if de una linea')
print('cuando devuelve true') if 5 > 2 else print('cuando devuelve false')
#----- AND/OR ----
if 2 < 5 and 3 > 2:
print ('ambas devuelven true')
if 2 > 5 and 3 > 2:
print ('hay una falsa, esto no se mostrara')
if 1 < 0 or 1 > 0:
print('una de las dos condiciones devolvio true') | false |
10aa1cd421da8e9c821f15281f1b3bdca4fe32d4 | xs2pranjal/data_structures | /linear/linkedlist.py | 1,701 | 4.4375 | 4 | class LinkedList(object):
"""
This is an implementation of a LinkedList in python.
"""
def __init__(self):
self.head = None
def print_ll(self, node=None):
if not node:
node = self.head
print(node.value)
# Calling the print_ll recursively
if node.next:
self.print_ll(node.next)
else:
print('End of LinkedList')
def reverse(self):
"""
Consider a linked list of the below shape and size.
Value: | Head | | 10 | | 3 | | 4 | | 1 |
------- ----- ---- ---- ----
Addresses: | 121 | |234| |34| |12| |None|
We want to change this to;
Value: | Head | | 1 | | 4 | | 3 | | 10 |
------- ---- ---- ---- -----
Addresses: | 12 | |34| |234| |121| |None|
:return: None
"""
if self.head:
prev_address = None
node = self.head
while node:
proxy_node = node
node = node.next
proxy_node.next = prev_address
prev_address = proxy_node
self.head = prev_address
class Node(object):
"""
A Node in a LinkedList that points to another node and has a value
"""
def __init__(self, value):
self.value = value
self.next = None
if __name__ == "__main__":
a = Node(1)
b = Node(2)
c = Node(3)
b.next = c
a.next = b
ll = LinkedList()
ll.head = a
ll.reverse()
ll.print_ll() | false |
8c2035389bee962cd81c58f710e21d5f5e15d5cd | artorious/simple_scripts_tdd | /test_longer_string.py | 998 | 4.15625 | 4 | #!/usr/bin/env python3
""" Tests for longer_string.py """
import unittest
from longer_string import longer_string
class TestLongerString(unittest.TestCase):
""" Test cases for longer_string() """
def test_invalid_input(self):
""" Tests both arguments are strings """
self.assertRaises(
TypeError, longer_string, ('art', 1), 'Expected strings'
)
self.assertRaises(
TypeError, longer_string, (11, 1), 'Expected strings'
)
def test_different_lengths(self):
""" Test function prints the longer of the two strings provided """
self.assertEqual(longer_string('art', 'arthur'), 'arthur')
self.assertEqual(longer_string('arthur', 'arthr'), 'arthur')
def test_same_lengths(self):
""" Test function prints both strings if they are of the same length
"""
self.assertEqual(longer_string('arthur', 'ngondo'), 'arthur\nngondo')
if __name__ == '__main__':
unittest.main()
| true |
e4a9b2f2f3c847ea444f2380217eca63adf7ffd3 | JessBrunker/euler | /euler23/euler23.py | 2,576 | 4.125 | 4 | #!/usr/bin/python3
'''
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 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 the sum exceed 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
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.
'''
import time
import math
start = time.time()
summed_divisors = {1:0, 2:0, 3:0, 5:0, 7:0, 11:0, 13:0, 17:0, 19:0}
'''
def sum_divisors(num):
if num in summed_divisors:
return summed_divisors[num]
top = int(num/2)
while top > 1:
if num % top == 0:
div = int(num / top)
factor = sum_divisors(top)
summed_divisors[num] = 1 + top + factor
if div not in summed_divisors:
summed_divisors[num] += div
return summed_divisors[num]
top -= 1
summed_divisors[num] = 0
return 0
'''
def sum_divisors(num):
if num == 1:
return 1
top = int(math.sqrt(num)) + 1
total = 1
divisor = 2
while divisor < top:
if num % divisor == 0:
total += divisor
total += int(num/divisor)
divisor += 1
return total
# test if number is abundant
def is_abundant(num):
return sum_divisors(num) > num
def test_abundant(num):
total = 0
for i in range(1, int(num/2)+1):
if num % i == 0:
total += i
return total > num
if __name__ == '__main__':
UPPER_LIMIT = 28124
#UPPER_LIMIT = 2000
abundants = []
for i in range(2,UPPER_LIMIT, 2):
if is_abundant(i):
abundants.append(i)
sums = set()
top = 0
for i in abundants:
for j in abundants:
total = i + j
top = max(top, total)
sums.add(total)
total = 0
for i in range(top):
if i not in sums:
total += i
print(total)
end = time.time()
print('{}s'.format(end-start))
| true |
8ffa90066929fb6ada2524fedba217edd785c2e4 | jorge-jauregui/guess-the-number-game | /guess the number.py | 587 | 4.125 | 4 | print("Welcome to Jorge's 'guess the number' game!")
print("I have in mind a number between 1 and 100. Can you guess what it is?")
import random
random.randrange(1, 101)
number_guess = random.randrange(1, 101)
chances = 0
while chances < 100000:
user_guess = int(input("Type your guess: "))
if user_guess == number_guess:
print("You smart cookie! Sorry, I don't have anything to give you.")
break
elif user_guess > number_guess:
print("Are you trying to pull my leg? Guess lower.")
else:
print("The number I have in mind is higher.")
| true |
5289398156ac28b120441ed9158c132411d511da | bennettokotcha/python_start | /hello_world.py | 1,503 | 4.53125 | 5 | # print ('Hello World')
# print ('new language means creating new pathwyas in my brain...alot of learning!!')
# x = 'Hello Python'
# print (x)
# y = 42
# print (y)
# print (x, y)
# print('this is a sample string')
# name = '`Bennett` the Don!'
# print('My name is ' + name)
# first_name = "Bennett"
# last_name = "Okotcha"
# age = 28
# print(f"My name is {first_name} {last_name} and I am {age} years old.")
# print("My name is {} {} and I am {} years old!".format(first_name, last_name, age))
# print("My name is %s %s, and I am %d years old" % (first_name, last_name, age))
# x = 'bennett NDOZI okotcha'
# print(x.lower().count('o'))
# print(x.lower().islower())
# print(x.upper().islower())
# print(x.lower().split('o'))
# print(x.endswith('a'))
# print(x.isalnum())
# print(x.lower().isalnum())
# ASSIGNMENT HELLO WORLD **
# 1 print Hello World
print('hello world'.title())
print ("Hello World")
# 2 print "Hello Noelle!" with the name in the variable
name = 'Bennett'
print('Hello ' + name + '!')
print ('Hello', name, '!')
# 3 print "Hello 42!" with the number as a varialble
number = 21
print ('Hello ' + str(number) + '!')
print ('Hello', number, '!')
# 4 print "I love to eat rice and stew." with the foods in variables
fav_food1 = 'rice'
fav_food1A = 'stew'
print("I love to eat {} and {}.".format(fav_food1, fav_food1A))
print(f"I love to eat {fav_food1} and {fav_food1A}.")
# this was fun to learn something new, i want to see if i can rememebr how to these chnages and merge them to my local console!
| false |
316688cfd723a90690b103add5d1b582ca75bbf9 | akshay-1993/Python-HackerRank | /Staircase.py | 574 | 4.40625 | 4 |
# Problem
# Consider a staircase of size : n = 4
#
# #
# ##
# ###
# ####
# Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces.
#
# Write a program that prints a staircase of size n.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
for i in range(1, n+1):
print(' '*(n-i)+"#"*i)
if __name__ == '__main__':
n = int(input())
staircase(n) | true |
83338738da87bdcc5cd4ef0522b5eb70c913046a | yokohamaH/deeplerninglen | /test.py | 462 | 4.21875 | 4 | def accumulate_list(iterable):
current = 0
lst = []
for element in iterable:
current += element
lst.append(current)
return lst
def accumulate_generator(iterable):
current = 0
for element in iterable:
current += element
yield current
# ジェネレータイテレータ
gen = accumulate_generator((1, 2, 3, 4, 5))
for e in gen:
print(e)
# リスト
lst = accumulate_list((1, 2, 3, 4, 5))
print(lst)
| false |
272470f47bd4c525369e615ea3b8346e2d525488 | yoheiMune/Python-LectureNote | /day2/common.py | 984 | 4.3125 | 4 | #
# 共通処理 - Python Lecture Day2
#
import numpy as np
import matplotlib.pyplot as plt
def load_data():
"""線形回帰に利用するデータを読み込みます"""
X = np.loadtxt("./automobile.txt", delimiter=",")
return X.tolist(), X[:,0].tolist(), X[:,1].tolist()
def show(data, x_vals=None, y_vals=None, Theta=None, hypothesis_func=None):
"""グラフ表示を行います"""
X = np.array(data)
min_x = 0
max_x = np.amax(X[:,0]) + 10
min_y = 0
max_y = np.amax(X[:,1]) + 1000
# データをプロットします
plt.plot(X[:,0], X[:,1], "ro")
plt.draw()
# 回帰直線の表示
if hypothesis_func:
t = np.arange(min_x, max_x, 0.01)
plt.plot(t, hypothesis_func(t.tolist(), Theta))
plt.draw()
# グラフ設定
plt.ylabel('price')
plt.xlabel('engine-size')
plt.title('車の排気量と価格')
plt.axis([min_x, max_x, min_y, max_y])
# グラフ表示
plt.show()
| false |
36d0406ea682acc2c1847191849ac889a75d75c9 | dagamargit/absg_exercises | /04_changing_the_line_spacing_of_a_text_file.py | 1,063 | 4.125 | 4 | #!/usr/bin/python
# Write a script that reads each line of a target file, then writes the line back to stdout,
#+but with an extra blank line following. This has the effect of double-spacing the file.
#
# Include all necessary code to check whether the script gets the necessary command-line argument (a filename),
#+and whether the specified file exists.
#
# When the script runs correctly, modify it to triple-space the target file.
# Finally, write a script to remove all blank lines from the target file, single-spacing it.
import sys
import os
err_wrong_args = 65
if len(sys.argv) == 1 or not os.path.isfile(sys.argv[1]):
print "Usage: " + os.path.basename(sys.argv[0]) + " file"
sys.exit(err_wrong_args)
text_file = sys.argv[1]
with open(text_file) as fl:
for line in fl.readlines():
if len(line) > 1:
print line,
# For now, script remove all blank lines from file.
# For double-spacing: uncomment two lines below.
# For triple-spacing: uncomment three lines below.
# print
# print
# print
| true |
e267a34267b31cae25ca650817d9f6ec23097ccc | jeremy-techson/PythonBasics | /tuples.py | 621 | 4.375 | 4 | # Tuples are immutable list
numbers = (1, 2, 3, 4, 5)
print(numbers)
# Operations available to tuples are almost the same with list
print(numbers[0:3])
print("Length: ", len(numbers))
numbers = numbers + (6, 7)
print(numbers)
print("7 in tuple?", 7 in numbers)
for num in numbers:
print(num, end=", ")
print("")
# Convert list to tuple
strawhat_crew = ["Luffy", "Zorro", "Nami", "Sanji", "Usopp", "Chopper", "Robin", "Franky", "Brook", "Jimbei"]
strawhat_crew = tuple(strawhat_crew)
print(strawhat_crew)
# Convert tuple to list
print(list(strawhat_crew))
print(min(strawhat_crew))
print(max(strawhat_crew))
| true |
fb5aeea26dd41fbeb9a6857358ee9d55bad7e798 | RafaelSanzio0/FACULDADE-PYTHON.2 | /Material para n2/N2 ESTUDO/Funções/SomaDigito.py | 626 | 4.34375 | 4 | '''9) Dado um número inteiro positivo, escreva um programa modularizado para calcular a soma de seus dígitos.
O seu programa deve contar uma função que lê um número inteiro e positivo, bem como uma função,
chamada somaDigitos, que recebe um inteiro e positivo n
e retorna um inteiro e positivo, representando a soma dos dígitos do número dado.'''
def Le_numero():
numero = str(input("Dgt um numero: "))
return numero
def soma_digito(numero):
soma = 0
for i in range(len(numero)):
soma += int(numero[i])
print("A soma dos dgts é",soma)
numero = Le_numero()
soma = soma_digito(numero) | false |
36020dbf86285bcb3904085cdd86a2abe920d528 | RafaelSanzio0/FACULDADE-PYTHON.2 | /Material para n2/N2 ESTUDO/Listas/ListaAmigos.py | 1,968 | 4.21875 | 4 | def msg():
print("-=-="*20)
print("LISTA DE AMIGOS :)")
msg()
def op():
print("\n")
print("(1) - Cadastrar um amigo no final da lista")
print("(2) - Mostrar o nome de todos na lista")
print("(3) Cadastrar um amigo no início da lista")
print("(4) Remover um nome")
print("(5) Substituir um nome")
print("(6) Mostrar o número total de amigos cadastrados")
print("(7) Colocar os nomes dos amigos em ordem alfabética")
print("(8) - Sair da Lista ""\n")
tipo = int(input("Digite uma opção: "))
return tipo
def nome_lista_final(): # 1
nome = str(input("Digite o nome a ser cadastrado no final: "))
print("\n")
lista.append(nome)
return lista
def mostrar_lista(): # 2
print(lista)
print("\n")
return lista
def nome_lista_inicio(): # 3
nome = str(input("Digite um nome a ser cadastrado no começo: "))
lista.insert(0,nome)
return lista
def remover_nome_lista(): # 4
id = int(input("Digite o indice a ser removido da lista: "))
del lista[id]
return lista
def sub_nome_lista(): # 5
id = int(input("Digite o indice a ser substituido da lista: "))
nome = str(input("Digite o novo nome: "))
lista[id] = nome
return lista
def total_lista(): # 6
print("Tamanho total da lista",len(lista))
return lista
def ordem_lista(): # 7
lista.sort()
return lista
def sair_lista(): # 8
print("Voce saiu")
return lista
lista = []
while True:
escolha = op()
if escolha == 1:
lista = nome_lista_final()
if escolha == 2:
lista = mostrar_lista()
if escolha == 3:
lista = nome_lista_inicio()
if escolha == 4:
lista = remover_nome_lista()
if escolha == 5:
lista = sub_nome_lista()
if escolha == 6:
lista = total_lista()
if escolha == 7:
lista = ordem_lista()
if escolha == 8:
lista = sair_lista()
break
| false |
2500df19b972bec81642da911c1ee72101bf0ee8 | tjguk/kelston_mu_code | /20181124/primes.py | 635 | 4.21875 | 4 | """A simple function which will indicate whether a number is a prime or not
"""
def is_prime(n):
#
# Check every number up to half of the number
# we're checking since if we're over half way
# we must have hit all the factors already
#
for factor in range(2, 1 + (n // 2)):
if n % factor == 0:
#
# Bail out as soon as we've found a factor
#
return False
#
# If we haven't found anything, it's a prime
#
return True
while True:
candidate = int(input("Enter a number: "))
print("Prime" if is_prime(candidate) else "Not Prime")
| true |
316e325d6eb23a574569332c4796dc70118847bc | ardenzhan/dojo-python | /arden_zhan/Python/Python Fundamentals/string_list.py | 862 | 4.125 | 4 | '''
String and List Practice
.find()
.replace()
min()
max()
.sort()
len()
'''
print "Find and Replace"
words = "It's thanksgiving day. It's my birthday, too!"
print "Position of first instance of day:", words.find("day")
print words.replace("day", "month", 1)
print ""
print "Min and Max"
x = [2,54,-2,7,12,98]
print "List:", x
print "Min value of list:", min(x)
print "Max value of list:", max(x)
print ""
print "First and Last"
x = ["hello",2,54,-2,7,12,98,"world"]
print "List:", x
newList = [x[0], x[len(x) - 1]]
print "List of first and last element:", newList
print ""
print "New List"
x = [19,2,54,-2,7,12,98,32,10,-3,6]
print x
x.sort()
print "Sorted List", x
half = len(x) / 2
firstHalf = x[:half]
secondHalf = x[half:len(x)]
print "First Half:", firstHalf
print "Second Half:", secondHalf
secondHalf.insert(0, firstHalf)
print "Output:", secondHalf | true |
4d79f25d46800b34809bfa18691f99567f91ce20 | ardenzhan/dojo-python | /arden_zhan/Python/Python Fundamentals/scores_and_grades.py | 800 | 4.34375 | 4 | '''Scores and Grades'''
# generates ten scores between 60 and 100. Each time score generated, displays what grade is for particular score.
'''
Grade Table
Score: 60-79; Grade - D
Score: 70-79; Grade - C
Score: 80-89; Grade - B
Score: 90-100; Grade - A
'''
# import random
# #random_num = random.random()
# #random function returns float - 0.0 <= random_num < 1.0
# random_num = random.randint(60, 100)
import random
def scoreGrade(quantity, min, max):
for x in range(quantity):
random_num = random.randint(min, max)
grade = ""
if random_num >= 90: grade += "A"
elif random_num >= 80: grade += "B"
elif random_num >= 70: grade += "C"
else: grade += "D"
print "Score: {}; Your grade is {}".format(random_num, grade)
scoreGrade(10, 60, 100)
| true |
c63063ed71536d139b127cc48d2aae18a915e8ba | muhammad-masood-ur-rehman/Skillrack | /Python Programs/adam-number.py | 665 | 4.375 | 4 | Adam number
A number is said to be an Adam number if the reverse of the square of the number is equal to the square of the reverse of the number. For example, 12 is an Adam number because the reverse of the square of 12 is the reverse of 144, which is 441, and the square of the reverse of 12 is the square of 21, which is also 441.
Write an Algorithm and the subsequent Python code to check whether the given number is an Adam number or not.
Write a function to reverse a number
def rev(n):
return(int(str(n)[::-1]))
def adam(num):
if(rev(num)**2==rev(num**2)):
print('Adam number')
else:
print('Not an Adam number')
n=int(input())
adam(n)
| true |
7451ad703a6c8c56d0976ef8e6d481ef3e7feae0 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/sum-unit-digit-3-or-6.py | 667 | 4.34375 | 4 | Sum - Unit Digit 3 or 6
The program must accept N integers as the input. The program must print the sum of integers having the unit digit as 3 or 6 as the output. If there is no such integer then the program must print -1 as the output.
Boundary Condition(s):
1 <= N <= 100
1 <= Each integer value <= 10^5
Example Input/Output 1:
Input:
5
12 43 30 606 7337
Output:
649
Example Input/Output 2:
Input:
4
52 84 365 134
Output:
-1
N = int(input())
numList = [int(val) for val in input().split()]
sumVal, printed = 0, False
for val in numList:
if val % 10 == 3 or val % 10 == 6:
sumVal += val
printed = True
print('-1' if sumVal == 0 else sumVal)
| true |
1c96e07d40bd8283d1b28ac27fe4c5d8af4d31e4 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/replace-border-with-string.py | 907 | 4.3125 | 4 | Replace Border with String
The program must accept a character matrix of size RxC and a string S as the input. The program must replace the characters in the border of the matrix with the characters in the string S in the clockwise direction. Then the program must print the modified matrix as the output.
Example Input/Output 1:
Input:
4 5
@ b c d E
e f 5 h i
b c d e q
k 9 o l 2
queenbee
Output:
q u e e n
e f 5 h b
b c d e e
k 9 o l e
Example Input/Output 2:
Input:
3 3
A b c
d * f
g h i
d@$zling
Output:
d @ $
g * z
n i l
R,C=map(int,input().split())
matrix=[list(map(str,input().split())) for ctr in range(R)]
S=input().strip()
row,col=0,0
for ch in S:
matrix[row][col]=ch
if row==0 and col<C-1:
col+=1
elif row==R-1 and col>0:
col-=1
elif col==C-1 and row<R-1:
row+=1
elif col==0 and row>0:
row-=1
for val in matrix:
print(*val)
| true |
ada01c186d7844f188d4231a43681cedd802029c | muhammad-masood-ur-rehman/Skillrack | /Python Programs/product-of-current-and-next-elements.py | 1,369 | 4.125 | 4 | Product of Current and Next Elements
Given an array of integers of size N as input, the program must print the product of current element and next element if the current element is greater than the next element. Else the program must print the current element without any modification.
Boundary Condition(s):
1 <= N <= 100
Input Format:
The first line contains the value of N.
The second line contains N integers separated by space(s).
Output Format:
The first line contains N integers separated by space(s).
Example Input/Output 1:
Input:
6
5 4 6 5 7 2
Output:
20 4 30 5 14 2
Explanation:
For 1st element, 5>4 so the output is 5*4=20
For 2nd element, 4<6 so the output is 4
For 3rd element, 6>5 so the output is 6*5=30
For 4th element, 5<7 so the output is 5
For 5th element, 7>2 so the output is 14
For 6th element there is no next element, so the output is 2
Example Input/Output 2:
Input:
5
22 21 30 2 5
Output:
462 21 60 2 5
Explanation:
For 1st element, 22>21 so the output is 22*21=462
For 2nd element, 21<30 so the output is 21
For 3rd element, 30>2 so the output is 30*2=60
For 4th element, 2<5 so the output is 2
For 5th element there is no next element, so the output is 5
n=int(input())
l=list(map(int,input().split()))
for i in range(n-1):
if(l[i]>l[i+1]):
print(l[i]*l[i+1],end=" ")
else:
print(l[i],end=" ")
print(l[n-1])
| true |
5c30823a56d59cc5c51b764f4781fed4b1ba1997 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/find-duplicates-in-folder.py | 1,562 | 4.1875 | 4 | Find Duplicates In Folder
The directory structure of a file system is given in N lines. Each line contains the parent folder name and child file/folder name. If a folder has two files/folders with the same name then it is a duplicate. Print all the duplicate file/folders names sorted in ascending order. If there is no duplicate print -1.
Boundary Condition(s):
1 <= N <= 100
2 <= Length of file/folder name <= 100
Input Format:
The first line contains N.
The next N lines contain parent and child file/folder name separated by space.
Output Format:
Print the duplicate file/folder names sorted in ascending order. If there is no duplicate print -1.
Example Input/Output 1:
Input:
5
videos trailer.mp4
documents word.doc
documents animal.jpg
test trailer.mp4
documents word.doc
Output:
word.doc
Example Input/Output 2:
Input:
7
src style.css
videos HD.mp4
documents sheet.xls
documents animal.jpg
test animal.jpg
documents sheet.xls
src style.css
Output:
sheet.xls
style.css
a=int(input())
d={}
e=[];f=[]
for i in range(a):
b,c=map(str,input().split())
e.append(b)
f.append(c)
x=0
for i in f:
d.setdefault(i,[]).append(e[x])
x+=1
ans=[]
for i in d.keys():
s=list(set(d[i]))
if(len(d[i])>1):
if(len(s)!=len(d[i])):
ans.append(i)
ans=sorted(ans)
if(ans==[]):
print(-1)
else:
print(*ans, sep="\n")
d=[]
c=[]
for i in range(int(input())):
k=input().split()
if k not in d:
d.append(k)
elif k[1] not in c:
c.append(k[1])
if not c:
print(-1)
for i in sorted(c):
print(i)
| true |
63f9c82f95090e789395286b4f977b74ac621a4b | muhammad-masood-ur-rehman/Skillrack | /Python Programs/matching-word-replace.py | 1,307 | 4.3125 | 4 | Matching Word - Replace ?
The program must accept two string values P and S as input. The string P represents a pattern. The string S represents a set of words. The character '?' in P matches any single character. The program must print the word in S that matches the given pattern P as the output. If two or more words match the pattern P, then the program must print the first occurring word as the output.
Note: At least one word in S is always matched with P.
Boundary Condition(s):
1 <= Length of P <= 100
1 <= Length of S <= 1000
Input Format:
The first line contains P.
The second line contains S.
Output Format:
The first line contains a string representing the word in S that matches the pattern P.
Example Input/Output 1:
Input:
?i?n
LION crane lion breath kiln
Output:
lion
Explanation:
Here P = "?i?n" and S = "LION crane lion breath kiln".
There are two words in S that match the pattern P.
lion klin
So the first occurring word lion is printed as the output.
Example Input/Output 2:
Input:
BR??E?
BRIGHT BEST BRAVE BROKEN
Output:
BROKEN
s=input().strip()
k=s;p=[];m=0
l=input().strip().split()
for i in l:
m=0
if len(i)==len(s):
for j in range(len(i)):
if s[j]!='?' and s[j]!=i[j]:
m=1
if m==0:
p.append(i)
print(p[0])
| true |
5de0252734c9525ea7956e7cd76d14401e1b3d7d | muhammad-masood-ur-rehman/Skillrack | /Python Programs/python-program-for-interlace-odd-even-from-a-to-b.py | 1,509 | 4.4375 | 4 | Python Program for Interlace odd / even from A to B
Two numbers A and B are passed as input. The program must print the odd numbers from A to B (inclusive of A and B) interlaced with the even numbers from B to A.
Input Format:
The first line denotes the value of A.
The second line denotes the value of B.
Output Format:
The odd and even numbers interlaced, each separated by a space.
Boundary Conditions:
1 <= A <= 9999999
A < B <= 9999999
Example Input/Output 1:
Input:
5
11
Output:
5 10 7 8 9 6 11
Explanation:
The odd numbers from 5 to 11 are 5 7 9 11
The even numbers from 11 to 5 (that is in reverse direction) are 10 8 6
So these numbers are interlaced to produce 5 10 7 8 9 6 11
Example Input/Output 2:
Input:
4
14
Output:
14 5 12 7 10 9 8 11 6 13 4
Explanation:
The odd numbers from 4 to 14 are 5 7 9 11 13
The even numbers from 14 to 4 (that is in reverse direction) are 14 12 10 8 6 4
So these numbers are interlaced to produce 14 5 12 7 10 9 8 11 6 13 4
(Here as the even numbers count are more than the odd numbers count we start with the even number in the output)
Example Input/Output 3:
Input:
3
12
Output:
3 12 5 10 7 8 9 6 11 4
Explanation:
The odd numbers from 3 to 12 are 3 5 7 9 11
The even numbers from 12 to 3 (that is in reverse direction) are 12 10 8 6 4
So these numbers are interlaced to produce 3 12 5 10 7 8 9 6 11 4
a=int(input())
b=int(input())
i=a;j=b
while(i<=b and j>=a):
if i%2!=0:
print(i,end=" ")
i+=1
if j%2==0:
print(j,end=" ")
j-=1
| true |
c2b2db90bec32dd87464306cbc8a57b91b3d0243 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/odd-even-row-pattern-printing.py | 940 | 4.59375 | 5 | Odd Even Row - Pattern Printing
Given a value of N, where N is the number of rows, the program must print the character '*' from left or right depending on whether the row is an odd row or an even row.
- If it is an odd row, the '*' must start from left.
- If it is an even row, the '*' must start from right.
After the asterisk '*' the numbers from 1 to the row count must be printed.
Input Format:
The first line will contain the value of N
Output Format:
N lines will contain '*' forming the pattern as described.
Constraints:
2 <= N <= 25
Example Input/Output 1:
Input:
3
Output:
*1
21*
*123
Example Input/Output 2:
Input:
5
Output:
*1
21*
*123
4321*
*12345
n=int(input())
for i in range(1,n+1):
if(i%2!=0):
print("*",end="")
for j in range(1,i+1):
print(j,end="")
print()
elif(i%2==0):
for j in range(i,0,-1):
print(j,end="")
print("*",end="")
print()
| true |
25e72d166e88791aaac58cdd83ed552c38b3867f | muhammad-masood-ur-rehman/Skillrack | /Python Programs/check-sorted-order.py | 1,127 | 4.125 | 4 | Check Sorted Order
The program must accept N integers which are sorted in ascending order except one integer. But if that single integer R is reversed, the entire array will be in sorted order. The program must print the first integer that must be reversed so that the entire array will be sorted in ascending order.
Boundary Condition(s):
2 <= N <= 20
Input Format:
The first line contains N.
The second line contains N integer values separated by a space.
Output Format:
The first line contains the integer value R.
Example Input/Output 1:
Input:
5
10 71 20 30 33
Output:
71
Explanation:
When 71 is reversed the array becomes sorted as below.
10 17 20 30 33
Example Input/Output 2:
Input:
6
10 20 30 33 64 58
Output:
64
Example Input/Output 3:
Input:
6
10 20 30 33 67 58
Output:
58
def rev(n):
reve=0
while(n>0):
r=n%10
reve=reve*10+r
n=n//10
return reve
n=int(input())
l=list(map(int,input().split()));ind=0
while(True):
number=l[ind]
r=rev(number)
l[ind]=r
if l==sorted(l):
print(number)
break
else:
l[ind]=number
ind+=1
| true |
a8d6708bf1f9958cd05214bf00e43a3cf3dcdfe0 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/count-overlapping-string-pattern.py | 1,039 | 4.1875 | 4 | Count Overlapping String Pattern
Two string values S and P representing a string and pattern are passed as the input to the program. The program must print the number of overlapping occurrences of pattern P in the string S as the output.
Note: The string S and pattern P contains only lowercase alphabets.
Boundary Condition(s):
1 <= Length of S <= 2000000
1 <= Length of P <= 10
Input Format:
The first line contains S.
The second line contains P.
Output Format:
The first line contains the number of overlapping occurrences of P in S.
Example Input/Output 1:
Input:
precondition
on
Output:
2
Explanation:
The pattern on occurs two times in precondition so 2 is printed.
Example Input/Output 2:
Input:
tetetetmtey
tet
Output:
3
def overlap(string,substring):
c=0;s=0
while s<len(string):
pos=string.find(substring,s)
if pos!=-1:
s=pos+1
c+=1
else:
break
return c
string=input().strip()
substring=input().strip()
print(overlap(string,substring))
| true |
6ee5cd6a8e090682bf699c788e467ccb8cfb975c | muhammad-masood-ur-rehman/Skillrack | /Python Programs/first-m-multiples-of-n.py | 558 | 4.46875 | 4 | First M multiples of N
The number N is passed as input. The program must print the first M multiples of the number
Input Format:
The first line denotes the value of N.
The second line denotes the value of M.
Output Format:
The first line contains the M multiples of N separated by a space.
Boundary Conditions:
1 <= N <= 999999
Example Input/Output 1:
Input:
5
7
Output:
5 10 15 20 25 30 35
Example Input/Output 2:
Input:
50
11
Output:
50 100 150 200 250 300 350 400 450 500 550
a=int(input())
b=int(input())
for i in range(1,b+1):
print(a*i,end=" ")
| true |
15125f1513e68e317ad5bc79e4f09f7c6dbb4dbd | muhammad-masood-ur-rehman/Skillrack | /Python Programs/direction-minimum-shift.py | 2,093 | 4.3125 | 4 | Direction & Minimum Shift
The program must accept two string values S1 and S2 as the input. The string S2 represents the rotated version of the string S1. The program must find the minimum number of characters M that must be shifted (Left or Right) in S1 to convert S1 to S2. Then the program must print the direction (L-Left or R-Right or A-Any direction) in which the characters in the string S1 are shifted and the value of M as the output. The direction A represents that the string S1 can be converted to S2 in both directions with the same value M.
Boundary Condition(s):
2 <= Length of S1, S2 <= 100
Input Format:
The first line contains S1.
The second line contains S2.
Output Format:
The first line contains a character (L or R or A) and M.
Example Input/Output 1:
Input:
hello
llohe
Output:
L2
Explanation:
Here S1 = hello and S2 = llohe.
If 3 characters in S1 are shifted to the right, it becomes llohe.
If 2 characters in S1 are shifted to the left, it becomes llohe.
Here the minimum is 2, so L2 is printed as the output.
Example Input/Output 2:
Input:
IcecrEAm
EAmIcecr
Output:
R3
Explanation:
Here S1 = IcecrEAm and S2 = EAmIcecr.
If 3 characters in S1 are shifted to the right, it becomes EAmIcecr.
If 5 characters in S1 are shifted to the left, it becomes EAmIcecr.
Here the minimum is 3, so R3 is printed as the output.
Example Input/Output 3:
Input:
ROBOTICS
TICSROBO
Output:
A4
Explanation:
Here S1 = ROBOTICS and S2 = TICSROBO.
If 4 characters in S1 are shifted to the right, it becomes TICSROBO.
If 4 characters in S1 are shifted to the left, it becomes TICSROBO.
Here both directions give the minimum is 4, so A4 is printed as the output.
n=input().strip()
m=input().strip()
if n==m:
print("A0")
else:
l,r=n,n
for i in range(1,len(n)+1):
l=l[1:]+l[0]
r=r[-1]+r[:-1]
if l==m and r==m:
print("A{}".format(i))
break
elif l==m:
print("L{}".format(i))
break
elif r==m:
print("R{}".format(i))
break
| true |
c88a8f7c2ef64b308a95bd5b040b5f98df2f40b1 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/remove-characters-from-left.py | 1,445 | 4.28125 | 4 | Remove Characters from Left
Remove Characters from Left: The program must accept two string values S1 and S2 as the input. The program must print the minimum number of characters M to be removed from the left side of the given string values so that the revised string values become equal (ignoring the case). If it is not possible, then the program must print -1 as the output.
Boundary Condition(s):
1 <= Length of S1, S2 <= 1000
Input Format:
The first line contains S1.
The second line contains S2.
Output Format:
The first line contains M.
Example Input/Output 1:
Input:
Cream
JAM
Output:
4
Explanation:
After removing the first 3 characters from the string Cream, the string becomes am.
After removing the first character from the string JAM, the string becomes AM.
The revised string values am and AM are equal by ignoring the case.
The minimum number of characters to be removed from the left side of the given string values is 4 (3 + 1).
So 4 is printed as the output.
Example Input/Output 2:
Input:
corn
Corn
Output:
0
Example Input/Output 3:
Input:
123@abc
123@XYZ
Output:
-1
S1=input().strip().lower()
S2=input().strip().lower()
L1=S1[::-1]
L2=S2[::-1]
temp=''
for ele in range(min(len(L1),len(L2))):
if L1[ele]==L2[ele]:
temp+=L1[ele]
else:
break
flag=len(temp)
var1=len(S1)-len(temp)
var2=len(S2)-len(temp)
if flag==0:
print(-1)
elif S1==S2:
print(0)
else:
print(var1+var2)
| true |
aa6ea506e424f5b0a50f4537652395b31a901596 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/rotate-matrix-pattern.py | 1,377 | 4.46875 | 4 | Rotate Matrix Pattern
The program must accept an integer matrix of size N*N as the input. The program must rotate the matrix by 45 degrees in the clockwise direction. Then the program must print the rotated matrix and print asterisks instead of empty places as the output.
Boundary Condition(s):
3 <= N <= 100
Input Format:
The first line contains N.
The next N lines, each contains N integers separated by a space.
Output Format:
The first (2*N)-1 lines containing the rotated matrix.
Example Input/Output 1:
Input:
3
1 2 3
4 5 6
7 8 9
Output:
**1
*4 2
7 5 3
*8 6
**9
Explanation:
After rotating the matrix by 45 degrees in the clockwise direction, the matrix becomes
1
4 2
7 5 3
8 6
9
So the rotated matrix is printed and the asterisks are printed instead of empty places.
Example Input/Output 2:
Input:
4
13 21 36 49
55 65 57 80
17 32 63 44
56 60 78 98
Output:
***13
**55 21
*17 65 36
56 32 57 49
*60 63 80
**78 44
***98
n=int(input())
arr=[]
for i in range(n):
a=[]
for j in range(n):
a.append(int(input()))
arr.append(a)
s1,s2=0,0
stars=n-1
for i in range(1, (2*n)):
i1=s1
i2=s2
for j in range(1,n+1):
if(j<=stars):
print("*",end=' ')
else:
print(arr[i1][i2],end=" ")
i1-=1
i2+=1
if(i>n-1):
s2+=1
stars+=1
else:
stars-=1
s1+=1
print("")
| true |
8ec84a6f4492aa2fc49b4fee6a9e6a9ca41083f6 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/sum-of-digits-is-even-or-odd.py | 690 | 4.125 | 4 | Sum of Digits is Even or Odd
Sum of Digits is Even or Odd: Given an integer N as input, the program must print Yes if the sum of digits in a given number is even. Else it must print No.
Boundary Condition(s):
1 <= N <= 99999999
Input Format:
The first line contains the value of N.
Output Format:
The first line contains Yes or No.
Example Input/Output 1:
Input:
123
Output:
Yes
Explanation:
The sum of digits in a given number is 1+2+3 = 6.
Hence the output is Yes.
Example Input/Output 2:
Input:
1233
Output:
No
Explanation:
The sum of digits in a given number is 1+2+3+3 = 9.
Hence the output is No.
n=input()
s=0
for i in n:
s+=int(i)
print('Yes' if s%2==0 else print('No')
| true |
1321a5a0862b67f2f4568189562a86f3444a201e | muhammad-masood-ur-rehman/Skillrack | /Python Programs/batsman-score.py | 844 | 4.125 | 4 | Batsman Score
Batsman Score: Given an integer R as input, the program must print Double Century if the given integer R is greater than or equal to 200. Else if the program must print Century if the given integer R is greater than or equal to 100. Else if the program must print Half Century if the given integer R is greater than or equal to 50. Else the program must print Normal Score.
Boundary Condition(s):
1 <= R <= 999
Input Format:
The first line contains the value of R.
Output Format:
The first line contains Double Century or Century or Half Century or Normal Score.
Example Input/Output 1:
Input:
65
Output:
Half Century
Example Input/Output 2:
Input:
158
Output:
Century
r=int(input())
print('Double Century') if r>=200 else print('Century') if r>=100 else print('Half Century') if r>=50 else print('Normal Score')
| true |
dc3805fb23ea3f2f06c3263183c16edd3967deed | muhammad-masood-ur-rehman/Skillrack | /Python Programs/toggle-case.py | 617 | 4.3125 | 4 | Toggle Case
Simon wishes to convert lower case alphabets to upper case and vice versa. Help Simon by writing a program which will accept a string value S as input and toggle the case of the alphabets. Numbers and special characters remain unchanged.
Input Format: First line will contain the string value S
Output Format: First line will contain the string value with the case of the alphabets toggled.
Constraints: Length of S is from 2 to 100
SampleInput/Output:
Example 1:
Input: GooD mORniNg12_3
Output: gOOd MorNInG12_3
Example 2:
Input:R@1nBow
Output:r@1NbOW
n=input()
print(n.swapcase())
| true |
cd8de721b5a119f128606b24071ed7a2c4aafed0 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/top-left-to-bottom-right-diagonals-program-in-python.py | 1,296 | 4.28125 | 4 | Top-left to Bottom-Right Diagonals Program In Python
The program must accept an integer matrix of size RxC as the input. The program must print the integers in the top-left to bottom-right diagonals from the top-right corner of the matrix.
Boundary Condition(s):
2 <= R, C <= 50
1 <= Matrix element value <= 1000
Input Format:
The first line contains R and C separated by a space.
The next R lines, each contains C integers separated by a space.
Output Format:
The first (R+C)-1 lines, each contains the integer value(s) separated by a space.
Example Input/Output 1:
Input:
3 3
9 4 5
9 5 3
7 7 5
Output:
5
4 3
9 5 5
9 7
7
Explanation:
In the given 3x3 matrix, the integers in the top-left to bottom-right diagonals from the top-right corner of the matrix are given below.
5
4 3
9 5 5
9 7
7
Example Input/Output 2:
Input:
7 5
17 88 27 71 57
28 96 59 99 56
52 69 80 86 57
85 56 48 59 47
61 85 58 86 36
63 23 14 70 60
28 50 17 24 13
Output:
57
71 56
27 99 57
88 59 86 47
17 96 80 59 36
28 69 48 86 60
52 56 58 70 13
85 85 14 24
61 23 17
63 50
28
r,c=map(int,input().split())
m=[list(map(int,input().split())) for row in range(r)]
for i in range(1-c,r):
for row in range(r):
for col in range(c):
if row-col==i:
print(m[row][col],end=" ")
print()
| true |
6c7286a208f6e7c8152d488ceb97ebb1df8c7bbf | muhammad-masood-ur-rehman/Skillrack | /Python Programs/unique-alphabet-count.py | 596 | 4.3125 | 4 | Unique Alphabet Count
A string S is passed as input to the program which has only alphabets (all alphabets in lower case). The program must print the unique count of alphabets in the string.
Input Format:
- The first line will contain value of string S+
Boundary Conditions:
1 <= Length of S <= 100
Output Format:
The integer value representing the unique count of alphabets in the string S.
Example Input/Output 1:
Input:
level
Output:
3
Explanation:
The unique alphabets are l,e,v. Hence 3 is the output.
Example Input/Output 2:
Input:
manager
Output:
6
print(len(set(input().strip())))
| true |
5ae44003eed074094a44f7b9f3edf268e48f022f | muhammad-masood-ur-rehman/Skillrack | /Python Programs/python-program-to-print-fibonacci-sequence.py | 575 | 4.5625 | 5 | Python Program To Print Fibonacci Sequence
An integer value N is passed as the input. The program must print the first N terms in the Fibonacci sequence.
Input Format:
The first line denotes the value of N.
Output Format:
The first N terms in the Fibonacci sequence (with each term separated by a space)
Boundary Conditions:
3 <= N <= 50
Example Input/Output 1:
Input:
5
Output:
0 1 1 2 3
Example Input/Output 2:
Input:
10
Output:
0 1 1 2 3 5 8 13 21 34
n=int(input())
n1,n2=0,1
count=0
while count<n:
print(n1,end=" ")
nth=n1+n2
n1=n2
n2=nth
count+=1
| true |
10e61b1d76df5b45f241b64dc305f9420d297a2e | muhammad-masood-ur-rehman/Skillrack | /Python Programs/print-numbers-frequency-based.py | 1,045 | 4.46875 | 4 | Print Numbers - Frequency Based
An array of N positive integers is passed as input. The program must print the numbers in the array based on the frequency of their occurrence. The highest frequency numbers appear first in the output.
Note: If two numbers have the same frequency of occurrence (repetition) print the smaller number first.
Input Format:
The first line contains N
The second line contains the N positive integers, each separated by a space.
Output Format:
The first line contains the numbers ordered by the frequency of their occurrence as described above.
Boundary Conditions:
1 <= N <= 1000
Example Input/Output 1:
Input:
10
1 3 4 4 5 5 1 1 2 1
Output:
1 4 5 2 3
Example Input/Output 2:
Input:
12
7 1 9 12 13 9 7 22 21 13 22 100
Output:
7 9 13 22 1 12 21 100
Example Input/Output 3:
Input:
5
11 11 11 11 11
Output:
11
Python:
import operator
n=int(input())
l=[int(i) for i in input().split()]
s={}
for i in l:
s[i]=l.count(i)
d=sorted(s.items(),key=operator.itemgetter(1),reverse=True)
for i in d:
print(i[0],end=' ')
| true |
1370e5de23f56dad4a80ed2d09096913b7899778 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/sparse-matrix.py | 706 | 4.34375 | 4 | Sparse Matrix
Write an algorithm and the subsequent Python program to check whether the given matrix is sparse or not. A matrix is said to be a “Sparse” if the number of zero entries in the matrix, is greater than or equal to the number of non-zero entries. Otherwise it is “Not sparse”. Check for boundary conditions and print 'Invalid input' when not satisfied.
r=int(input()) #number of rows in matrix
c=int(input()) #number of columns in matrix
if(r<=0 or c<=0):
print('Invalid input')
exit
else:
vals=[]
flag=0
for i in range(r*c):
vals.append(int(input()))
zero_entries=vals.count(0)
if(zero_entries>=r*c-zero_entries):
print('Sparse')
else:
print('Not sparse')
| true |
82212ae4feda9fea0df5846fdc235aee5d457ddf | muhammad-masood-ur-rehman/Skillrack | /Python Programs/all-digits-pairs-count.py | 1,119 | 4.21875 | 4 | All Digits - Pairs Count
The program must accept N integers as the input. The program must print the number of pairs X where the concatenation of the two integers in the pair consists of all the digits from 0 to 9 in any order at least once.
Boundary Condition(s):
2 <= N <= 100
1 <= Each integer value <= 10^8
Input Format:
The first line contains N.
The second line contains N integers separated by a space.
Output Format:
The first line contains X.
Example Input/Output 1:
Input:
6
38479 74180 967132 1584604 726510 6512160
Output:
3
Explanation:
The 3 possible pairs are given below.
(38479, 726510) -> 38479726510
(38479, 6512160) -> 384796512160
(967132, 1584604) -> 9671321584604
The concatenation of the two integers in each pair contains all the digits from 0 to 9 at least once.
Example Input/Output 2:
Input:
4
2670589 243106 3145987 5789
Output:
4
Python:
num=int(input())
list_arr=list(map(str,input().split()))
count=0
for i in range(len(list_arr)):
for j in range(i+1,len(list_arr)):
temp=list_arr[i]+list_arr[j]
if len(set(temp))==10:
count+=1
print(count)
| true |
27381d83b8d936ffeff2ef2e10665d913a7a166b | alexandroid1/PytonStarter_Lesson1_PC | /calculator.py | 370 | 4.1875 | 4 | x = float(input("First number: "))
y = float(input("Second number: "))
operation = input("Operation")
result = None
if operation == '+':
result = x + y
elif operation == '-':
result = x-y
elif operation == '*':
result = x*y
elif operation == '/':
result = x/y
else:
print('Unsupported operation')
if result is not None:
print('Result:', result) | true |
70f77d776c25ec8bb620e789c5f579451bb5ba09 | tapans/Algorithms-Puzzles-Challenges | /CTCI_6e/1.9_string_rotation.py | 1,072 | 4.15625 | 4 | #!/usr/bin/python
import unittest
def isSubstring(s1, s2):
'''
Returns True if s2 is a substring of s1
'''
return s1 in s2
def is_string_rotation(s1,s2):
'''
Returns True if s2 is a rotation of s1 using only one call to isSubstring. False o/w
Time Complexity: let a be len of s1, b be len of s2, and let b > a => O(b)
Space Complexity: O(1)
'''
return isSubstring(s1, s2 + s2)
def is_string_rotation_old(s1,s2):
'''
Returns True if s2 is a rotation of s1 using only one call to isSubstring. False o/w
Time Complexity: let a be len of s1, b be len of s2, and let b > a => O(b log b)
Space Complexity: O(1)
'''
s1_sorted = ''.join(sorted(s1))
s2_sorted = ''.join(sorted(s2))
return isSubstring(s1_sorted, s2_sorted)
class Test_String_Rotation(unittest.TestCase):
def test_is_substring_case(self):
self.assertTrue(is_string_rotation("waterbottle", "erbottlewat"))
def test_not_substring_case(self):
self.assertFalse(is_string_rotation("hi", "bye"))
if __name__ == '__main__':
unittest.main() | false |
fc8f710a881f74f7bf2cfc65a6c00ecccd939dfe | urstkj/Python | /thread/thread.py | 1,484 | 4.125 | 4 | #!/usr/local/bin/python
#-*- coding: utf-8 -*-
import _thread
import threading
import time
# Define a function for the thread
def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % (threadName, time.ctime(time.time())))
# Create two threads as follows
try:
_thread.start_new_thread(print_time, (
"Thread-1",
2,
))
_thread.start_new_thread(print_time, (
"Thread-2",
4,
))
except:
print("Error: unable to start thread")
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("Starting " + self.name)
print_time(self.name, 5, self.counter)
print("Exiting " + self.name)
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print("Exiting Main Thread")
print("done.")
| true |
0236e95fdffd9e769366713f402c0833f2023599 | anabeatrizzz/exercicios-pa-python | /exercicios_5/exercicios_5_01.py | 2,466 | 4.25 | 4 | """Escreva um programa que peça para o usuário digitar uma data contendo dia, mês e ano
e o programa deverá informar se é uma data válida ou não."""
class Data():
def __init__(self):
self.dia = 0
self.mes = 0
self.ano = 0
def VerificaDia(dia, mes, resultado):
if (mes == 1 or 3 or 5 or 7 or 8 or 10 or 12) and dia > 31 or dia <= 0:
print("\033[31mData invalida, informe um dia menor que 31 e não negativo.\033[m")
resultado = False
elif (mes == 4 or 6 or 9 or 11) and dia > 30 or dia <= 0:
print("\033[31mData invalida, informe um dia menor igual a 30 e não negativo.\033[m")
resultado = False
else:
resultado = True
return resultado
def VerificaBissexto(ano, mes, dia, resultado):
if (ano % 4 == 0) and (ano % 100 != 0) or (ano % 400 == 0) and (mes == 2) and (dia > 29):
print("\033[31mData invalida, fevereiro apenas possui 29 dias neste ano.\033[m")
resultado = False
elif (ano % 4 != 0) and (mes == 2) and (dia > 28):
print("\033[31mData invalida, fevereiro neste ano apenas possui 28 dias.\033[m")
resultado = False
else:
resultado = True
return resultado
def VerificaFevereiro(dia, mes, resultado):
if dia > 29 and mes == 2:
print("\033[31mData invalida, fevereiro apenas pode possuir 29 dias.\033[m")
resultado = False
else:
resultado = True
return resultado
def VerificaMes(mes, resultado):
if 12 > mes <= 0:
print("\033[31mData invalida, digite um mes válido.\033[m")
resultado = False
else:
resultado = True
return resultado
def VerificaAno(ano, resultado):
if len(str(ano)) > 4 or len(str(ano)) < 4:
print("\033[31mData invalida, digite um ano com 4 digitos.\033[m")
resultado = False
else:
resultado = True
return resultado
def VerificaTudo(dia, mes, ano, resultado):
if VerificaDia(dia, mes, resultado) and VerificaMes(mes, resultado) and VerificaFevereiro(dia, mes, resultado) and VerificaBissexto(ano, mes, dia, resultado) and VerificaAno(ano, resultado):
print(f"\033[32mA data digitada foi {dia}/{mes}/{ano} e é uma data valida!\033[m")
resultado = False
data = Data()
data.dia = int(input("Digite um dia: "))
data.mes = int(input("Digite um mês: "))
data.ano = int(input("Digite um ano: "))
VerificaDia(data.dia, data.mes, resultado)
VerificaMes(data.mes, resultado)
VerificaFevereiro(data.dia, data.mes, resultado)
VerificaBissexto(data.ano, data.mes, data.dia, resultado)
VerificaAno(data.ano, resultado)
VerificaTudo(data.dia, data.mes, data.ano, resultado)
| false |
6eff63e0b9409caaa59773416df3adb8128c880e | anabeatrizzz/exercicios-pa-python | /exemplos_Aula_4/Aula_4_07.py | 306 | 4.28125 | 4 | matriz = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
print("Entre com o valor em cada posição da matriz: ")
for a in range(0, 3):
for b in range(0, 3):
matriz[a][b] = int(input(f"mat[{a}][{b}] = "))
print("\nExibindo os dados da matriz: ")
for a in range(0, 3):
for b in range(0, 3):
print(matriz[a][b]) | false |
dc8b6496247dbcd6c0e1af69d9f44880a4567dde | anabeatrizzz/exercicios-pa-python | /exercicios_do_caderno/exercicio01_do_caderno.py | 477 | 4.28125 | 4 | """Elabore um algoritmo que receba dois números e mostre na tela o resultado da soma, subtração, multiplicação
e divisão desses números"""
num1 = float(input("Digite um numero: "))
num2 = float(input("Digite outro numero: "))
print(f'A soma desses dois numeros é: {num1 + num2}')
print(f'A subtração desses dois numeros é: {num1 - num2}')
print(f'A multiplicação desses dois numeros é: {num1 * num2}')
print(f'A divisão desses dois numeros é: {num1 // num2}')
| false |
7c5ce778fe8d215102fd05915c7d370faec8044b | anabeatrizzz/exercicios-pa-python | /exercicios_4/exercicios_4_03.py | 1,132 | 4.34375 | 4 | """Escreva um programa que leia uma matriz (3x5 ou 5x3) de 15 números inteiros e exiba ao final
a soma dos valores de cada linha que estão armazenados nesta matriz."""
matriz = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
valores = 0
for l in range(0, 3):
for c in range(0, 5):
matriz[l][c] = int(input(f'Linha {l} Coluna {c}'))
print()
print(f'{matriz[0][0]}', f'{matriz[0][1]}', f'{matriz[0][2]}')
print(f'{matriz[0][3]}', f'{matriz[0][4]}', f'{matriz[1][0]}')
print(f'{matriz[1][1]}', f'{matriz[1][2]}', f'{matriz[1][3]}')
print(f'{matriz[1][4]}', f'{matriz[2][0]}', f'{matriz[2][1]}')
print(f'{matriz[2][2]}', f'{matriz[2][3]}', f'{matriz[2][4]}')
print()
print(f'Soma dos numeros da primeira linha: {matriz[0][0] + matriz[0][1] + matriz[0][2]}')
print(f'Soma dos numeros da primeira linha: {matriz[0][3] + matriz[0][4] + matriz[1][0]}')
print(f'Soma dos numeros da primeira linha: {matriz[1][1] + matriz[1][2] + matriz[1][3]}')
print(f'Soma dos numeros da primeira linha: {matriz[1][4] + matriz[2][0] + matriz[2][1]}')
print(f'Soma dos numeros da primeira linha: {matriz[2][2] + matriz[2][3] + matriz[2][4]}')
| false |
98af71260debdb1435845afefa1dc166ea4301d3 | anabeatrizzz/exercicios-pa-python | /exercicios_1/exercicios_1_10.py | 484 | 4.125 | 4 | # Escreva um programa que calcule a expressão lógica, sendo que o usuário deverá informar os valores (números inteiros)
# para as variáveis.
# ((X >= Y) AND (Z <=X)) OR ((X == W) AND (Y == Z)) OR (NOT(X != W))
X = int(input("Informe um valor para X: "))
Y = int(input("Informe um valor para Y: "))
Z = int(input("Informe um valor para Z: "))
W = int(input("Informe um valor para W: "))
conta = ((X >= Y) and (Z <= X)) or ((X == W) and (Y == Z)) or (not(X != W))
print(conta)
| false |
38aa843a83904894f86e1c447fcdb138b281a370 | luckeyme74/tuples | /tuples_practice.py | 2,274 | 4.40625 | 4 | # 12.1
# Create a tuple filled with 5 numbers assign it to the variable n
n = ('2', '4', '6', '8', '10')
# the ( ) are optional
# Create a tuple named tup using the tuple function
tup = tuple()
# Create a tuple named first and pass it your first name
first = tuple('Jenny',)
# print the first letter of the first tuple by using an index
print first[0]
# print the last two letters of the first tuple by using the slice operator (remember last letters means use
# a negative number)
print first[3:]
# 12.2
# Given the following code, swap the variables then print the variables
var1 = tuple("hey")
var2 = tuple("you")
var1, var2 = var2, var1
print var1
print var2
# Split the following into month, day, year, then print the month, day and year
date = 'Jan 15 2016'
month, day, year = date.split(' ')
print month
print day
print year
# 12.3
# pass the function divmod two values and store the result in the var answer, print answer
answer = divmod(9, 2)
print answer
# 12.4
# create a tuple t4 that has the values 7 and 5 in it, then use the scatter parameter to pass
# t4 into divmod and print the results
t4 = (7, 5)
result = divmod(*t4)
print result
# 12.5
# zip together your first and last names and store in the variable zipped
# print the result
first = "Jenny"
last = "Murphy"
zipped = zip(first, last)
print zipped
# 12.6
# Store a list of tuples in pairs for six months and their order (name the var months): [('Jan', 1), ('Feb', 2), etc
months = [('October', 10), ('January', 1), ('March', 3), ('May', 5), ('July', 7), ('December', 12)]
# create a dictionary from months, name the dictionary month_dict then print it
month_dict = dict(months)
print month_dict
# 12.7
# From your book:
def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
return res
# Create a list of words named my_words that includes at least 5 words and test the code above
# Print your result
my_words = ('hacienda', 'empathetic', 'harmonious', 'allegorical', 'totalitarianism', 'harpsichord', 'embellishment', 'lassitude', 'mysticism')
print sort_by_length(my_words)
| true |
abe6186dcccda09293dd055eb09cbb0c24de9a93 | saidaHF/InitiationToPython | /exercises/converter2.py | 1,031 | 4.15625 | 4 | #!/usr/bin/env python
# solution by cpascual@cells.es
"""
Exercise: converter2
---------------------
Same as exercise converter1 but this time you need to parse the header
to obtain the values for the gain and the offset from there.
Also, you cannot assume that the header has just 3 lines or that the order
of the items in the header is always the same.
In summary: you know that the "gain" is the number just after the word "GAIN"
and the offset is the number after word "OFFSET". You also know that the word
"DATA" marks the end of the header and that after it it comes the channels
data.
If possible, try not to use `for i in len(range(...))`. Use "enumerate" and
"zip" instead.
Note: call the output of this program "converter2.dat", and compare it
(visually) with "converted1.dat"
Important: do not import modules. Do it with the basic python built-in
functions.
Tips:
- see tips of exercise converter1 and also
- note that you can find elements in a list using the .index() method of a list
"""
# Write your solution here
| true |
e1be8a6391e8d69d9906b8712357a171952493c4 | mauricejenkins-00/Python-Challenge | /pypoll/main2.py | 2,486 | 4.34375 | 4 | #Import libraries os, and Csv
import os
import csv
#Give canidates a variable to add the canidates and vote count to
candidates = {}
#election_csv is a variable that calls for the election data file in the resources folder
election_csv = os.path.join('.','Resources','election_data.csv')
#With statement opens the election_csv variable as csvfile and is set to read mode
with open(election_csv, 'r') as csvfile:
#csvreader is a variable set to opening the csv file and reading each row of data
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader) #The header variable is set to equal the next object in each column
#For loop is used to input data into spots in the dictionary we started earlier in the program called candidates
for row in csvreader:
if row[2] in candidates.keys():
candidates[row[2]]+=1
else: #If no value is returned then it sets the value to default
candidates[row[2]] = 1
#Sets the total candidates value equal to total so we can call for it later
total = candidates.values()
#Sets the variable total_votes equal to the sum of candidates value
total_votes = sum(total)
#List_candidates is just the dictionary keywords
list_candidates = candidates.keys()
#Here a variable is set equal to the equation used to calculate the votes per candidate
votes_per = [f'{(x/total_votes)*100:.3f}%' for x in candidates.values()]
#Winner is a variable set equal to whoever has the highest amount of votes saved to the dictionary and prints it
winner = list(candidates.keys())[list(candidates.values()).index(max(candidates.values()))]
winner
#Prints the final results to the terminal
#Extra print statements are used to space out the output in the terminal
print("Election results")
print("--------------------------------")
print(f" Total votes: {int(total_votes)}")
print("---------------------------------")
i = 0
#For loop runs for candidate votes and goes for the length of all the candidate items
#Prints the candidate name, the vote count, and the vote percentage they received
for candidate, vote in candidates.items():
print(f'{candidate}, {vote} , {votes_per[i]}')
i+=1
#Prints the final result of who won the election
print("------------------------------")
print(f" Winner: {winner}")
print("------------------------------")
| true |
1c4c1304afa4fb8619848032eafba93110c4eb19 | jackmar31/week_2 | /parkingGarage/# Best Case: O(n) - Linear.py | 901 | 4.28125 | 4 | # Best Case: O(n) - Linear
def swap(i,j, array):
array[i],array[j] = array[j],array[i]
def bubbleSort(array):
# initially define isSorted as False so we can
# execute the while loop
isSorted = False
# while the list is not sorted, repeat the following:
while not isSorted:
# assume the list is sorted
isSorted = True
# crawl along the list from the beginning to the end
for num in range(len(array) - 1):
# if the item on the left is greater
# than the item on the right
if array[num] > array[num + 1]:
# swap them so the greater item goes on the right
swap(num, num + 1, array)
# because we had to make the swap,
# the list must not have been sorted
isSorted = False
return array
bubbleSort([22,55,88,44,1,100,34,66]) | true |
9c3a48801a65a13415cb5f4ff705facfb5bf2469 | cleitonPiccini/calculo_numerico | /metodo_newton.py | 797 | 4.34375 | 4 | #python 3
#Cleiton Piccini
#Algoritmo do metódo de Newton para encontrar raizes de funções.
import math
# Função
def funcao (x):
#x = (x / (math.e**(10*x))) - (1 / (math.e ** 5))
x = math.cos(50 * x + 10) - math.sin(50 * x - 10)
return x
# Derivada da Função
def derivada (x):
#x = (math.e**(-10*x)) * (1 - 10 * x)
x = -50 * (math.sin(50 * x + 10) + math.cos(50 * x - 10))
return x
# Metodo de Newton
def newton(x, i, erro):
#
i = i + 1
x_funcao = funcao (x)
x_derivada = derivada (x)
x_novo = x - (x_funcao / x_derivada)
#
if abs((x_novo - x) / x_novo) < erro or x_derivada == 0.0:
print("Iterações = ",i)
return x_novo
else :
return newton (x_novo, i, erro)
#
'''_Main_'''
i = 0
x = -0.5
erro = 0.0000000001
x = newton (x, i, erro)
print("Raiz = ",x) | false |
06ea29eec33fe7ef9b2254a7b3fcd28b33bd6a60 | simgroenewald/StringDataType | /Manipulation.py | 869 | 4.34375 | 4 | # Compulsory Task 3
strManip = input("Please enter a sentence:")#Declaring the variable
StrLength = len(strManip)#Storing the length of the sentence as a variable
print(StrLength)# Printing the length of the sentence
LastLetter = strManip[StrLength-1:StrLength] #Storing the last letter of the lentence as a variable
print(strManip.replace(LastLetter,"@"))#Replacing all of the letters that are the same as last letter with the @ symbol
print(strManip[StrLength:StrLength-4:-1])#Printing the last 3 letter using the length of the string as the letters positions
print(strManip[0:3]+ strManip[StrLength-2:StrLength]) #Slicing the string and concatenating the sliced pieces together
print(strManip.replace(" ","\n"))#Replacing all of the spaces with the backslash (there is no backslash on my keyboard so I had to copy it - please help)n to put in new lines
| true |
3695661c954293f8c27fd7f1ea75e22e4003c377 | ulicqeldroma/MLPython | /basic_slicing.py | 696 | 4.15625 | 4 | import numpy as np
x = np.array([5, 6, 7, 8, 9])
print x[1:7:2]
"""Negative k makes stepping go toward smaller indices. Negative i and j are
interpreted as n + i and n + j where n is the number of elements in the
corresponding dimension."""
print x[-2:5]
print x[-1:1:-1]
"""If n is the number of items in the dimension being sliced. Then if i is not
given then it defaults to 0 for k > 0 and n - 1 for k < 0. If j is not given
it defaults to n for k > 0 and -1 for k < 0. If k is not given it defaults
to 1. Note that :: is the same as : and means select all indices along this
axis."""
print x[4:]
"""(root) G:\MachineLearning\Python\book>python basic_slicing.py
[6 8]
[8 9]
[9 8 7]
[9]""" | true |
5a30f84ddc0999fc6ad5f6c964eb18447ffba7a3 | tenedor/SourceFlowPlotter | /tracers/test.py | 401 | 4.15625 | 4 | def double(x):
x *= 2
return x
def triple(x):
x += double(x)
return x
def recursive_1(x, i):
if i > 0:
x += i
x = recursive_2(x, i - 1)
return x
def recursive_2(x, i):
if i > 0:
x *= i
x = recursive_1(x, i - 1)
return x
def recursive_start(n):
m = recursive_1(1, n)
print m
if __name__ == '__main__':
print triple(10)
print triple(20)
recursive_start(5)
| false |
da2a27e14b2e98b13c25310fea2ea62af5f9e07c | JIANG09/LearnPythonTheHardWay | /ex33practice.py | 354 | 4.125 | 4 | def while_function(x, j):
i = 0
numbers = []
while i < j:
print(f"At the top i is {i}")
numbers.append(i)
i = i + x
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
return numbers
numbers_1 = while_function(7, 10)
print("The numbers: ")
for num in numbers_1:
print(num)
| true |
620a67cbe340ace45f2db953d28b110f9fb0ac3d | timwilson/base30 | /base30/base30.py | 2,528 | 4.4375 | 4 | #!/usr/bin/env python3
"""
This module provides two functions: dec_to_b30 and b30_to_dec
The purpose of those functions is to convert between regular decimal
numbers and a version of a base30 system that excludes vowels and other
letters than may be mistaken for numerals. This is useful for encoding large
numbers in a more compact format while reducing the likelihood of errors
while typing the base30-encoded version.
The base30 digits include 0-9 and the letters BCDFGHJKLMNPQRSTVWXZ
"""
class Error(Exception):
"""Base class for other exceptions"""
pass
class NumberInputError(Error):
"""Raised when the input value is a float"""
pass
class ImproperBase30FormatError(Error):
"""Raised when the input value contains letters that aren't allowed in the base30 specification"""
pass
values = "0123456789BCDFGHJKLMNPQRSTVWXZ"
digit_value_dict = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"B": 10,
"C": 11,
"D": 12,
"F": 13,
"G": 14,
"H": 15,
"J": 16,
"K": 17,
"L": 18,
"M": 19,
"N": 20,
"P": 21,
"Q": 22,
"R": 23,
"S": 24,
"T": 25,
"V": 26,
"W": 27,
"X": 28,
"Z": 29,
}
def dec_to_b30(num):
"""Given a decimal number, return the base30-encoded equivalent."""
base_num = ""
# Make sure the function received an integer as input
try:
if isinstance(num, float):
raise NumberInputError
num = int(num)
except (ValueError, NumberInputError):
print("Must provide an integer to convert.")
else:
while num > 0:
digit = int(num % 30)
if digit < 10:
base_num += str(digit)
else:
base_num += values[digit]
num //= 30
base_num = base_num[::-1]
return base_num
def b30_to_dec(num):
"""Given a base30-encoded number, return the decimal equivalent."""
# Make sure the function received a base30 number that doesn't include any illegal characters
try:
num = str(num)
for c in num:
if c not in values:
raise ImproperBase30FormatError
except ImproperBase30FormatError:
print(f"Invalid base30 format. My only contain {values}.")
else:
dec_num = 0
rev_num = num[::-1]
for i in range(len(rev_num)):
dec_num += digit_value_dict[rev_num[i]] * (30 ** i)
return dec_num
| true |
400b14f32ee96af63ee8fbf4c750443ec51c1532 | hamk-webdev-intip19x6/petrikuittinen_assignments | /lesson_python_basics/side_effect.py | 629 | 4.375 | 4 | # WARNING! DO NOT PROGRAM LIKE THIS
# THE FOLLOWING FUNCTION HAS AN UNDOCUMENTED SIDE EFFECT
def mymax(a):
"""Return the item of list a, which has the highest value"""
a.sort() # sort in ascending order
return a[-1] # return the last item
a = [1, 10, 5, -3, 7]
print(mymax(a))
print(a) # a is sorted as well!
# This version does NOT have a side effect
def mymax2(a):
"""Return the item of list a, which has the highest value"""
b = a.copy()
b.sort() # sort in ascending order
return b[-1] # return the last item
a = [1, 10, 5, -3, 7]
print(mymax2(a))
print(a) # a is still in original order | true |
cfb4d5c4bfeeb729969a5cd3169d09ee8c63e079 | hamk-webdev-intip19x6/petrikuittinen_assignments | /lesson_python_file_and_web/typing_hints.py | 779 | 4.125 | 4 | from typing import List, Dict, Tuple, Union, Any
def square(x: float) -> float:
return x*x
def is_negative(x: float) -> bool:
return x < 0
def print_many(s: Union[str, int, float], n: int = 5) -> None:
for i in range(n):
print(s)
def multiply_list(a: List[float], n: float) -> List[float]:
return [n*i for i in a]
a : List[str]
a = ["cat", 2]
print(square(9))
#print(square("bug"))
d: Dict[str, Any] = {"key": "value", "key2": ("tuple", ), "key3": 13}
print("We got so far")
#d[123] = "bug"
print(is_negative(4))
#print(is_negative("bug"))
print_many(5)
print_many("Hello")
print_many("two", 2)
#print_many("bug", 3.5)
print(multiply_list([1, 2.5, 3], 2.5))
#print(multiply_list([1, "bug", 3.14], 5))
#print(multiply_list([1, "cat", 3.14], "bug"))
| false |
047fe4c0903be5318f414cff2ce4fbb295768f58 | hamk-webdev-intip19x6/petrikuittinen_assignments | /lesson_python_file_and_web/ask_float_safely.py | 533 | 4.15625 | 4 | def ask_float(question):
"""display the question string and wait for standard input
keep asking the question until user provides a valid floating
point number. Return the number"""
while True:
try:
return float(input(question))
except ValueError:
print("Please give a valid floating point number")
def lbs_to_kg(lbs):
"""Convert pounds (lbs) to kilograms (kg)"""
return lbs * 0.45359237
lbs = ask_float("How many pounds (lbs) ?")
print(f"{lbs_to_kg(lbs):.2f} kg")
| true |
8b3498cef391bc920ca5d9db2966bd3cbe71bcfd | hamk-webdev-intip19x6/petrikuittinen_assignments | /lesson_python_basics/closure.py | 322 | 4.21875 | 4 | # Example of a closure
def make_multiplier(x): # outer / enclosing function
def multiplier(y): # inner / nested function
return x*y
return multiplier
mul10 = make_multiplier(10) # mul is the closure function
print(mul10(5)) # 50
print(mul10(10)) #100
mul2 = make_multiplier(2)
print(mul2(10)) # 20
| true |
f162f9720be4566474fcd6e09731c5f43a727059 | sterlingb1204/EOC2 | /HW4.py | 998 | 4.5 | 4 | #-- Part 2: Python and SQLite (25 Points)
#--
#-- Take your Homework 1, Part 1 module and re-write
#-- it to so that it queries against the sqlite3
#-- babynames database instead.
#--
#-- The beauty of this approach is that, because
#-- your original code was in a module, you can
#-- change how the module fulfills the `get_frequency()`
#-- function request, and all of the scripts that you
#-- wrote that use your module will benefit from
#-- the improvements!
#--
#-- You can test your module by running your Homework
#-- 1, parts 2 and 3 scripts, and see if you observe
#-- an improvement in the speed of the scripts!
#------------------------------------------------
import babynames1
print("The Fantastic Four!")
print("-" * 19)
names = {name: sum(babynames1.get_frequency(name).values()) for name in ["Reed", "Susan", "Ben", "Johnny"]}
for name, count in names.items():
print(f"{name:>7}: {count:>9,}")
print("pynames")
print(f"\n{max(names, key=names.get)} is the most popular!") | true |
e37de75b4b15d71da1d709b52889d49cbef78bd8 | volodiny71299/Right-Angled-Triangle | /02_number_checker.py | 1,010 | 4.3125 | 4 | # number checker
# check for valid numbers in a certain range of values
# allow float
def num_check(question, error, low, high, num_type):
valid = False
while not valid:
try:
response = num_type(input(question))
if low < response < high:
return response
else:
print(error)
except ValueError:
print(error)
# main routine goes here
get_angle = num_check("What is the value of the angle ", "Enter a value between 0 and 90\n", 0, 90, float)
# get the length of a side (used the float('inf') to represent an infinite integer, doesn't have a max restriction)
get_length = num_check("What is the length of one side ", "Enter a value greater than 0\n", 0, float('inf'), float)
# calculate the second angle (can be used for overall data for end results)
angle_two = 90 - get_angle
print()
# prints results of input
print("Angle one: {:.3f}".format(get_angle))
print("Angle two: {:.3f}".format(angle_two))
| true |
2571fb011cab5aed53fa2d7a10bb66470982bbf9 | volodiny71299/Right-Angled-Triangle | /01_ask_what_calculate.py | 962 | 4.40625 | 4 | # ask user what they are trying to calculate (right angled triangle)
valid_calculations = [
["angle", "an"],
["short side", "ss"],
["hypotenuse", "h"],
["area", "ar"],
["perimeter", "p"]
]
calculation_ok = ""
calculation = ""
for item in range(0,3):
# ask user for what they are trying to calculate
what_to_calculate = input("What do you want to calculate? ".lower())
for var_list in valid_calculations:
# if the calculation is in list
if what_to_calculate in var_list:
# get full name of what is needed to be calculated
calculation = var_list[0].title()
calculation_ok = "yes"
break
# # if the chosen calculation is not valid ask again
else:
calculation_ok = "no"
# print option again
if calculation_ok == "yes":
print("You want to calculate '{}'".format(calculation))
else:
print("Invalid choice")
| true |
8f24a35c4ff8b1ebbb4e476e7ac6dd74d4a652dc | pjarcher913/python-challenges | /src/fibonacci/module.py | 1,020 | 4.15625 | 4 | # Created by Patrick Archer on 29 July 2019 at 9:00 AM.
# Copyright to the above author. All rights reserved.
"""
@file asks the user how many Fibonacci numbers to generate and then generates them
"""
"""========== IMPORTS =========="""
"""========== GLOBAL VARS =========="""
"""========== MAIN() =========="""
def fib():
print("\nThis app generates a sequence of Fibonacci numbers for a specified range.\n")
seqLength = input("How many numbers would you like to generate?\n")
print("\nResulting sequence:")
print(str(fibGen(int(seqLength))))
"""========== ADDITIONAL FUNCTIONS =========="""
def fibGen(seqLength):
fibSeq = []
for index in range(0, seqLength):
if index == 0:
fibSeq.append(0)
elif index == 1:
fibSeq.append(1)
else:
fibSeq.append(fibSeq[index - 2] + fibSeq[index - 1])
return fibSeq
"""========== \/ SCOPE \/ =========="""
if __name__ == '__fib__':
fib()
"""========== \/ @file END \/ =========="""
| true |
cfc949e732347cebc4b073cc891826075cb9520e | julianvalerio/ExemploPython | /Listas/Listas.py | 1,817 | 4.1875 | 4 | import copy
#lista de listas ou matrizes
notas = [['nota1', 'nota2', 'nota3'], [7, 8.2, 6]]
print(notas[0][1],notas[1][1])
#uso do for#
nomes = ['julian', 'rodrigues', 'valerio']
#for i in ['julian', 'rodrigues', 'valerio']
for i in range(len(nomes)):
print('Indice '+str(i)+ ' descrição ' + nomes[i])
#dessa forma conseguimos percorrer toda lista
#o tamanho da lista é descoberto através da função len
#encontrar valor em uma lista utilizando métodos, metodos utilizam valores quando são chamados
print(nomes.index('rodrigues'))
nomes.append('marta')
#nomes.insert(2,'pedro')
print(nomes)
#insert insere o elemento em qualquer posição da lista, necessário indice
nomes.insert(2,'pedro')
print(nomes)
#removendo com del ou remove
del nomes[-1]
nomes.remove('pedro')
print(nomes)
#exercício: crie uma lista frutas em seguida crie uma função que receba a lista e imprima
#todos seus valores separados por vírgula e que o último valor será separado por e
#ordenando os valores da lista sort
#não funciona com listas heterogêneas
nomes.insert(0,'Pedro')
nomes.sort(reverse=True)
print(nomes)
#padrão de ordenação ASCII
nomes.append('Julian')
nomes.sort(key=str.lower)
print(nomes)
#tipo tuple, semelhante a lista mas não pode ser modificado
tupla=('julian',)
print(tupla[0])
#atribuição por referência
disc = 'matematica'
cad = disc
print(cad)
disciplinas = ['programação', 'Banco de dados', 'ED', 'ihc']
cadeiras = disciplinas
cadeiras[0]='4º semestre'
print(disciplinas)
cadeiras.insert(1,'programação')
print(cadeiras)
#python utiliza referências sempre que os valores são mutáveis
#função copy
#permite copiar ou duplicar uma lista
materias = copy.copy(disciplinas)
print(materias)
materias.append('python')
print(materias)
print(disciplinas) | false |
c4cccf258eab393d27882e0e80b006df10784546 | phu-n-tran/LeetCode | /monthlyChallenge/2020-05(mayChallenge)/5_02_jewelsAndStones.py | 1,349 | 4.15625 | 4 | # --------------------------------------------------------------------------
# Name: Jewels and Stones
# Author(s): Phu Tran
# --------------------------------------------------------------------------
"""
You're given strings J representing the types of stones that are jewels,
and S representing the stones you have. Each character in S is a type
of stone you have. You want to know how many of the stones you have are
also jewels.
The letters in J are guaranteed distinct, and all characters in J and S
are letters. Letters are case sensitive, so "a" is considered a different
type of stone from "A".
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.
Hint: For each stone, check if it is a jewel.
"""
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
sum_jewel = 0
for each_jewel in J:
sum_jewel += S.count(each_jewel)
return sum_jewel
'''###alternate solution###
setJ = set(J)
return sum(s in setJ for s in S)
'''
| true |
0482288b53ef2ee63980d4d388ae8dc7d9b6ae7f | phu-n-tran/LeetCode | /monthlyChallenge/2020-06(juneChallenge)/6_29_UniquePaths.py | 2,214 | 4.5 | 4 | # --------------------------------------------------------------------------
# Name: Unique Paths
# Author(s): Phu Tran
# --------------------------------------------------------------------------
"""
A robot is located at the top-left corner of a m x n grid
(marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid
(marked 'Finish' in the diagram below).
How many possible unique paths are there?
(see 6_29_illustration.png)
Above is a 7 x 3 grid. How many possible unique paths are there?
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
Constraints:
1. 1 <= m, n <= 100
2. It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.
"""
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
# each block represent the current coordinate and its value represent the number of ways to move from origin to the current coordinate
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
'''other faster methods (from other submissions)
##################################################
def binom(n, k):
"""n choose k, i.e. n! / (k! (n-k)!)"""
result = 1
for i in range(k+1, n+1):
result *= i
for i in range(1, n-k+1):
result /= i
return result
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
return binom((m-1)+(n-1), n-1)
##################################################
'''
| true |
68cb6a414b42c04874e1a204a7bd2ffd16f3dba9 | phu-n-tran/LeetCode | /monthlyChallenge/2020-07(julychallenge)/7_02_BTLevelOrderTraversal2.py | 2,801 | 4.21875 | 4 | # --------------------------------------------------------------------------
# Name: Binary Tree Level Order Traversal II
# Author(s): Phu Tran
# --------------------------------------------------------------------------
"""
Given a binary tree, return the bottom-up level order traversal of its
nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def bottomUp(root, result, level):
if root:
if len(result) <= level:
result.append([])
result[level] += [root.val]
bottomUp(root.left, result, level+1)
bottomUp(root.right, result, level+1)
result = []
bottomUp(root, result, 0)
return result[::-1]
'''other faster methods (from other submissions)
##################################################
def levelOrderBottom(self, root):
if not root:
return []
prev = [root]
ret = []
while prev:
ret.append([n.val for n in prev])
curr = []
for node in prev:
if node.left:
curr.append(node.left)
if node.right:
curr.append(node.right)
prev = curr
return list(reversed(ret))
##################################################
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
if not root:
return res
queue = [root]
level=0
while queue:
node = [nod for nod in queue]
temp =[]
res.append([nod.val for nod in node])
for nod in node:
if nod.left:
temp.append(nod.left)
if nod.right:
temp.append(nod.right)
queue = temp
level+=1
return res[::-1]
##################################################
'''
| true |
5b5cda38002926df07c4809361992ba67ed62c2a | phu-n-tran/LeetCode | /monthlyChallenge/2020-06(juneChallenge)/6_18_HIndex_V2.py | 2,119 | 4.25 | 4 | # --------------------------------------------------------------------------
# Name: H-Index II
# Author(s): Phu Tran
# --------------------------------------------------------------------------
"""
Given an array of citations sorted in ascending order (each citation is
a non-negative integer) of a researcher, write a function to compute the
researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has
index h if h of his/her N papers have at least h citations each, and the
other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total
and each of them had received 0, 1, 3, 5, 6 citations
respectively. Since the researcher has 3 papers with at
least 3 citations each and the remaining two with no more
than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken
as the h-index.
Follow up:
1. This is a follow up problem to H-Index, where citations is now guaranteed
to be sorted in ascending order.
2. Could you solve it in logarithmic time complexity?
"""
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
l=len(citations)
res=0
for i in range(l):
if citations[l-i-1]>=(res+1):res+=1
else:return res
return res
'''other methods (from other submissions)
##################################################
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n = len(citations)
if n == 0:
return 0
#citations.sort(reverse = True)
for i in range(n):
if citations[n - 1 - i] <= i:
return i
return n
'''
| true |
862417cfb9e359619f04610c0a1ee27492e43ddc | phu-n-tran/LeetCode | /monthlyChallenge/2020-06(juneChallenge)/6_13_LargestDivisibleSubset.py | 2,169 | 4.15625 | 4 | # --------------------------------------------------------------------------
# Name: Largest Divisible Subset
# Author(s): Phu Tran
# --------------------------------------------------------------------------
"""
Given a set of distinct positive integers, find the largest subset such
that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:
Input: [1,2,4,8]
Output: [1,2,4,8]
"""
class Solution(object):
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if nums:
nums.sort()
results = [[each_ele] for each_ele in nums]
for i in range(len(nums)):
for k in range(i):
# 1st cond is to check if the current number divisible by all the small number
# 2nd cond is to make sure the iterate number is also divisible by other numbers in the list
if nums[i] % nums[k] == 0 and len(results[i]) <= len(results[k]):
results[i] += [nums[k]]
print(results)
# return max(results, key=len)
return max(results, key=lambda each_list: len(each_list))
'''other methods (from other submissions)
##################################################
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
dic = {}
for i in sorted(nums):
a = [(k,len(dic[k])) for k in dic if i%k==0]
#print(dic)
if a:
dic[i]=dic[max(a,key=lambda x:x[1])[0]]+[i]
else:
dic[i]=[i]
#print(dic)
return max(dic.items(), key=lambda x:len(x[1]))[1]
'''
| true |
cb8cb4431ddc8182c23adff86c9e3f1b21d1f63c | mily-chan/scripts-python | /calculadora.py | 500 | 4.1875 | 4 | def calculadora(n1, n2, operador):
if operador == '+':
print( n1 + n2)
elif operador == '-':
print( n1 - n2)
elif operador == '*':
print(n1 * n2)
else:
print( n1 / n2)
n1 = int(input("Digite um número: "))
while True:
operador= input("Digite o operador válido (+, -, *, /): ")
if operador == '+' or operador == '-' or operador == '*' or operador == '/':
break
n2 = int(input("Digite outro número: "))
calculadora(n1, n2, operador)
| false |
890540caa1d454ce7c0d7dd0944d8fde13ed3193 | aernesto24/Python-el-practices | /Basic/Python-university/Functions/ArithmeticTables/arithmeticTables.py | 2,650 | 4.46875 | 4 | """This software shows the arithmetic tables based on the input the user provides, it can show:
multiplication table, sum tablet, etc. """
#Function to provide the multiplication table from 0 to 10
def multiplicationTables(LIMIT, number):
counter = 0
print("Tabla de multiplicar de " + str(number))
for i in range(LIMIT+1):
result = number * counter
print(str(number) + " * " + str(counter)+ " = " + str(result))
counter +=1
#Function to provide the division table from 1 to 10
def divisionTables(LIMIT, number):
counter = 1
print("Tabla de dividir de " + str(number))
for i in range(LIMIT+1):
result = round(number / counter, 2)
print(str(number) + " / " + str(counter)+ " = " + str(result))
counter +=1
#Function to provide the sum table from 0 to 10
def sumTables(LIMIT, number):
counter = 0
print("Tabla de sumar de " + str(number))
for i in range(LIMIT+1):
result = number + counter
print(str(number) + " + " + str(counter)+ " = " + str(result))
counter +=1
#Function to provide the substraction table from 0 to 10
def substrationTables(LIMIT, number):
counter = 0
print("Tabla de restar de " + str(number))
for i in range(LIMIT+1):
result = number - counter
print(str(number) + " - " + str(counter)+ " = " + str(result))
counter +=1
#Run function, here are declared the LIMIT constant and request user input for the number and option
def run():
print("***TABLAS DE SUMA | RESTA | MULTIPLICACION | DIVISION***")
LIMIT = 10
number = int(input("Ingresa el numero para conocer su tabla: "))
option = input("""Selecciona la opcion que quieres:
1. Tabla de multiplicacion
2. Tabla de division
3. Tabla de suma
4. Tabla de resta
5. Mostrar todas las tablas
: """)
if option == '1':
multiplicationTables(LIMIT, number)
elif option == '2':
divisionTables(LIMIT, number)
elif option == '3':
sumTables(LIMIT, number)
elif option == '4':
substrationTables(LIMIT, number)
elif option == '5':
multiplicationTables(LIMIT, number)
print("")
divisionTables(LIMIT, number)
print("")
multiplicationTables(LIMIT, number)
print("")
sumTables(LIMIT, number)
print("")
substrationTables(LIMIT, number)
else:
print("Opción invalida!!")
if __name__ == '__main__':
run() | true |
15a69ecb35cec652121faaf582966f25ea7dad8b | gaoyangthu/leetcode-solutions | /004-median-of-two-sorted-arrays/median_of_two_sorted_arrays.py | 1,815 | 4.28125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
"""
class Solution(object):
def find_kth(self, nums1, nums2, k):
if not nums1:
return nums2[k - 1]
if not nums2:
return nums1[k - 1]
if k == 1:
return min(nums1[0], nums2[0])
m = nums1[k / 2 - 1] if len(nums1) >= k / 2 else None
n = nums2[k / 2 - 1] if len(nums2) >= k / 2 else None
if n is None or (m is not None and m < n):
return self.find_kth(nums1[k / 2:], nums2, k - k / 2)
else:
return self.find_kth(nums1, nums2[k / 2:], k - k / 2)
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
l = len(nums1) + len(nums2)
if l % 2 == 1:
return self.find_kth(nums1, nums2, l / 2 + 1)
else:
return (self.find_kth(nums1, nums2, l / 2) + self.find_kth(nums1, nums2, l / 2 + 1)) / 2.0
def test():
solution = Solution()
print solution.findMedianSortedArrays([1, 2], [1, 2, 3])
print solution.findMedianSortedArrays([1, 2], [1, 2])
print solution.findMedianSortedArrays([1, 2], [3])
print solution.findMedianSortedArrays([1], [2, 3])
print solution.findMedianSortedArrays([4], [1, 2, 3, 5, 6])
print solution.findMedianSortedArrays([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22], [0, 6])
if __name__ == '__main__':
test()
| true |
3153c6df49836cc64a8b4cf94a57c9bcf1b30927 | dgibbs11a2b/Module-9-Lab-Assignment | /Problem2NumList10.py | 711 | 4.1875 | 4 | #----------------------------------------
#David Gibbs
#March 10, 2020
#
#This program will use a while loop to append the current
#value of the current counter variable to the list and
#then increase the counter by 1. The while loop then stops
#once the counter value is greater than 10.
#----------------------------------------
l = [0,1,2,3,4,5,6,7,8,9,10]
counter_value = 0
#sets counter value
counter_max = 10
#sets counter maximum
while counter_value <= counter_max:
l.append(counter_value)
counter_value += 1
#while statement which appens incremented counter values to list "l"
print('The updated list is: ', l)
#Updated List
#x = 0
#L = []
#while x < 11:
# L.append(x)
# x += 1
#print(L)
| true |
6efd4db15c5bd72c01c320701715f3845ca25b4c | wanglun0318/pythonProject | /register.py | 1,587 | 4.15625 | 4 | # 注册新用户
def new_user():
username = input("请输入用户名:")
while username in accounts:
username = input("此用户名已经被使用请重新输入:")
else:
accounts[username] = input("请输入你的密码:")
print("注册成功,赶紧试试登录吧!")
# 用户登录
def old_user():
username = input("请输入用户名:")
while username not in accounts:
print("您输入的帐号或者密码错误!")
username = input("请输入用户名:")
else:
password = input("请输入你的密码:")
while password != accounts[username]:
print("您输入的帐号或者密码错误!")
password = input("请输入你的密码:")
else:
print("欢迎登录XXOO系统!!!")
print("|--- 新建用户:N/n ---|")
print("|--- 登录帐号:E/e ---|")
print("|--- 退出程序:Q/q ---|")
contacts = input("|--- 请输入指令代码:")
accounts = dict()
while contacts not in "NnEeQq":
contacts = input("您输入的指令错误,请重新输入:")
else:
while contacts not in "Qq":
if contacts == "N" or contacts == "n":
new_user()
print(accounts)
contacts = input("如您还想其他操作,请重新输入指令:")
elif contacts == "E" or contacts == "e":
old_user()
contacts = input("如您还想其他操作,请重新输入指令:")
else:
print("再见!真想下次早点见到你呢!!!")
exit() | false |
4764110d5c381f3322608d31b9498f87139a3d8d | wanglun0318/pythonProject | /mageic/iteratortest.py | 1,071 | 4.1875 | 4 | """
迭代是重复反馈过程的活动,其目的通常是为了接近并到达所需的目标或结果。每一次对过程的重复
被称为异常“迭代”,而每一次迭代得到的结果会被用来作为下一次的迭代的初始值
迭代器就是实现了__next__()方法的对象,用于遍历容器中的数据
__iter__(self) 定义当迭代容器中的元素的行为
__next__() 让对象可以通过next(实例名)访问下一个元素
"""
import datetime as dt
class LeapYear:
def __init__(self):
self.now = dt.date.today().year # 获取当前年份
def isLeapYear(self, year):
if(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
def __iter__(self):
return self
def __next__(self):
while not self.isLeapYear(self.now):
self.now -= 1
temp = self.now
self.now -= 1
return temp
leapYears = LeapYear()
for i in leapYears:
if i >= 2000:
print(i)
else:
break
| false |
84cce619cee66ec68eb13425e3d6c11ef2cb6ec1 | JonasKanuhsa/Python | /Survey/Survey.py | 573 | 4.1875 | 4 | '''
Make a program that can take survey information.
@author: Jonas Kanuhsa
'''
question = "What is your name?"
name = input("What is your name")
print(name)
response = "What is your favorite color?"
color = input("What is your favorite color?")
print(color)
var = = "What city did you grow up in?"
city = input("What city did you grow up in?")
print(city)
var1 = "What is your best friends name?"
variable = input("What is your best friends name?")
print(variable)
var2 = "What color hair do you have?"
hair = input("What color hair do you have?")
print(hair)
| true |
f0345277450b059093e85d4a310eddb279d501ea | MistyLeo12/Learning | /Python/double_linked.py | 1,967 | 4.21875 | 4 |
class Node(object):
def __init__(self, data = None):
self.data = data
self.next = None
self.prev = None
class doublyLinkedList(object):
def __init__(self):
self.root = Node()
self.size = 0
def get_size(self):
current = self.root
counter = 0
while current.next is not None:
counter += 1
current = current.next
return counter
def push(self, data): #Inserts at head of the list
new_node = Node(data)
new_node.next = self.root
new_node.prev = None
if self.root is not None:
self.root.prev = new_node
self.root = new_node
def insert(self, prev, data):
if prev is None: #Checks if prev is NULL
print("Node doesn't exist in the List")
return
new_node = Node(data)
new_node.next = prev.next #point next of new node as next of previous node
prev.next = new_node #next of previous as new node
new_node.prev = prev #make previous as previous of new node
if new_node.next is not Node:
new_node.next.prev = new_node
def append(self, data):
new_node = Node(data)
#traverses list until it reaches the last node
current = self.root
while current.next is not None:
current = current.next
current.next = new_node #changes the next of last
new_node.prev = current #makes the last node the previous node
def returnList(self, node):
elements = []
while node is not None:
elements.append(node.data)
node = node.next
return elements
newList = doublyLinkedList()
newList.append(8)
newList.append(66)
newList.append(77)
print(newList.returnList(newList.root))
newList.push(133)
print(newList.returnList(newList.root))
newList.insert(newList.root.next, 9)
print(newList.returnList(newList.root)) | true |
da11b4c7fdf486d72914db90af4b471bb91709bf | ErickMwazonga/learn_python | /others/mothly_rate.py | 1,097 | 4.1875 | 4 | import locale
# set the locale for use in currency formatting
result = locale.setlocale(locale.LC_ALL, '')
if result == 'C':
locale.setlocale(locale.LC_ALL, 'en_US')
# display a welcome message
print("Welcome to the Future Value Calculator")
# print()
choice = 'Y'
while choice.lower() == 'y':
# get input from the user
monthly_investment = float(input('Enter monthly investment:\t'))
yearly_interest_rate = float(input('Enter yearly interest rate:\t'))
years = int(input('Enter number of years"\t\t'))
# convert yearly values to monthly values
monthly_interest_rate = yearly_interest_rate/12/100
months = years * 12
# calculate the future value
future_value = 0
for i in range(months):
future_value = future_value + monthly_investment
monthly_interest_amount = future_value * monthly_interest_rate
future_value = future_value + monthly_interest_amount
# format and display the result
print('Future value:\t\t\t' + locale.currency(
future_value, grouping=True))
print()
# see if the user wants to continue
choice = input('Continue? (y/n): ')
print()
print('Bye!') | true |
c75f229bf209fb251f09cac3f2c7746a8c834007 | 09-03/Infa | /Exam/UPD/7.py | 591 | 4.125 | 4 | """
Реализовать программу, способную находить наибольший и наименьший элемент в
списке и менять их местами. Список задается с клавиатуры
"""
list = [int(i) for i in input("Введите список чисел через пробел: ").split()]
max_value = max(list)
min_value = min(list)
for n in range(len(list)):
if list[n] == min_value:
list[n] = max_value
elif list[n] == max_value:
list[n] = min_value
print(f"Новый список: {list}")
| false |
85c7222686015f91f512afc68fa49a2d3689f67a | edithclaryn/march | /hobbies.py | 251 | 4.28125 | 4 | """Create a for loop that prompts the user for a hobby 3 times, then appends each one to hobbies."""
hobbies = []
# Add your code below!
for i in range(3):
hobby = input("Enter your hobby: ")
print (hobby)
hobbies.append(hobby)
i += 1 | true |
0a2280f39b0f3bcc6ed11af2df1001813cc342b9 | edithclaryn/march | /battleship.py | 945 | 4.21875 | 4 | """Create a 5 x 5 grid initialized to all 'O's and store it in board.
Use range() to loop 5 times.
Inside the loop, .append() a list containing 5 "O"s to board.
Note that these are capital letter "O" and not zeros."""
board = []
for i in range(0,5):
board.append(["O"]*5)
print (board)
#Use the print command to display the contents of the board list.
"""First, delete your existing print statement.
Then, define a function named print_board with a single argument, board.
Inside the function, write a for loop to iterates through each row in board and print it to the screen.
Call your function with board to make sure it works."""
def print_board(board):
for i in board:
print (i)
print_board(board)
"""to remove commas in the list:
Inside your function, inside your for loop, use " " as the separator to .join the elements of each row."""
def print_board(board):
for row in board:
print (" ".join(row))
print_board(board) | true |
291b9fcbb8a201634e37bc6ffded8ca809404b6e | nahymeee/comp110-21f-workspace | /exercises/ex05/utils.py | 1,120 | 4.125 | 4 | """List utility functions part 2."""
__author__ = "730330561"
def only_evens(first: list[int]) -> list[int]:
"""Gives back a list of only the even numbers."""
i: int = 0
evens: list[int] = []
while i < len(first):
if first[i] % 2 == 0:
evens.append(first[i])
i += 1
return evens
def sub(lista: list[int], first: int, last: int) -> list[int]:
"""Makes a sub list from the original list provided."""
i: int = 0
new: list[int] = []
if len(lista) == 0 or first >= len(lista) or last <= 0:
return new
if last > len(lista):
last = len(lista)
if first <= 0:
first = 0
while i < len(lista):
while first != last:
new.append(lista[first])
first += 1
i += 1
return new
def concat(first: list[int], second: list[int]) -> list[int]:
"""Combines two lists together."""
i: int = 0
both: list[int] = []
while i < len(first):
both.append(first[i])
i += 1
i = 0
while i < len(second):
both.append(second[i])
i += 1
return both
| true |
a5d9456a0bfc97f70d8555b4c9ce4f34c543edb3 | mucheniski/python-exemplos | /exercicios/operacao-matematica.py | 477 | 4.125 | 4 | # Escreva um programa que receba dois números e um sinal, e faça a operação matemática definida pelo sinal.
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
operacao = input("Digite o sinal da operação: ")
calculo = 0
if operacao == "+":
calculo = n1 + n2
elif operacao == "-":
calculo = n1 - n2
elif operacao == "*":
calculo = n1 * n2
elif operacao == "/":
calculo = n1 / n2
print(calculo) | false |
1f23bfe9500c5f4405f3f1ad69e472dd5a755a05 | NickPerez06/Python-miniProjects | /rpsls.py | 1,802 | 4.34375 | 4 | '''
This mini project will create the game rock, paper, scissors,
lizard, spock for your enjoyment.
Author: Nicholas Perez
'''
import random
def name_to_number(name):
'''converts string name to number for rpsls'''
number = 0
if( name == "rock" ):
number = 0
return number
elif ( name == "Spock" ):
number = 1
return number
elif ( name == "paper" ):
number = 2
return number
elif ( name == "lizard" ):
number = 3
return number
elif ( name == "scissors" ):
number = 4
return number
else:
return "This is not one of the choices!"
def number_to_name(number):
'''Converts number to srting name for rpsls game'''
if ( number == 0 ):
return "rock"
elif ( number == 1 ):
return "Spock"
elif ( number == 2 ):
return "paper"
elif ( number == 3 ):
return "lizard"
elif ( number == 4 ):
return "scissors"
else:
return "Error: you must pick a number between 0-4"
def rpsls(player_choice):
'''Main Fucntion for rpsls. Will use helper fucntions listed above'''
print ""
print "Player chooses " + player_choice
player_number = name_to_number(player_choice)
#Below will be the computers choice form 0-4
comp_number = random.randrange(0, 5)
comp_choice = number_to_name(comp_number)
print "Computer chooses " + comp_choice
#Below will determind who wins or if there is a tie
result = (player_number - comp_number) % 5
if ( result == 1 or result == 2 ):
print "Player wins!"
elif ( result == 3 or result == 4 ):
print "Computer wins!"
else:
print "Player and Computer tie!"
# testing code
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
| true |
29bcc76645fbf2a3133fe36f2799a53ac5de279b | MicahJank/Intro-Python-I | /src/16_stretch.py | 1,893 | 4.3125 | 4 | # 3. Write a program to determine if a number, given on the command line, is prime.
# 1. How can you optimize this program?
# 2. Implement [The Sieve of
# Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), one
# of the oldest algorithms known (ca. 200 BC).
import sys
import math
# in order to check if a number is prime i need to find if it has any factors besides 1 and itself - if it does it is not a prime number
# i only need to check the numbers up to the square root of the number being inputted
# i should start my loop at 2 since 1 is not relevant
# First i will need to get the number that the user is inputting into the command line
# sys.args will give me everything that has been inputted on the command line
# I will then need to find the square root of that number - this number will be the last number i need to check in the loop
# I will need to loop starting at 2 all the way until i get to the square root of the number the user inputted
# inside the loop i need to check if the current index in the loop is divisible by the number the user inputted - if it is - then that means the number is not prime
# if i get to the end of the loop and none of the index numbers have been divisible by the number then there is a good chance it is a prime
inputs = sys.argv
number = 0
isPrime = False
def run_program(num):
num = int(num)
print("Running")
sqrt = int(math.sqrt(num))
for factor in range(2, sqrt):
if num % factor == 0:
return False
return True
try:
number = inputs[1]
except:
print("No number inputted - please make sure you are inputting a number into the command line")
else:
print(f"Number inputted: {number}")
isPrime = run_program(number)
print(f"{number} is a prime number" if isPrime == True else f"{number} is not a prime number")
| true |
99bfc65a4a0cffca30b37ff18a129edd81b8b359 | kom50/PythonProject | /Simple Code/Factorial.py | 369 | 4.21875 | 4 | # find factorial using loop
def fact(num): # 1st function
f = 1
for i in range(1, num + 1):
f *= i
return f
# find factorial using recursive function
def fact1(num): # 2nd function
if num == 1:
return 1
return num * fact1(num - 1)
# 1st function
print('Factorial : ', fact(4))
# 2nd function
print('Factorial : ', fact1(4))
| true |
6aa47cd97da9f307b127f9ba7df2b81325f5674b | tlkoo1/Lok.Koo-Chatbot | /ChatBotTemplate.py | 569 | 4.25 | 4 | #open text document stop-words.txt
file = open("stop-words.txt")
stopwords = file.readlines()
#function going through all stopwords
def removeStopwords(firstWord):
for word in stopwords:
next = word.strip()
firstWord = firstWord.replace(" " + next + " ", " " )
return firstWord
#while input matches stop words, no display
while True:
input = raw_input("What is your name ? ")
input = " " + input + " "
filtered = removeStopwords(input);
filtered = filtered.replace(" name "," ")
print("Answer: " + filtered.strip())
| true |
ef6c8b1057839016de9dd2b51ffd879435043270 | martinaobrien/pands-problem-sets | /sumupto.py | 1,128 | 4.28125 | 4 | # Martina O'Brien: 24 - 02 - 2019
# Problem Set Programming and Scripting Code 1
#Calculate the sum of all factorials of positive integer
# Input variable needed for calculation
# Int method returns an integer as per python programming
# input "Enter Number" will be visible on the user interface
# setting up variables to be used later in while loop
start = int (input ('Please enter a positive number: '))
ans = 0
# ans = 0 and 0 is the value that the loop begins calculating
i = 1
if start > 0:
# i = 1 as the starting point
while i <= start:
ans = ans + i
i = i + 1
print(ans)
# Print is the funtion used to display the sum of all factorials of positive integer inputted
# As print is not contained through indentation in the previous statement, it displays one figure as ans
else:
print('This is not a positive number')
# ans will continue to increase by the value of i as it progresses through the while loop
# i will increase by 1 each time it goes through while loop.
# This will continue while the argument is true i.e: Until the i reaches the start number.
| true |
0debb74096cb6fb8c78922e17677242b87b884d9 | rmaur012/GraphicalSequenceAlgorithm | /GraphicalSequenceAlgorithm.py | 2,392 | 4.3125 | 4 | #Setting up the sequence list
try:
sizeOfSeq = raw_input("How many vetices are there? ")
sizeOfSeq = int(sizeOfSeq)
index = 0
sequence = [None]*sizeOfSeq
except ValueError:
print 'A Non-Numerical Value Was Entered. Please Try Again And Enter With A Numerical Value.'
quit()
#The user inputs the degrees of the vertices, then sorts it in reverse.
#It will also calculate sum of the sequence of degrees to then be evaluated in the second if statement after the loop
seqSum = 0
while sizeOfSeq>0:
try:
sequence[index]=int(raw_input("Enter The Degree For A Vertex: "))
seqSum = seqSum + sequence[index]
sizeOfSeq=sizeOfSeq-1
index=index+1
except ValueError:
print 'A Non-Numerical Value Was Entered. Please Enter A Numerical Value.'
sequence.sort(reverse = True)
#Checks if a degree is bigger or equal to number of vertices,
#then will check if the sum of the sequence = 2*(number of edges), which would make it not graphical if it does not equal,
#then it proceeds with algorithm if it's not determined to be either of the first two
if sequence[0]>=len(sequence):
print 'The Sequence Is Not Graphical: Degree Is Higher Than The Number Of Vertices'
elif seqSum%2 !=0:
print 'The Sequence Is Not Graphical: The Sum Of The Degrees In The Sequence Is Not Divisible By 2'
else: #Algorithm starts here
seqIndex = 1
iteration = 0
negFound = False
while iteration<len(sequence):
num = sequence[0]
sequence[0] = 0
while num>0:
sequence[seqIndex]= sequence[seqIndex]-1
num = num -1
seqIndex = seqIndex + 1
sequence.sort(reverse=True)
if sequence[len(sequence)-1]<0:
negFound = True
break
seqIndex = 1
iteration = iteration + 1
if negFound == True:
print 'The Sequence Is Not Graphical: A Term Of The Sequence Was Negative'
else:
print 'The Sequence Is Graphical!'
#Prints The State Of The Sequence At The End Of The Algorithm
print 'Algorithm Ended With Sequence As: {0}'.format(sequence)
| true |
adab3d9ccab42569ced54c6fd3551335a7b34969 | hsrwrobotics/Robotics_club_lectures | /Week 2/Functions/func_echo.py | 1,497 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 16:15:36 2019
HSRW Robotics
@author: mtc-20
"""
# A function definition starts with the keyword def followed the function
# name which can be anything starting with an alphabet, preferably in
# lowercase followed by a colon {:}. The body(the block of code to be reused)
# starts in the subsequent line and is closed by the return statement
# Below is a simple function that takes 0 arguments and returns nothing
def echo():
shoutout = input("Shout out something: ")
print(shoutout.upper())
print(shoutout)
print(shoutout.lower())
for i in range(len(shoutout)):
print(shoutout[:-i].lower())
return
# To use the function, it can be called in different ways:
echo()
test_echo = echo()
print ("\n", test_echo)
# Pay attention to the variable explorer, is there anything stored?
# What about the print statements from the different call?
# Below is another way of writing the same function. Functions can also have
# arguments that are passed in brackets {()}. Arguments are variables and a
# function can have any number of arguments.
# The below function takes 1 argument and returns True value always
def echo2(shoutout):
print(shoutout.upper())
print(shoutout)
print(shoutout.lower())
for i in range(len(shoutout)):
print(shoutout[:-i].lower())
return True
# There are atleast 3 different ways to call this function, that's your task
| true |
b746788b2a554acf3ce050acede7af3fb3ae19d3 | danilokevin/Lote-1---Python | /Lote 1/Ex24.py | 329 | 4.34375 | 4 | # Objetivo: Receba um valor inteiro. Verifique e mostre se é divisível por 2 e 3.
A=int(input("Digite um número: "))
if(A%6)==0:
print("SIM! É DIVISÍVEL POR 2 E 3")
elif(A%3)==0:
print("DIVISÍVEL SOMENTE POR 3")
elif(A%2)==0:
print("DIVISÍVEL SOMENTE POR 2")
else:
print("NÃO É DIVISÍVEL POR 2 OU 3") | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.