blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
52008b5181e886e0656108dab34c19823d1caa07 | brandonbloch/cisc327 | /bCommands.py | 2,983 | 4.21875 | 4 |
def find_account(number, accounts):
"""
This function takes in a account number and the master accounts list
to check if the specified account number is in the master accounts list.
"""
for i in range(len(accounts)):
if accounts[i][0] == number:
return i+1
return 0
def withdraw(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
If the transaction is not valid the program will terminate
"""
num = find_account(transaction[2], accounts)
if not num:
raise RuntimeError
elif int(accounts[num-1][1]) - int(transaction[3]) < 0:
raise RuntimeError
else:
accounts[num-1][1] = str(int(accounts[num-1][1]) - int(transaction[3]))
return accounts
def deposit(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
"""
num = find_account(transaction[1], accounts)
if not num:
raise RuntimeError
else:
accounts[num-1][1] = str(int(accounts[num-1][1]) + int(transaction[3]))
return accounts
def transfer(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
"""
num1 = find_account(transaction[1], accounts)
num2 = find_account(transaction[2], accounts)
if not (num1 and num2):
raise RuntimeError
elif int(accounts[num2-1][1]) - int(transaction[3]) < 0:
raise RuntimeError
else:
accounts[num1-1][1] = str(int(accounts[num1-1][1]) + int(transaction[3]))
accounts[num2-1][1] = str(int(accounts[num2-1][1]) - int(transaction[3]))
return accounts
def create(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
"""
num = find_account(transaction[1], accounts)
if num:
raise RuntimeError
else:
transaction = [transaction[1], '000', transaction[4]]
accounts.append(transaction)
return accounts
def delete(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
"""
num = find_account(transaction[1], accounts)
if not num:
raise RuntimeError
elif int(accounts[num-1][1]) != 0:
raise RuntimeError
elif transaction[4] != accounts[num+1][2]:
raise RuntimeError
else:
accounts.remove([accounts[num-1][0], accounts[num-1][1], accounts[num+1][2]])
return accounts
| true |
246230d338d105ac5c2b85f151a63818d8b890a7 | 1gn1z/Python_Ejercicios | /ex005_cadena_inversa.py | 824 | 4.40625 | 4 | # Ejercicio 5. Obtener la representacion inversa de una cadena de caracteres
#cadena = input('Ingresa la cadena: ')
#print(cadena[::-1])
# Lo logré sin ver el tutorial :3 <3
# De aquí pa' abajo el codigo del tutorial.
# Con un ciclo for iteraremos la cadena
cadena = 'Python'
# Con RANGE definimos que empiece desde el primer caracter (posicion 0)
# Y con LEN obtenemos la cantidad total de caracteres de la cadena, y poder obtener la ultima posicion
# Con el tercer argumento de RANGE podemos indicar en que orden hara el recorrido, osea -1
for i in range(len(cadena) -1, -1, -1):
# Finalmente imprimimos la POSICION actual de i en la cadena:
# Agregamos el end para que muestre el resultado del ciclo en una sola linea y no asi:
# n
# o
# h
# etc.
print(cadena[i], end='')
print()
print(cadena[::-1]) | false |
77cee1eae648b4d90ce87bfd203332c8f49fd0c8 | Mb01/Code-Samples | /algorithms/sorting/heapsort.py | 1,886 | 4.25 | 4 | #!/usr/bin/env python
import random
LENGTH = 100
data = [random.randint(0,100) for _ in range(LENGTH)]
def heapsort(lst):
def swap(lst, a, b):
"""given a list, swap elements at 'a' and 'b'"""
temp = lst[a]
lst[a] = lst[b]
lst[b] = temp
def siftdown(lst, start, end):
"""move an element to proper position"""
root = start
while root * 2 + 1 <= end:
left_child = root * 2 + 1
cand = root
# is left_child a candidate for swapping?
if lst[cand] < lst[left_child]:
cand = left_child
# given that swap is max(left_child, root),
# is right_child a candidate for swapping?
if left_child + 1 <= end and lst[cand] < lst[left_child + 1]:
cand = left_child +1
# set root to value to be swapped (or do nothing if same)
if cand != root:
swap(lst, root, cand)
root = cand
else:
break
def heapify(lst):
"""call siftdown on non-leaf elements"""
size = len(lst)
# begin at rightmost non-leaf element
start = size/2 -1
# call siftdown and move left (start -= 1)
while start >= 0:
siftdown(lst, start, size - 1)
start -= 1
def heapsort(lst):
# create heap
heapify(lst)
last = len(lst) - 1
# while there is a heap under consideration
while last > 0:
# zeroeth element is largest, move to last position
swap(lst, last, 0)
# shrink heap
last = last - 1
# first element altered, move to proper position
siftdown(lst, 0, last)
heapsort(lst)
print "initial", data
heapsort(data)
print "sorted", data
| true |
e02e83c6c26a6e38a6451a1f2fff180be829c9d2 | krei/scripts | /dectobin.py | 255 | 4.1875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
decimals = int(input("Введите натуральное число: "))
binars = ""
while decimals > 0:
y = str(decimals % 2)
binars = y + binars
decimals = int(decimals / 2)
print(binars)
| false |
1c676ba9bb43be453458060ce539fa12e31e645b | brianaguirre/CS3240 | /lab3/lab3_part1.py | 1,642 | 4.28125 | 4 | __author__ = 'BrianAguirre'
#USER CREATION
user_name = ""
password = ""
data = {}
print("This program takes in usernames and password.")
print("If at any point you wish to quit, enter an empty string.")
user_name = input("Please enter the first user name:")
password = input("Enter a password for " + user_name + ":")
condition = True
if (user_name == ""):
condition = False
elif (password == ""):
condition = False
while(condition):
data[user_name] = password
user_name = input("Please enter another username:")
password = input("Please enter another password for " + user_name + ":")
if (user_name == ""):
condition = False
elif (password == ""):
condition = False
#VERIFY USER LOGIN
print("")
print("Please login by enter a username and password.")
print("Enter an empty string to stop.")
check_user = input("Please enter the first user name:")
check_pass = input("Enter a password for " + check_user + ":")
condition2 = True
if (check_user == ""):
condition2 = False
elif (check_pass == ""):
condition2 = False
while(condition2):
if (check_user in data):
pass_on_file = data[check_user]
if (check_pass == pass_on_file):
print("Login success!")
else:
print("Login failed. Wrong Password.")
else:
print("Username not found.")
check_user = input("Please enter another username:")
check_pass = input("Please enter another password for " + check_user + ":")
if (check_user == ""):
condition2 = False
elif (check_pass == ""):
condition2 = False
if __name__ == "__main__":
pass | true |
58d8e5da962370d21564be1b4e891a64abfb26da | underwaterlongs/codestorage | /Project_Euler/P3_LargestPrimeFactor.py | 1,362 | 4.15625 | 4 | """
The prime factors of 13,195 are 5,7,13,29.
What is the largest prime factor of a given number ?
We can utilize Sieve of Eratosthenes to find the prime factors for N up to ~10mil or so efficiently.
General pseudocode for sieve:
initialize an array of Boolean values indexed by 2 to N, set to True
i = 2
for i to sqrt(n) do
if(arr[i]==True):
for j = i^2, i^2+i, i^2+2i.... to n do
a[j] = False
p^2: 2^2, 3^2, 4^2 -> for this p in 2 to sqroot(num), we mark this as the non prime factors by switching it to False. Thus remaining numbers in the range are prime and remain True
We can modify this concept to find factors instead.
"""
import math
import sys
def find_largest_prime_factor(num):
largest_prime_factor = 0
# check for divisibility by 2, if so -> divide till only 1 or some other non-2 factors are left
while(num%2 == 0):
num //= 2
largest_prime_factor=2
for i in range(3,int(math.sqrt(num)+1),2):
while (num%i==0):
num //= i
largest_prime_factor = int(i)
if(num>=2):
largest_prime_factor = int(num)
print(largest_prime_factor)
if __name__ == "__main__":
# number of testcases, t
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
find_largest_prime_factor(n) | true |
05f7b9c287e7acf3a1534243c4cb7b96cdf5d916 | felipem0ta/furry-potato | /Python/Cousera_Google Automation/Crash Course/coursera.py | 791 | 4.1875 | 4 | """
função que conta quantas vezes uma letra aparece em um texto.
"""
def count_letters(text):
result = {} #incializando um dicionario vazio
for letter in text: #percorre o texto passado
if letter not in result:
result[letter] = 0 #inicializa a contagem da letra com 0 se não estiver no dicionário
result[letter] +=1 #acrescenta a contagem à letra
return result
print(count_letters("Quantas vezes cada letra desse texto aparece nele"))
#Dicionario de roupas por cor.
wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}
for keys, values in wardrobe.items(): #Percorre todos os itens do dicionário
for value in values: #Imprime cada "key" cor por cor (value)
print("{} {}".format(value, keys))
print(wardrobe["shirt"]) | false |
1044ae5fa1dcff182100ef9f352d2985e2ee924a | Roy-Chandan/Roy-world | /Range1.py | 685 | 4.15625 | 4 | def user_choice():
choice = 'Wrong'
accept_range = range(0,10)
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input ("Enter a number between 1-10: ")
if choice.isdigit() == False:
print ("Please enter a number not string")
if choice.isdigit() == True:
if int(choice) in accept_range:
within_range = True
else:
print ("Number is not between 1-10")
within_range = False
return int(choice)
result = user_choice()
print (result)
| true |
2cd2cee48549e357234920cd03528ecad6b1c5ba | kvega/potentialsim | /src/potentialsim.py | 1,020 | 4.28125 | 4 | #!/usr/bin/python3
import pylab
import random
"""
Generates a text file of values representing the coordinates of n particles in a
potential.
"""
# Create the Particle Class
class Particle(object):
"""
Representation of a simple, non-interacting, massive particle
(assumes point-like, does not model charge).
"""
def __init__(self, position, velocity, mass=1.0):
"""
TODO: define attributes
"""
self.mass = mass
self.position = position
self.velocity = velocity
# Get the current position and velocity of the particle
def get_position(self):
return self.position
def get_velocity(self):
return self.velocity
# Set the new position and velocity of the particle
def set_position(self, position):
self.position = position
def set_velocity(self, velocity):
self.velocity = velocity
# TODO: Implement the equations of motion for a given potential
# TODO: Create function to generate particles | true |
861a99afac2f93a6163847d6a9bdc57b21136b19 | jflow415/mycode | /dict01/marvelchar01.py | 1,290 | 4.21875 | 4 | #!/usrbin/env python3
marvelchars = {
"Starlord":
{"real name": "peter quill",
"powers": "dance moves",
"archenemy": "Thanos"},
"Mystique":
{"real name": "raven darkholme",
"powers": "shape shifter",
"archenemy": "Professor X"},
"She-Hulk":{
"real name": "jennifer walters",
"powers": "super strength & intelligence",
"archenemy": "Titania"}
}
char_name = input("Which character do you want to know about? (starlord, mystique, she-hulk)").title()
char_stat = input("What statistic do you want to know about? (real name, powers, archenemy)").lower()
#print(marvelchars, sep= ", ")
print(char_name,"s", char_stat, "is:", marvelchars[char_name][char_stat])
# notice that when you put the cursor over the last parens, it doesn't highlight the FIRST one next to print at the beginning of the line
# shows that you're missing an ending parenthesis at the end of line 21 :)
#would the get method give the current power of the chosen character?
# as written, no I don't believe so... the first argument is the key being "get"ted, the second argument is what gets returned if no key is found.
#Ok. I'll do some more digging . Ok cool! Let me know if you need any help!
| true |
7830f2711cd16350747357b1639b0f72d2974a68 | RasikKane/problem_solving | /python/00_hackerrank/python/08_list_comprehension.py | 631 | 4.375 | 4 | """
Let's learn about list comprehensions!
You are given three integers x, y and z representing the dimensions of a cuboid along with an integer n.
Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n.
Here, 0 <= i <=x , 0 <=j <=y, 0 <= k <=z. Please use list comprehensions rather than multiple loops, as a learning exercise.
"""
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print([[i,j,k] for i in list(range(x+1)) for j in list(range(y+1)) for k in list(range(z+1)) if not int(i+j+k) == n]) | true |
51ac5fba05dea57ebbc98fc66092876f2e867b82 | NoraIlisics/FirstRep | /for.py | 924 | 4.34375 | 4 | #Write a program which sums the integers from 1 to 10 using a for loop
# (and prints the total at the end).
total = 0
for i in range(1,11):
total += i
print(total)
#Can you think of a way to do this without using a loop?
total2 = sum(range(1,11))
print(total2)
#Write a program which finds the factorial of a given number.
# E.g. 3 factorial, or 3! is equal to 3 x 2 x 1; 5! is equal to 5 x 4 x 3 x 2 x 1, etc..
# Your program should only contain a single loop.
number = int(input("Choose a number: "))
num_fact = 123412313241234123412341234
for i in range(1, number+1):
num_fact *= i
print(num_fact)
#Write a program which prompts the user for 10 floating-point numbers and calculates their sum,
# product and average. Your program should only contain a single loop.
#Rewrite the previous program so that it has two loops
# – one which collects and stores the numbers, and one which processes them.
| true |
57ddd657bd402e1b4666223f51ad8efcc17a070f | Nevashka/Project-Euler | /palindrome.py | 591 | 4.1875 | 4 | #Problem 4: Find the largest palindrome made from the product of two 3-digit numbers.
def largest(digits):
''' (int) -> int
return the largest palindrome from the product of the numbers with
the given number of digits
palindrome(2) -> 9009 '''
first = 10**(digits-1)
last = (10**digits)-1
palindrome = [0]
for i in range(last, first, -1):
for x in range(last, first, -1):
product = i * x
if str(product) == str(product)[::-1] and palindrome[0] < product:
palindrome[0] = product
return palindrome[0]
| true |
b6de5d4434c5d21dbbafe799879b02b43278c2ec | davidlbyrne/cybersecurity | /assignment2/des_cbc.py | 2,882 | 4.15625 | 4 | #!/usr/local/bin/python3
# Assignment2 - Assignment 2, due November 7, 2018: Problem 6.1
# in the lecture notes. You may import the following packages from
# Python libraries:
import sys
import binascii
from Crypto.Cipher import DES
from Crypto import Random
def checkpad(plaintext):
length= len(plaintext)
if ((length % 8) != 0):
rem = length%8
# Pad indicates how many characters we have to add to the end of the file
pad = 8 - rem
# the first meaningless number in binary is (10000000) which is equal to 128
for i in range (pad):
plaintext= plaintext + chr (0)
return (plaintext)
# xor function
def xor(lft, rht):
# set up 8 char arrays with none elements
lft_ba = [None,None,None,None,None,None,None,None]
rht_ba = [None]*8
# print(lft_ba)
# print(lft, rht)
# step through each letter and conv to integer and store
for i in range(0,8):
# print(i)
lft_ba[i] = ord(lft[i])
rht_ba[i] = ord(rht[i])
# finally the result of xor
xor_res = [None] * 8
for i in range(0, 8):
xor_res[i] = lft_ba[i] ^ rht_ba[i]
# convert the bits into char again
ret=""
# print('xor_result:',xor_res)
return bytes(bytearray(xor_res))
#Encrypt function
def des_cbc_encrypt(plaintext,key,iv) :
ciphertext=b''
previous=""
#des first round
obj = DES.new(key,DES.MODE_ECB)
plaintext = checkpad(plaintext)
pte = plaintext[:8]
plaintext = plaintext[8:]
# print("pte:",pte)
pte = xor(iv,pte)
# print(len(pte))
previous = obj.encrypt(pte)
# print(len(previous), previous)
ciphertext = ciphertext + previous
# begin remaining rounds
for i in range (0,int((len(plaintext)/8))) :
pte = checkpad(plaintext[:8])
plaintext = plaintext[8:]
# print("encrypting ",len(pte),"bytes :\'",pte,"\'")
previous = ''.join([chr(s) for s in bytearray(previous)])
# print("previous :",previous)
pte = xor(previous,pte)
# print(pte,"END")
# print(len(pte), "pte",pte)
previous = obj.encrypt(pte)
# print(len(previous), previous)
ciphertext = ciphertext + previous
return ciphertext
#Decrypt Function
#des first round
#remaining rounds
if __name__ == '__main__':
key = sys.argv[1]
# print("Encrypting :",sys.argv[2])
file = open(sys.argv[2],'r')
plaintext=file.read()
file.close()
iv = '00000000'
ciphertext=des_cbc_encrypt(plaintext,key,iv)
print(ciphertext)
#print
'''
$ more test.txt
Hello, World!
$ python des-cbc.py 12345678 test.txt | xxd -b
00000000: 11100000 01011001 00110010 11110100 00101101 10100110 .Y2.-.
00000006: 11111011 01101011 00001000 00100001 10011100 01011100 .k.!.\
0000000c: 11000111 10110010 11001000 01001010 00001010 ...J.
'''
| true |
72e11ac47280c2ff079353f3e92a744fb16de490 | sabasharf123/word-frequency | /word-frequency-starter.py | 2,824 | 4.21875 | 4 | #set up a regular expression that can detect any punctuation
import re
punctuation_regex = re.compile('[\W]')
#open a story that's in this folder, read each line, and split each line into words
#that we add to our list of storyWords
storyFile = open('short-story.txt', 'r') #replace 'short-story.txt' with 'long-story.txt' if you want!
storyWords = []
for line in storyFile:
lineWords = line.split(' ') #separate out each word by breaking the line at each space " "
for word in lineWords:
cleanedWord = word.strip().lower() #strip off leading and trailing whitespace, and lowercase it
cleanedWord = punctuation_regex.sub('', cleanedWord) #remove all the punctuation
#(literally, replace all punctuation with nothing)
storyWords.append(cleanedWord) #add this clean word to our list
#set up an empty dictionary to hold words and their frequencies
#keys in this dictionary are words
#the value that goes with each key is the number of times that word appears in the dictionary
#Example: a key might be 'cat', and frequency_table['cat'] might be 5 if the word 'cat'
#appears 5 times in the storyWords list
frequency_table = {}
#ALL OF OUR CODE GOES HERE
for word in storyWords:
#if I have not seen any words of this type before, add a new entry
#1 is referring to how many times you've seen it before
if word not in frequency_table:
frequency_table[word] = 1
#if I have seen it before, add 1 to its current count
else:
frequency_table[word] = 1 + frequency_table[word]
print(frequency_table)
#this is a function that finds the most frequent word
def find_max_frequency():
#at the start, I haven't seen any words
#but I want to keep track of the most frequent word I've seen so far
max_freq = 0
max_word = ' '
#look through ALL words in the frequency table
for word in frequency_table:
#if the word I'm looking at now has appeared more than any
#words I've seen so far, update my max
if frequency_table[word] > max_freq:
max_freq = frequency_table[word]
max_word = word
#at the end of the for loop, we've looked through all entries and max_word has the most frequent word in it
return max_word
best_word = find_max_frequency()
print("The most frequent word is: " + best_word)
#make a fucntion to find the top 10
#CHALLENGE: modify this so it takes the top N
def top_twenty():
#take the most frequent word out of the frequency table 10 times
for count in range(20):
top_word = find_max_frequency()
print(top_word + " appears " + str(frequency_table[top_word]))
del(frequency_table[top_word]) #take that entry out of the table
#call the top ten function
top_twenty()
| true |
80c4ac318f00b8cc10a938cfc432f09763e00871 | AngelmunozQ/An | /Clases/examen3.py | 1,552 | 4.125 | 4 | #1
"""def Calcu (num1,num2,num3):
Z=(num1*num2*num3)
f=(num1/num2/num3)
W=(num1**num2**num3)
print(f"{Z},{f},{W}")
print("""
#1. Multiplicacion,Potencia y Division.
#2.Salir
""")
Eleccion = (input("seleccione una opcion : "))
if Eleccion == "1":
a = int(input("ingresa numero : "))
y = int(input("ingresa numero : "))
p = int(input("ingrese numero: "))
Calcu(a,y,p)
else:
(print("Adios"));"""
#3
""""def triangulo (r1,r2):
J=(r1*r2/2)
print(J)
print("Ingresa la base y altura del triangulo para calcular el AREA.")
i=float(input("Ingresa base: "))
k=float(input("ingresa Altura: "))
triangulo(i,k)"""
#2
"""def list ():
lista1=[1,3,4]
lista2=[3,4,3]
lista3=[3,2,1]
print(f"{lista1},{lista2},{lista3}");"""
#4
"""AB= [36,37,38,35,36,38]
def encontrar ():
print("Elemento mayor", max(AB))
print("Elemento menor",min(AB))
suma=0
for i in AB:
suma+=i
promedio =suma/6
print(promedio)"""
#5
def fib(n):
a=0
b=1
lista5=[]
while a < n:
print(a, end="")
a=b
b=a+b
lista5.append(b)
print(lista5)
ingreso=int(input("Ingrese el numero a encontrar: "))
suma=0
for i in lista5:
if ingreso == lista5:
print("el numero {} se encontro en la posicion {}".format(ingreso,i))
else:
print("el numero {} no esta en la posicion {}".format(ingreso,i))
fib(1000)
#6
#es relativamente simple hacer eso solo es utilizar la palabra es "from file import sum(a,b)"
| false |
aec85ea6f687ec7516c577d5ddd58ed90f72e18f | tigerjoy/SwayamPython | /old_programs/cw_17_06_20/year.py | 471 | 4.15625 | 4 | year=int(input("enter year :"))
if year%100==0:
print("it is a centennial year")
if year%400==0:
print("it is a leap year")
else:
print("it is not a leap year")
elif year%4==0:
print("it is a leap year")
else:
print("it is not a leap year")
# Alternative
# if (year % 100 == 0) and (year % 400 == 0):
# print("it is a leap year")
# elif (year % 100 != 0) and (year % 4 == 0):
# print("it is a leap year")
# else:
# print("it is not a leap year") | true |
571a5322ed3b18be4a319ffa3a14a9541b6f08d3 | tigerjoy/SwayamPython | /old_programs/cw_2021_01_16/dictionary_exercise.py | 639 | 4.1875 | 4 | dict_users={}
for i in range(1,11):
# Enter username of user 1:
username=input("Enter username of user {}:".format(i))
password=input("Enter password of user {}:".format(i))
dict_users[username]=password
print("Enter log in details:")
username=input("Enter username of user :")
password=input("Enter password of user :")
# If the username is present in the dictionary
if(username in dict_users):
# If the entered password is of the username
if(dict_users[username] == password):
print("Welcome",username,"you are now logged in")
else:
print("Password is invalid")
else:
print(username,"is not a valid user")
| true |
3b51f2f0f0267366f5c1b246267ca3c10105cf9b | tigerjoy/SwayamPython | /old_programs/cw_2021_01_16/list_exercise.py | 623 | 4.15625 | 4 | list1 = []
list2 = []
size1 = int(input("Enter the size of list 1: "))
print("Enter elements in list 1")
for i in range(size1):
item = int(input("Enter element {}: ".format(i + 1)))
list1.append(item)
size2 = int(input("Enter the size of list 2: "))
print("Enter elements in list 2")
for i in range(size2):
item = int(input("Enter element {}: ".format(i + 1)))
list2.append(item)
# Q3 (Page 95) (List Exercise)
is_subset = True
for e in list1:
if e not in list2:
print("No, list1 notasubset of list2")
is_susbet = False
break
if is_subset == True:
print("Yes, list 1 is a subset of list 2")
| true |
12d9d1eb684dad8946f5c66c30eb5faec45c3f72 | tigerjoy/SwayamPython | /old_programs/cw_2020_10_22/list_q15.py | 264 | 4.34375 | 4 | size=int(input("Enter size of a list:"))
arr=[]
for i in range(0,size):
item=int(input("Enter element {}:".format(i+1)))
arr.append(item)
largest=arr[0]
for i in range(1,size):
if(arr[i]>largest):
largest=arr[i]
print("Largest element is:",largest) | true |
2cc2a7b4d5e441bdd774cdd94d14d54257b2c91e | tigerjoy/SwayamPython | /old_programs/cw_2020_10_22/list_q16.py | 269 | 4.25 | 4 | size=int(input("Enter size of a list:"))
arr=[]
for i in range(0,size):
item=int(input("Enter element {}:".format(i+1)))
arr.append(item)
smallest=arr[0]
for i in range(1,size):
if(arr[i]<smallest):
smallest=arr[i]
print("smallest element is:",smallest) | true |
cb7ec04d9e47007ae26eb6a0dbeddf298c13ce90 | tigerjoy/SwayamPython | /cw_2021_06_19/sum_factor_q11.py | 253 | 4.1875 | 4 | def sum_of_factor(num,f=1):
if f>num//2:
return(num)
elif(num%f==0):
return (f+sum_of_factor(num,f+1))
else:
return (sum_of_factor(num,f+1))
num=int(input("Enter a number:"))
print("Sum of factors of", num ,"is",sum_of_factor(num)) | false |
8c8c861daf4fb6f0c70eb776d8563907dda10f35 | Yuchen-Yan/UNSW_2017_s2_COMP9021_principle_of_programming | /labs/lab_1/my_answer/celsius_to_fahrenheit.py | 435 | 4.1875 | 4 | # Written by Yuchen Yan for comp9021 lab 1 question1
'''
Prints out a conversion table of temperatures from Celsius to Fahrenheit degrees,
with the former ranging from 0 to 100 in steps of 10.
'''
min_temperature = 0
max_temperature = 100
step = 10
print('Celsius\tFahrenheit')
for celsius in range(min_temperature, max_temperature + step, step):
fahrenheit = celsius * 9 / 5 +32
print(f'{celsius:7d}\t{int(fahrenheit):10d}')
| true |
20e61a14ba04a69c1095840c5b33ff936f6a8d3b | vpiyush/SandBox | /python-samples/rangeOp.py | 330 | 4.15625 | 4 |
# sequnce of numbers 0 to 8
for temp in range(9):
print(temp)
# sequnce of numbers 0 to 8
# range (start, stop)
for temp in range(5, 9):
print(temp)
# sequnce of numbers 0 to 8
# range (start, stop, step)
for temp in range(1, 9, 2):
print(temp)
#typecasting to list
oddlist = list(range(1, 19, 2))
print(oddlist)
| true |
27a48c5d309c06a6730df859139245bec6106a37 | sureshanandcse/Python | /listex.py | 693 | 4.34375 | 4 | # Creating a List with the use of multiple values
l= ["Sairam", "Engineering", "College"]
print("\nList containing multiple values: ")
print(l[0])
print(l[2])
s=l[1]
print("s= ",s)
print("s[2] =" ,s[2])
print(len(l))
"""
list = [ 'abcd', 786 , 2.23, 'john', 70.26 ]
list[0]='suresh' # list is mutable
print(list)
print (list[0]) # Prints first element of the list
print (list[1:3]) # 1,2 # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print(list)
print (list[-1] ) # prints last element in list
print (list[-5]) # prints first element in list
print(list[0:10])
"""
| true |
995a812fcfa31f6ba0ca9b8cf48bba04e6ff1a66 | codekyz/learn-algorithm | /algorithm_with_python/Doit/old/2_8.py | 733 | 4.1875 | 4 | # reverse sort of mutable sequence element
from typing import Any, MutableSequence
def reverse_array(a: MutableSequence) -> None:
n = len(a)
for i in range(n//2):
a[i], a[n-i-1] = a[n-i-1], a[i]
if __name__ == '__main__':
print('reverse sort of array element')
nx = int(input('enter number of element : '))
x = [None] * nx
for i in range(nx):
x[i] = int(input(f'x[{i}] = '))
reverse_array(x)
print('finish reverse sort')
for i in range(nx):
print(f'x[{i}] = {x[i]}')
# python 표준 라이브러리를 이용한 리스트 역순 정렬
# x.reverse() / 튜플은 안됨 immutable이므로
# y = list(reversed(x)) # x의 원소를 역순으로 정렬하여 y에 대입 | false |
125c4341943e9781fc9ee60b35e6beb13717c4aa | peggybarley/Ch.03_Input_Output | /3.0_Jedi_Training.py | 1,568 | 4.375 | 4 | # Sign your name: Peggy Barley
# 1.) Write a program that asks someone for their name and then prints their name to the screen?
print()
name = str(input("What is your name?"))
print("Hello,", name,"!")
print()
# 2. Write a a program where a user enters a base and height and you print the area of a triangle.
print()
print("Welcome to the triangle area calculator!")
base = float(input("What is the base of your triangle?"))
height = float(input("What is the height o your triangle?"))
area = 0.5*(base*height)
print()
print("The area of your triangle is", area)
print()
# 3. Write a line of code that will ask the user for the radius of a circle and then prints the circumference.
print()
print ("Welcome to the circumference calculator!")
r = float(input("What is the radius of your circle?"))
cir = 3.14*(r*2)
print()
print("The circumference of your circle is", r)
print()
# 4. Ask a user for an integer and then print the square root.
print()
print ("Welcome to the square root calculator!")
inte = int(input("Type an integer!"))
sr = inte**0.5
print()
print("The square root of", inte, "is", sr)
print()
# 5. Good Star Wars joke: "May the mass times acceleration be with you!" because F=ma.
# Ask the user for mass and acceleration and then print out the Force on one line and "Get it?" on the next.
print()
print("Welcome to the force calculator!")
m = float(input("What is the mass?"))
a = float(input("what is the acceleration?"))
f = m*a
print()
print("The force is", f)
print("May the mass times acceleration be with you!")
print("Get it?")
print() | true |
7ee6a48e8387a0d45ea82cf44b3e7b679dfcc503 | kongxilong/python | /mine/chaptr3/readfile.py | 341 | 4.3125 | 4 | #!/usr/bin/python3
'readTextFile.py--read and display text file'
#get file name
fname = input('please input the file to read:')
try:
fobj = open(fname,'r')
except:
print("*** file open error" ,e)
else:
#display the contents of the file to the screen.
for eachline in fobj:
print(eachline,)
fobj.close()
| true |
6c9b1f856e9c1abb350336b26b76f48a87a9f1bb | antwork/pynote | /source/str.py | 1,872 | 4.25 | 4 | # encoding:utf-8
# len(str)
s = 'hello China'
print(len(s))
#
# capitalize
# Return a capitalized version of S, i.e. make the first character
# have upper case and the rest lower case.
print('big city'.capitalize()) # Big city
#encode:utf-8
#
# casefold
# out: **********************value***********************
print('value'.center(50, '*'))
# out: value*********************************************
print('value'.ljust(50, '*'))
# out: *********************************************value
print('value'.rjust(50, '*'))
# out: 2
print('big city'.count('i')) # 2
#
# encode
# out: True
print('hello'.endswith('lo'))
# out:False
print('hello'.startswith('e'))
# print('^ one ^'.expandtabs(32))
#
# expandtabs
#
# find
print('CHINA'.find('I')) # Found: return index:2
print('China'.find('I')) # Not Found: return -1
print('CHINA'.index('I'))
try:
print('China'.index('I'))
except ValueError as e:
print(e) # substring not found
#
# format
#
# format_map
# isalnum
print('abc'.isalnum()) # True
print('12ab'.isalnum()) # True
print('+'.isalnum()) # False
#
# isalpha
print('abc'.isalpha()) # True
print('123'.isalpha()) # False
# isdecimal
# Return True if there are only decimal characters in S, False otherwise.
# >>> print('0123456789'.isdecimal())
# True
# >>> print('0123456789a'.isdecimal())
# False
# isdigit
#
# isidentifier
#
# islower
#
# isnumeric
#
# isprintable
#
# isspace
#
# istitle
#
# isupper
#
# Out:apple.banana.orange
arr = ['apple', 'banana', 'orange']
print('.'.join(arr))
#
# ljust
#
# lower
#
# lstrip
#
# maketrans
#
# partition
#
# Out: banana is delicious!
src = "orange is delicious!"
print(src.replace('orange', 'banana'))
#
# rfind
#
# rindex
#
# rjust'#
# rpartition'#
# rsplit'#
# rstrip'#
# split'#
# splitlines'#
# startswith'#
# strip'#
# swapcase'#
# title'#
# translate'#
# upper'#
# zfill'
| true |
42db40859935dc3bfca4f40ccb32ba90abf8e3b6 | boksuh/Jump_to_Python | /02/02-3.py | 970 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Bokyung Suh
점프 투 파이썬
"""
odd = [1, 3, 5, 7, 9]
a = [1, 2, 3]
print(a)
print(a[0])
print(a[0] + a[2])
print(a[-1])
a = [1, 2, 3, ['a', 'b', 'c']]
print(a[0])
print(a[-1])
print(a[3])
print(a[-1][0])
a = [1, 2, 3, 4, 5]
print(a[0:2])
print(a[:2])
print(a[2:])
a = [1, 2, 3]
b = [4, 5, 6]
print(a + b)
print(a * 3)
print(len(a))
a[2] = 4
print(a)
del a[1]
print(a)
a = [1, 2, 3, 4, 5]
del a[2:]
print(a)
a = [1, 2, 3]
a.append(4)
print(a)
a.append([5, 6])
print(a)
a = [1, 4, 3, 2]
a.sort()
print(a)
a.reverse()
print(a)
a = ['a', 'c', 'b']
a.sort()
print(a)
a.reverse()
print(a)
a = [1, 2, 3]
print(a.index(3))
print(a.index(1))
a = [1, 2, 3]
a.insert(0, 4)
print(a)
a.insert(3, 5)
print(a)
a = [1, 2, 3, 1, 2, 3]
a.remove(3)
print(a)
a = [1, 2, 3]
print(a.pop(), a)
a = [1, 2, 3]
print(a.pop(1), a)
a = [1, 2, 3, 1]
print(a.count(1))
a = [1, 2, 3]
a.extend([4, 5])
print(a)
b = [6, 7]
a.extend(b)
print(a) | false |
a988f35e8376fcd9c82ee7b463fab10240abb1fe | n0execution/prometheus-python | /lab3_1.py | 321 | 4.3125 | 4 | import sys
a = float(sys.argv[1]) #a is the first argument
b = float(sys.argv[2]) #b is the second argument
c = float(sys.argv[3]) #c is the third argument
if (a + b > c) & (a + c > b) & (b + c > a) :
print("triangle") #two sides > than the other
else :
print("not triangle") #two sides <= than the other
| false |
8416779fee766e6ad1dbbf23bc88cdd02c7a7706 | n0execution/prometheus-python | /lab5_3.py | 635 | 4.40625 | 4 | """
function for calculating superfibonacci numbers
it is a list of whole numbers with the property that,
every n term is the sum of m previous terms
super_fibonacci(2, 1) returns 1
super_fibonacci(3, 5) returns 1
super_fibonacci(8, 2) returns 21
super_fibonacci(9, 3) returns 57
"""
def super_fibonacci(n, m) :
#checking for some special cases
if n <= m or m == 1 :
return 1
#making list of [1, 1, 1...] with length of m
new_list = [1 for x in range(m)]
for i in range(m, n) :
length = len(new_list)
#appending the sum of m last elements to list
new_list.append(sum(new_list[length - m :]))
return new_list[n - 1]
| true |
39a3ba15e6a0fe148f4977ccb5db70ad5142e2fe | n0execution/prometheus-python | /lab7_4.py | 1,866 | 4.34375 | 4 | import datetime, calendar
"""
function for displaying definite month of definite year
$ print create_calendar_page(1)
'--------------------
MO TU WE TH FR SA SU
--------------------
01 02 03 04 05 06 07
08 09 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31'
$ print create_calendar_page()
'--------------------
MO TU WE TH FR SA SU
--------------------
01 02 03 04
05 06 07 08 09 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28'
$ print create_calendar_page(4, 1992)
'--------------------
MO TU WE TH FR SA SU
--------------------
01 02 03 04 05
06 07 08 09 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30'
"""
def create_calendar_page(month = 2, year = 2018) : #default values of month and year are today's month and year
begin = 20 * '-' + '\nMO TU WE TH FR SA SU\n' + 20 * '-' + '\n' #preparation
result = begin
days = calendar.monthrange(year, month)[1] #variable for storing number of days in that month
day = datetime.datetime(year, month, 1) #variable for day
current_day = 1 #first day of month
for d in range(days) : #iterate through all month
day_week = day.weekday() #variable for day of week
if current_day <= 9 : #if day is 1..9
str_day = '0' + str(current_day) #add '0' and convert to str-type
else :
str_day = str(current_day) #convert to str-type
if current_day == 1 : #if it is first day of month
result += 3 * ' ' * day_week + str_day
else :
result += str_day
if day_week != 6 and d != days - 1: #if the day is not the last in the week and in the month
result += ' '
if day_week == 6 : #if the day is sunday
result += '\n'
current_day += 1 #increment the variable of day
if current_day in range(days + 1) : #search currend_day in days
day = datetime.datetime(year, month, current_day) #update day-variable
return result
| false |
5cf0406aa64a6679f4aea84a4662d819dad13d4a | TaylorKolasinski/hackerrank_solutions | /strings/pangrams.py | 1,122 | 4.3125 | 4 | # Difficulty - Easy
# Problem Statement
# Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly because it is a pangram. ( pangrams are sentences constructed by using every letter of the alphabet at least once. )
# After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.
# Given a sentence s, tell Roy if it is a pangram or not.
# Input Format
# Input consists of a line containing s.
# Constraints
# Length of s can be atmost 103 (1≤|s|≤103) and it may contain spaces, lowercase and uppercase letters. Lowercase and uppercase instances of a letter are considered same.
# Output Format
# Output a line containing pangram if s is a pangram, otherwise output not pangram.
def findPanagram(s):
alpha = []
for char in s:
if char not in alpha:
alpha.append(char)
if len(alpha) == 26:
print "pangram"
else:
print "not pangram"
if __name__ == '__main__':
# Hanlde inputs
s = raw_input().replace(" ", "").lower()
findPanagram(s) | true |
8c31f4a29804ccecb16daedd837a65ea8fd375bb | JAT117/Notes | /CSCE4910/PythonExamples/TexBoxWidget.py | 827 | 4.25 | 4 | #!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Python GUI")
#Handles Button Clicked
def clickMe():
#When clicked, change name of button.
myButton.configure(text='Hello ' + name.get())
#Lable INSIDE our win (Window)
ttk.Label(win, text="Enter a name:").grid(column=0, row=0)
#String Variable
name = tk.StringVar()
#Box for INPUT inside win of width 12 and value stored on Var name
inputBox = ttk.Entry(win, width = 12, textvariable = name)
inputBox.grid(column = 0, row = 1) #Possition
#Adding a Button
myButton = ttk.Button(win, text="Click Me!", command=clickMe)
myButton.grid(column=1, row=1) #Possition
win.mainloop()
| true |
ff0020378e4521727e26a70d4e1657ed17854576 | Bascil/python-data-structures-code-challenge | /17.py | 1,086 | 4.3125 | 4 | # Dictionaries
'''
Are key value pairs
Are associative arrays like Java Hashmap
Dicts are unordered
'''
x = {'pork' : 25.3, 'beef': 33.8, 'chicken': 22.4 }
print(x)
x = dict([('pork', 25.3), ('beef', 33.8), ('chicken', 22.4)])
print(x)
x = dict(pork = 25.3, beef = 33.8, chicken = 22.4)
print(x)
# Add or update
x['shrimp'] = 38.2
print(x)
# Delete an item
del(x['pork'])
print(x)
# Check membership
x = {'pork' : 25.3, 'beef': 33.8, 'chicken': 22.4 }
print('beef' in x)
# Delete all items from dict
x.clear()
print(x)
# delete dict
del(x)
# accessing keys and values
y = {'pork' : 25.3, 'beef': 33.8, 'chicken': 22.4 }
print(y.keys())
y = {'pork' : 25.3, 'beef': 33.8, 'chicken': 22.4 }
print(y.values())
y = {'pork' : 25.3, 'beef': 33.8, 'chicken': 22.4 }
print(y.items())
# check membership in y keys
print('pork' in y)
# or
print('pork' in y.keys())
# check membership in y values
print('claims' in y.values())
# iterating a dict
y = {'pork' : 25.3, 'beef': 33.8, 'chicken': 22.4 }
for key in y:
print(key , y[key])
# or
for k,v in y.items():
print(k,v)
| false |
674c75a565efdf149d612db8fead1899d1e5336e | vedk21/python-playground | /Intermediate/OOP/Abstraction/abstraction.py | 710 | 4.1875 | 4 | # Abstraction (hiding the details of operation but availabling the interface open)
class Car:
def __init__(self, name, color, year):
self.name = name
self.color = color
self._year = year # _ represents it understood as private member
def drive(self):
print('driving {self.name} a car of color {self.color}')
def _get_year(self):
return self._year
def show_year(self):
print(f'This car is manufactured in {self._get_year()}')
mustang = Car('Mustang GT', 'grey', 1970)
print(mustang.show_year())
# There is no way in python, that we can limit the member access using public or private key words,
# But it is a common practice to use '_' as representation of private members
| true |
104cc6f2a2c4044a905c748603f3998535f84b0f | taylorak/python-demo | /03-if-statement/if_statement.py | 767 | 4.1875 | 4 | '''
Working with if-then statements
'''
def if_else(correct):
"Checks if correct is true or not"
if correct:
print("true statement")
else:
print("false statement")
if_else(True)
if_else(False)
def check_nums(num1, num2):
'''
Checks which number is greater
'''
if num1 > num2:
print("{} is greater than {}".format(num1, num2))
elif num2 > num1:
print("{} is greater than {}".format(num2, num1))
else:
print("{} is equal to {}".format(num1, num2))
check_nums(1, 2)
check_nums(2, 1)
check_nums(2, 2)
def ternary_if(correct):
"Checks if correct is true or not"
statement = "true statment" if correct else "false statment"
print(statement)
ternary_if(True)
ternary_if(False)
| true |
f325e2ecd71b06b20c57d57bcf31148c0d76cadf | joamho-luiz/notas-python | /cohdigo/aula07.py | 782 | 4.1875 | 4 | # DESAFIO 005
"""n1 = int(input('Digite um número inteiro: '))
print('Antes do {} temos {} e depois o {}.'.format(n1, n1-1, n1+1))"""
# DESAFIO 006
"""n2 = int(input('Digite um número inteiro: '))
print('{} elevado ao quadrado é: {}.'.format(n2, n2**2))
print('{} elevado ao cubo é: {}.'.format(n2, n2**3))
print('A raiz de {} é: {:.2f}.'.format(n2, float(n2**(1/2))))"""
# DESAFIO 007
"""n3 = int(input('Primeira nota: '))
n4 = int(input('Segunda nota: '))
print('A média do aluno é: {:.1f}'.format(float((n3+n4)/2)))"""
# DESAFIO 008
"""print('-|-|-|- Conversor de metros -|-|-|-')
n5 = int(input('Digite o valor em metros: '))
print('{}m é igual a: {}cm'.format(n5, n5*100))
print('{}m é igual a: {}mm'.format(n5, n5*10**3))"""
# DESAFIO 009 a 13
# Depois eu faço.
| false |
2e1e275dd7191f8b18fe73af0a8d7cde49c95289 | gaurangalat/SI506 | /Gaurang_DYU2.py | 1,163 | 4.3125 | 4 | #Week 2 Demonstrate your understanding
print "Do you want a demo of this week's DYU?\nA. Yes B. Not again\n"
inp = raw_input("Please enter your option: ") #Take input from user
if (inp =="B" or inp =="b"):
print "Oh well nevermind"
elif(inp == "A" or inp =="a"): #Check Option
print "\nHere are a few comic book characters"
d={"Batman" : "Robin", "Asterix": "Obelix", "Tintin" :"Snowy"} #Dictionary Initialization
print d.keys() #Print keys of the dictionary
x= raw_input("\nDo you want to know their sidekicks?\nA. Yes B. No\n")
if (x == "A" or x =="a"): #Check for User Option
y = raw_input("Which character's sidekick would you like to know about? ") #Take input
c=0
for ele in d.keys():
if (y.upper()==ele.upper()): #Compare input and key of ditcionary
print d[ele], "is the sidekick of", y, "\n"
else:
c+=1
if(c==3): #Invalid Input checker
print "Please Check Again"
elif(inp =="B" or inp =="b"):
print "\nOh well nevermind"
else:
print "\nNevermind. Sorry to waste your time :)"
else: #Invalid input checker
print ("\nSorry, wrong option. Run again")
| true |
8db034fea3cc39b02329ea5246f5a526caa3f88d | Ktulu1/Learning_Python3_The_Hard_Way | /ex20-1.py | 1,555 | 4.15625 | 4 | # import argv from library sys
from sys import argv
# setup variables for argv
script, input_file = argv
# define a function that prints the entire contents of the file
def print_all(f):
print(f.read())
# define a function that seeks to the begining of the file
def rewind(f):
f.seek(0)
# define a fuction that prints a specific line in the file
def print_a_line(line_count, f):
print(line_count, f.readline())
# set the a variable for the open file
current_file = open(input_file)
# echo this text to the screen
print("First let's print the whole file:\n")
# call the function print_all
print_all(current_file)
# echo this text to the screen
print("Now let's rewind, kind of like a tape.")
# call the function rewind
rewind(current_file)
# echo this text to the screen
print("Let's print three lines:\n")
# set a variable for line number
current_line = 1
print(f"Current line is {current_line}")
# call the function print_a_line and pass the line number and file object variables
print_a_line(current_line, current_file)
# take the variable for line number and increment it by 1
current_line += current_line
print(f"current line is {current_line}")
# call the function print_a_line and pass the line number and file object variables
print_a_line(current_line, current_file)
# take the variable for line number and increment it by 1
current_line = current_line + 1
print(f"Current line is {current_line}")
# call the function print_a_line and pass the line number and file object variables
print_a_line(current_line, current_file) | true |
9f04f14496b13a8a9b851f6758bf9b0dfb62c46a | Ktulu1/Learning_Python3_The_Hard_Way | /ex16.py | 1,209 | 4.28125 | 4 | # load argv from the sys library
from sys import argv
# define variables for argv
script, filename = argv
# echo some text with a varaible in it
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you want that, hit RETURN.")
# set the prompt
input("?")
# echo some text about what's going on
print("Opening the file...")
# open the file as file object "target" in write mode
target = open(filename, 'w')
# more echoed text
print("Truncating the file. Goodbye!")
# use the truncate command on the file object "target"
target.truncate()
# echo some instructions
print("Now we're goign to ask you for three lines.")
# input 3 strings named line1...
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
# more status updates echoed to the screen
print("I'm going to write these to the file.")
# use the write command to write the imput from above to the file object "target" and write a new line - 3 times
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
# more status echoed
print("And finally, we close it.")
# close the file object "target"
target.close() | true |
fdaae9577fa0821a143ca185cc1019d03bcf5202 | Nathnos/probabilistic_battleships | /game/board_setup.py | 1,920 | 4.1875 | 4 | """
Main game functions
"""
import numpy as np
from game.game_tools import (
get_direction,
get_boat_size,
get_random_direction,
get_random_position,
)
def can_place(grid, boat, position, direction):
"""
grid : numpy array
boats : represented by an integer
position : tuple (x, y)
direction : left, right, top or bottom
"""
x_dir, y_dir = get_direction(direction)
boat_size = get_boat_size(boat)
x, y = position
for i in range(boat_size):
x_i = x + i * x_dir
y_i = y + i * y_dir
if x_i >= 10 or x_i < 0 or y_i >= 10 or y_i < 0 or grid[y_i, x_i]:
return False
return True
def place(grid, boat, position, direction, append=False):
"""
Returns where or not the boat has been placed.
"""
if not can_place(grid, boat, position, direction) and not append:
return False
x_dir, y_dir = get_direction(direction)
boat_size = get_boat_size(boat)
x, y = position
if append:
for i in range(boat_size):
grid[y + i * y_dir, x + i * x_dir] += 1
else:
for i in range(boat_size):
grid[y + i * y_dir, x + i * x_dir] = boat
return True
def generate_random_grid(boat_list=range(1, 6)):
"""
Generate a random grid, making sure boats don't share same position.
"""
grid = get_empty_grid()
for boat in boat_list:
random_placement(grid, boat)
return grid
def get_empty_grid():
return np.zeros((10, 10), dtype=np.uint8)
def random_placement(grid, boat):
"""
Try a random location, until it's possible (no other boats there).
"""
placed = False
while not placed:
direction = get_random_direction()
position = get_random_position()
placed = place(grid, boat, position, direction)
def show(grid):
print(grid)
def eq(grid1, grid2):
return (grid1 == grid2).all()
| true |
221c0daa1d412fc285fd01b8386202029931e2d0 | arnab-arnab/Python-Course | /06.Chapter 6/Question 4.py | 211 | 4.15625 | 4 | text=input("Enter the text:\n")
a=len(text)
print("Length is:",a)
if(a<10):
print("The length is less than 10")
if(a>10):
print("The length is greater than 10")
if(a is 10):
print("The length is 10") | true |
f1e5cca8210d307dbe84e01717b19d11ee7298f9 | arnab-arnab/Python-Course | /04.Chapter 4/Question_3.py | 403 | 4.25 | 4 | print("Enter three elements to be stored in tuple")
a1=input("Enter the 1st element: ")
a2=input("Enter the 2nd element: ")
a3=input("Enter the 3rd element: ")
tupl=(a1,a2,a3)
print(tupl)
print("Which of the element of the tuple would you try to change\n")
print("0\t1\t2\n")
a4=input("Enter the index value from the above:")
a5=input("Enter the new element:")
tupl[a4]=a5 # <-- Error
print(tupl)
| true |
6002071aa47b871e3cfb4121562fcc334392ebf3 | arnab-arnab/Python-Course | /05.Chapter 5/02_Dictionary_Methods.py | 1,239 | 4.375 | 4 | myDict={
"Fast":"In a quick manner",
"Arnab":"A coder",
"Marks":[1,2,5],
"Li":(3,44,6),
"Number": 5,
"anotherDict":{"Devesh":"Doggy",
"Sneha":"Bitch",
"Deborshi":"Cow",
"Sex_Position":69
}
}
# DICTIONARY METHODS
print(tuple(myDict.keys())) # We can convert the keys of the dictionary to a tuple
print(list(myDict.keys())) # We can convert the keys of a dictionary to a list
print(myDict.values()) # Prints the values inside the dictionary
print(myDict.keys()) # Prints all the keys of the dictionary
print(myDict.items()) # Prints all the keys, values for all items of the dictionary
print(myDict)
updateDict={
"Devesh":"Friend", # Here devesh is not updated because it is inside nested dictionary
56:69,
"Arnab":"A programmer" # Here it also updates arnab from a coder to a programmer
}
myDict.update(updateDict) # Updates the dictionary with the new keys and values
print(myDict)
print(myDict.get("Devesh")) # It searches for a key
print(myDict["Devesh"])
print(myDict.get("Devesh2")) # It does not throw error
# print(myDict.grt("Devesh2")) <-- It throws error | true |
7edb376678fb9e3a64e821b0f5fee8beab517875 | arnab-arnab/Python-Course | /08.Chapter 8/03_factorial.recursion.py | 585 | 4.375 | 4 | '''
fact=int(input("Enter the number till which you need factorial:\n"))
product=1
for i in range(1,fact+1):
product=product*i
print(product)
*****************************A NORMAL FACTORIAL PROGRAM ABOVE*********************************
'''
def fact_recr(n):
if(n is 1 or n is 0):
return 1
return n*fact_recr(n-1) # Mujhe bhi kuch samaj nehi aaya idhar
''' dekho ye aapda ko kaise talte hai
factorial(5)
--> 5*factorial(4)
--> 5*4*factorial(3)
--> 5*4*3*factorial(2)
--> 5*4*3*2*factorial(1)
--> 5*4*3*2*1
=120
'''
# SAMAJ ME AAYA KYA
f=fact_recr(5)
print(f) | false |
f7ed51b9039ee4b5488431c519be8027e383b5e6 | markkampstra/examples | /Python/fizzbuzz.py | 1,620 | 4.25 | 4 | #!/usr/bin/python
# FizzBuzz by Mark Kampstra
#
# Write a program that prints the numbers from 1 to 100.
# But for multiples of 3 print "Fizz" instead of the number and for the multiples of five print "Buzz".
# For numbers which are multiple of both 3 and 5, print "FizzBuzz".
#
import string
class FizzBuzz:
'''The FizzBuzz class'''
def __init__(self):
self.result = ""
def do_fizz_buzz(self):
# return the FizzBuzz sequence in a string
# create an array with numbers 1 to 100
numbers = range(1,101)
# loop though the array of numbers and check whether to print 'Fizz', 'Buzz', 'FizzBuzz' or just the number
for n in numbers:
if n % 3 == 0:
self.fizz()
if n % 5 == 0:
self.buzz()
if (n % 3 != 0) and (n % 5 != 0):
self.result += "%d" % (n)
# add a space
self.result += ' '
return self.result[:-1] # remove trailing space and return
def fizz(self):
self.result += "Fizz"
def buzz(self):
self.result += "Buzz"
def fizz_buzz_oneliner(self):
# FizzBuzz in one line
return string.join(["FizzBuzz" if x%15 == 0 else "Fizz" if x%3 == 0 else "Buzz" if x % 5 == 0 else str(x) for x in range(1,101)])
def main():
fizz_buzz = FizzBuzz()
result1 = fizz_buzz.do_fizz_buzz()
result2 = fizz_buzz.fizz_buzz_oneliner()
print 'FizzBuzz'
print
print 'do_fizz_buzz() result:'
print result1
print
print 'fizz_buzz_oneliner result:'
print result2
if result1 == result2:
print 'Both results are the same! \o/'
else:
print 'Oops, something is not right :\'('
if __name__ == "__main__":
main() | true |
ea3cd26f2804b5ac8850ea448d8dcb23f9e1cca9 | dbozic/useful-functions-exploration | /column_unique_values.py | 1,252 | 4.71875 | 5 | def column_unique_values(data, exclusions):
"""
This function goes through each column of a dataframe
and prints how many unique values are in that column.
It will also show what those unique values are. The
function is particularly useful in exploratory data
analysis for quick understanding of column content
within the dataframe. Assumes that pandas has
been imported.
INPUTS:
data: dataframe to be analyzed.
exclusions: a list of columns as strings to be excluded, e.g. exclusions = ['column1', 'column2']
If no exclusions, then input 'exclusions = []'.
OUTPUT:
print statements
"""
# First, we select only those columns that are implicitly included
selection = data.drop(exclusions, axis = 1)
# Then we parse through every column of the dataframe
for column in selection.columns.values:
print('Column {x} has {y} unique values.').format(x = column, y = len(data[column].unique()))
print('')
print('Those unique values are:')
print('')
print(data[column].unique())
print('')
print('- - - - - - - - - - - - - - - - - -')
print('')
| true |
ae172af54bc2698ce83bedd94416e22847593e60 | QkqBeer/PythonSubject | /面试练习/29.py | 1,205 | 4.1875 | 4 | # __author__ = "那位先生Beer"
#
#
# def divide( dividend, divisor ):
# """
# :type dividend: int
# :type divisor: int
# :rtype: int
# """
# flag = 0
# dividendn = abs( dividend )
# divisorn = abs( divisor )
# while dividendn > 0:
# if dividendn >= divisorn:
# dividendn -= divisorn
# flag += 1
# else:
# break
# print(flag)
# return flag if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) else 0 - flag
# print(divide(7, -3))
def divide( dividend, divisor ):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
MAX_INT = 0x7fffffff
if divisor == 0: return MAX_INT
sign = 1
if divisor < 0:
sign = -sign
divisor = -divisor
if dividend < 0:
sign = -sign
dividend = -dividend
res = 0
while dividend >= divisor:
redu = divisor
res0 = 1
while dividend > redu * 2:
res0 <<= 1
redu <<= 1
dividend -= redu
res += res0
if sign < 0:
res = -res
if res > MAX_INT:
res = MAX_INT
return res
print(divide(-2147483648, -1)) | false |
69c059b8b6f1f9665fa8857a9e039c5bb4ba2c45 | mengbinsu/Core_Python_Programming | /ch6/Exam/6.3.py | 638 | 4.34375 | 4 | #!/usr/bin/env python
import string
def des_sort_numstr_by_decimal(numstr):
numlist = numstr.split(',')
for i in range(0, len(numlist)):
numlist[i] = int(numlist[i])
numlist.sort()
numlist.reverse()
return numlist
def des_sort_numstr_by_dictionary(numstr):
numlist = numstr.split(',')
numlist.sort()
numlist.reverse()
return numlist
if __name__ == '__main__':
numstr = raw_input('input some numbers: ')
print 'before sort: ' + numstr
print 'sort by decimal:' + str(des_sort_numstr_by_decimal(numstr))
print 'sort by dictionary:' + str(des_sort_numstr_by_dictionary(numstr))
| false |
2d00ae0f6dae836d393953e41555dd6b9d130f7a | anhnguyendepocen/Python_learning | /mypolygon.py | 986 | 4.28125 | 4 | #!/usr/bin/python
# Filename:mypolygon.py
from swampy.TurtleWorld import *
import math
world = TurtleWorld()
bob = Turtle()
print bob
def square(t, dist):
for i in range(4):
fd(t,dist)
lt(t)
bob.delay = 0.01
def polygon(t, dist, n):
for i in range(n):
fd(t,dist)
lt(t, 360.0/n)
def ployline(t, dist, n, angle):
"""Draws n line segments with the given length and
angle (in degrees) between them. t is a turtle.
"""
for i in range(n):
fd(t, dist)
lt(t, angle)
def arc(t, r, angle):
"""Draws a part of a circle with the given r and
angle (in degrees). t is a turtle.
"""
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n
ployline(t, step_length, n, step_angle)
def circle(t, r):
arc(t, r, 360)
# square(bob, 100)
# polygon(bob, 30, 5)
#arc(bob, 40, 60)
#circle(bob, 40)
#wait_for_user()
| false |
45af716bb44964e643e8bf989626a735719dbdca | judyohjo/Python-exercises | /Python exercise 12 - List.py | 396 | 4.3125 | 4 | '''
Exercise 12 - Get the smallest number from each list and create a new list and print that new list.
'''
list1 = [1, 3, 5, 0, 2, 3]
list2 = [3, 5, 3, 56, 7, 22]
list3 = [67, 34, 24, 15, 88, 99]
newlist = []
smallest1 = min(list1)
smallest2 = min(list2)
smallest3 = min(list3)
newlist.append(smallest1)
newlist.append(smallest2)
newlist.append(smallest3)
print(newlist)
| true |
fbaf080f19aea0424908dfa870cf4213753b719a | judyohjo/Python-exercises | /Python exercise 11 - Input.py | 209 | 4.21875 | 4 | '''
Exercise 11 - Input a number and print the number of times of "X" (eg. if number is 3, print...
X
XX
XXX)
'''
num = int(input("Input a number: "))
for i in range(1, num+1):
print(i*"X")
| true |
a05605bc741df904178fa79706fc90b7bedd50bf | schappidi0526/IntroToPython | /20_IterateOnDictionary.py | 811 | 4.65625 | 5 | grades={'Math': 100,
'Science': 80,
'History': 60,
'English': 50}
grades['Biology']=70
#To print just keys
for key in grades:
print(key)
#To print keys along with their values
for key in grades:
print(key,grades[key])
for key in grades.keys():
print(key,grades[key])
#To print values from a dictionary
for value in grades.values():
print (value)
#keys and values are dynamic objects and read only. When the dict changes these will change
values=grades.values()
keys=grades.keys()
print (sorted(keys))
print (sorted(values))
#to make changes to the keys
"""though keys structure appear to be as lists but those
are not lists, we need to convert to list to make changes"""
keys_l=list(keys)
keys_l.append('Zoology')
print(keys_l)
| true |
eb63068b4b356aa525322e418921c6b23f681c6b | schappidi0526/IntroToPython | /22_Update&DeleteDictionary.py | 1,088 | 4.3125 | 4 | #Merge/Update dictionary
dict1={'Math':99,
'science':98,
'history':33}
dict2={'telugu':88,
'hindi':77,
'english':99,
'Math':69}#If you have same keys in both dictionaries,values will be updated
dict1.update(dict2)
print (dict1)
dict2.update(dict1)
print(sorted(dict2.keys()))
print(sorted(dict2.values()))
#Delete keys in dictionary based on the keys
del dict1["hindi"]
print (dict1)
dict1.pop('english')
print (dict1)
#if you try to pop a key that doesn't exist, it will throw keyerror
# dict1.pop('hindi')
# print (dict1)
#clear all elements
dict1.clear()
print (dict1)
#get function
print (dict1.get('hindi'))
"""By default above will print 'None'. If a key doesn't exist and if you want to specify a
value other than 'None'"""
print (dict1.get('hindi','Not found'))
#Add lists to dictionary
L1=[1,2,3,4,5]
count=['count1','count2','count3','count4','count5']
dict2={"l1":L1,
"count":count}
print (dict2)
#Another way
d1=dict(zip(L1,count))
print (d1)
print (help()) | true |
9a403dad3118c5410b09b4969f8e2ff2f7fb41f1 | problems-forked/Dynamic-Programming | /0_1 Knapsack/Programmes/main(14).py | 1,149 | 4.15625 | 4 |
def find_target_subsets(num, s):
totalSum = sum(num)
# if 's + totalSum' is odd, we can't find a subset with sum equal to '(s + totalSum) / 2'
if totalSum < s or (s + totalSum) % 2 == 1:
return 0
return count_subsets(num, int((s + totalSum) / 2))
# this function is exactly similar to what we have in 'Count of Subset Sum' problem.
def count_subsets(num, s):
n = len(num)
dp = [[0 for x in range(s+1)] for y in range(n)]
# populate the sum = 0 columns, as we will always have an empty set for zero sum
for i in range(0, n):
dp[i][0] = 1
# with only one number, we can form a subset only when the required sum is
# equal to the number
for s in range(1, s+1):
dp[0][s] = 1 if num[0] == s else 0
# process all subsets for all sums
for i in range(1, n):
for s in range(1, s+1):
dp[i][s] = dp[i - 1][s]
if s >= num[i]:
dp[i][s] += dp[i - 1][s - num[i]]
# the bottom-right corner will have our answer.
return dp[n - 1][s]
def main():
print("Total ways: " + str(find_target_subsets([1, 1, 2, 3], 1)))
print("Total ways: " + str(find_target_subsets([1, 2, 7, 1], 9)))
main() | true |
e8394e8222e225d194d080a264743172b11a28b9 | Rhapsody0128/python_learning | /base/03.for.py | 383 | 4.25 | 4 | students=["bonny","jack","rose"]
for student in students :
print(student)
print("hello !")
# 建立一個students串列
# 告知python從students串列中取出名字,並將取出的名字存到student變數內
# 印出student變數取到的名字
# 跳出迴圈並印出hello
# *迴圈內執行的東西要記得縮排,若不是迴圈內要執行的東西則不用縮排 ! | false |
1e9c999f99c01c8289e891f0abc516ce901213b4 | Rhapsody0128/python_learning | /base/08.input.py | 1,377 | 4.5 | 4 | # input()函式會讓程式暫停,等待使用者輸入一些文字,python在取得使用者輸入文字後,會把我們輸入的文字存到一個變數內
# * 一般的input()函式
name = input("please enter your name : ")
print("hello,"+name) # 因為name是字串所以可以直接跟"hello,"字串相加f
# * 用int()來取得輸入的字串
age = input("how old are you ?") # 使用者輸入的東西都算是字串
age = int(age) # 將age變數轉成int的型態再傳回age變數中
if age >= 20 : # age變數轉為數值後才可以比大小不然會出錯
print("can vote")
else :
print("can't vote")
# * 模術運算子( % )
number = input("please enter a number : ")
number = int(number) # 將number變數轉成int的型態再傳回number變數中
if number % 2 ==0 : # 判斷是否除2會整除
print("It's even") # 如果整除2就是偶數
else :
print("It's odd") # 如果們有整除2就是奇數
# 如果是在python 2 的版本中,使用者輸入的方法是用raw_input()函式,用法和python 3 的input()函式相同,都會把接收的輸入解讀成字串
text = "apple banana apple grape apple apple watermelon" # 建立一個text字串
find = input("which word do you want to find ?") # 輸入一個值存到find變數中
print(text.count(find)) # 用count()方法來找find變數的值在text字串裡出現幾次 | false |
5e98df340cc93a5c839aea8ca82a91c09ed83d3f | dwangnew/euler | /9.py | 1,270 | 4.1875 | 4 |
# Special Pythagorean triplet
# Problem 9
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
import math
# while a+b+c <= 1000:
# if a+b+c == 1000:
# print "we found a winner!!!", a, b, c
# break
def find_pythag_trips(n):
""" finds n number of pythagorean triplets and returns a list with all of them"""
list1 = []
winner = ["JFOWIJFOEJFOEIJFOWEJFOEWIJFEOIFJOWEIFJOWEJFOEIWFJOIWEFJOEWFJOIWEFJOEWFJOIEWFJOEWIFJOIFOEWIJFOEWFJOEIWFJOEWJOEIF"]
a = 3
print "starting function 'find_pythag_trips'"
while a<n:
# print "starting first while loop"
b = a + 1
c = math.sqrt(a**2 + b**2)
print a, b, c
if c - int(c) == 0:
print a, b, c, "is a triplet"
list1.append([a,b,c])
if a+b+c == 1000:
winner.append([a,b,c])
while b/a <20:
# print "starting second while loop"
b += 1
c = math.sqrt(a**2 + b**2)
print a, b, c
if c - int(c) == 0:
print a, b, c, "is a triplet"
list1.append([a,b,c])
if a+b+c == 1000:
winner.append([a,b,c])
a += 1
# print "end of first while loop"
return list1, winner
print find_pythag_trips(500) | false |
6e6b8dbcdd7d5cbfef4c7ae9005cbd2639671f18 | fanliu1991/LeetCodeProblems | /38_Count_and_Say.py | 1,473 | 4.21875 | 4 | '''
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the n-th term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
'''
import sys, optparse, os
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
integer = "1"
for _ in range(n-1):
digit = integer[0]
digit_count = 0
output = ""
for num in integer:
if num == digit:
digit_count += 1
else:
output = output + str(digit_count) + digit
digit = num
digit_count = 1
integer = output + str(digit_count) + digit
return integer
# n = 5
# solution = Solution()
# result = solution.countAndSay(n)
# print result
solution = Solution()
for n in range(1,6):
result = solution.countAndSay(n)
print(n, result)
'''
Complexity Analysis
Time complexity : O(logn).
Binary search solution.
Space complexity : O(1).
No extra space is used. Only two extra variables left and right are needed.
''' | true |
da22091944898edbfca31ed8919e568a6802d8ec | fanliu1991/LeetCodeProblems | /75_Sort_Colors.py | 2,115 | 4.28125 | 4 | '''
Given an array with n objects colored red, white or blue,
sort them in-place so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2
to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's,
then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
'''
import sys, optparse, os
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
'''
Initially, we set the frist 1 and first 2 at position 0,
For every number in the nums, we set it as 2,
if it is 2, then we done,
else if it is 0 or 1, then we set the value at first 2 position as 1 and mover forward the first 2 position,
if it is 1, then we done,
else if it is 0, then we set the value at first 1 position as 0 and mover forward the first 1 position.
hence, [0, first_one), [first_one, first_two), [first_two, k) are 0s, 1s and 2s sorted in place for [0,k).
'''
first_one, first_two = 0, 0
for i in range(len(nums)):
value = nums[i]
nums[i] = 2
if value < 2:
nums[first_two] = 1
first_two += 1
if value == 0:
nums[first_one] = 0
first_one += 1
nums = [2,0,2,1,1,0]
solution = Solution()
result = solution.sortColors(nums)
print result
'''
Complexity Analysis
Time complexity : O(n).
We are doing one pass through the nums.
Space complexity : O(1).
Nums are sorted in place and no extra space is used. Only extra variables are needed.
'''
| true |
0cd58414e3ad8e23d1532ba3509d4e005d9f5cf0 | fanliu1991/LeetCodeProblems | /89_Gray_Code.py | 1,833 | 4.25 | 4 | '''
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code,
print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
'''
import sys, optparse, os
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
"""
n = 0, 0 = 0
n = 1, 0 = 0
1 = 1
n = 2, 00 = 0
01 = 1
11 = 3
10 = 2
n = 3, 000 = 0
001 = 1
011 = 3
010 = 2
110 = 6
111 = 7
101 = 5
100 = 4
for n bits sequence,
add 2^(n-1) to each value in the reversed sequence of n-1 bits,
i.e. replace the first bit of n-bit number from 0 to 1,
will generate the sequence of n bits
"""
if n == 0:
return [0]
# spical case, which should be [], but accepted answer is [0]
result = [0]
for i in range(n):
result = result + [value + 2**i for value in reversed(result)]
return result
n = 4
solution = Solution()
result = solution.grayCode(n)
print result
'''
Complexity Analysis
Time complexity : O(2^n).
We are doing one pass through each of the list
with length 2, 4, 8, ..., 2^(n-1).
Space complexity : O(2^n).
Extra space is used to store 2^n values of n bits sequence.
'''
| true |
5a81227b5affe10bfea4b5acabb0dcea57f9ec68 | fanliu1991/LeetCodeProblems | /125_Valid_Palindrome.py | 1,278 | 4.1875 | 4 | '''
Given a string, determine if it is a palindrome,
considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
import sys, optparse, os
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
s = s.lower()
left = 0
right = len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left] != s[right]:
return False
else:
left += 1
right -= 1
return True
s = "A man, a plan, a canal: Panama"
solution = Solution()
result = solution.isPalindrome(s)
print result
'''
Complexity Analysis
Time complexity: O(n).
We are doing a single pass through the string, hence n steps,
where n is the length of price array.
Space complexity : O(1).
No extra space is used. Only extra variables are needed.
'''
| true |
97de3552794dbc0e04be28659349f09d415702ba | fanliu1991/LeetCodeProblems | /101_Symmetric_Tree.py | 2,889 | 4.25 | 4 | '''
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Example 1:
input: binary tree [1,2,2,3,4,4,3]
output: True
1
/ \
2 2
/ \ / \
3 4 4 3
Example 2:
input: binary tree [1,2,2,null,3,null,3]
output: False
1
/ \
2 2
\ \
3 3
'''
import sys, optparse, os
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# recursive solution
def isMirror(left_subtree, right_subtree):
if left_subtree == None and right_subtree == None:
return True
elif left_subtree == None or right_subtree == None:
return False
if left_subtree.val != right_subtree.val:
return False
else:
ans = isMirror(left_subtree.left, right_subtree.right) and \
isMirror(left_subtree.right, right_subtree.left)
return ans
if root == None:
return True
else:
res = isMirror(root.left, root.right)
return res
# iterative solution
'''
stack = []
if root == None:
return True
stack.append((root.left, root.right))
while stack:
subtrees = stack.pop()
left_subtree = subtrees[0]
right_subtree = subtrees[1]
if left_subtree == None and right_subtree == None:
continue
elif left_subtree == None or right_subtree == None:
return False
if left_subtree.val != right_subtree.val:
return False
else:
stack.append((left_subtree.left, right_subtree.right))
stack.append((left_subtree.right, right_subtree.left))
return True
'''
root = [1,2,2,3,4,4,3]
solution = Solution()
result = solution.isSymmetric(root)
print result
'''
Complexity Analysis
Time complexity : O(n).
We traverse the entire input tree once, the total run time is O(n),
where n is the total number of nodes in the tree.
Space complexity :
recursive method: O(logN).
The number of recursive calls is bound by the height of the tree.
But in the worst case, the tree is linear, i.e. each node has only one child.
Therefore, the height of tree is in O(n),
space complexity due to recursive calls on the stack is O(n) in the worst case.
iterative method: O(n).
There is additional space required for the search queue.
In the worst case, we have to insert O(n) nodes in the queue.
Therefore, space complexity is O(n).
'''
| true |
c95cc386832630e4fee7e56c2ec320cc4abd0978 | Darya1501/python | /Раздел 7. Минимумы и максимумы.py | 1,663 | 4.125 | 4 | print("Раздел 7. Минимумы и максимумы")
print("Задача 6. Дано целое число N и набор из N целых чисел. Найти номера первого минимального и последнего максимального элемента из данного набора и вывести их в указанном порядке.")
print("Решение: ")
s = int(input("Введите размер массива: "))
a = [0]*s
print("Введите элементы массива: ")
for i in range(0, s):
a[i] = int(input())
minin = 0
maxin = 0
for f in range(0, s):
if a[f] < a[minin]:
minin = f
for b in range(0, s):
if a[b] >= a[maxin]:
maxin = b
print("Порядковый номер первого минимального:", minin+1, ", порядковый номер последнего максимального:", maxin+1)
print("____________")
print("Задача 17. Дано целое число N и набор из N целых чисел. Найти количество элементов, расположенных после последнего максимального элемента.")
print("Решение: ")
s = int(input("Введите размер массива: "))
a = [0]*s
print("Введите элементы массива: ")
for i in range(0, s):
a[i] = int(input())
maxin = 0
for b in range(0, s):
if a[b] >= a[maxin]:
maxin = b
s = s - maxin - 1
print("Элементов после последнего максимального:", s)
| false |
97d3deb5ca9a1c43dc506e2844df03243be31ffb | mmxm0/IP_Listas_SI1 | /locadora_antes_da_Netflix.py | 2,379 | 4.125 | 4 | """ 2 - Houve uma época em que, quando as pessoas queriam assistir um filme, iam até a
locadora.
Crie uma classe filme que contém os atributos
gênero, nome, disp_catalogo. Você deve criar um método que altere
a disponibilidade do filme, gets e sets.
Em seguida crie uma classe Locadora, essa classe contém uma lista de todos os
filmes já cadastrados no sistema, crie metodos para listar os
filmes por gênero(Ação, Aventura e Romance), dizer quantos filmes estão alugados(total de todos os filmes),
alugar filmes e devolver.
"""
class Filme:
def __init__(self, nome,genero, disp_catalogo=True):
self.__genero = genero
self.__titulo = nome
self.__disponibilidade = disp_catalogo
def getGenero(self):
return self.__genero
def getTitulo(self):
return self.__titulo
def getDisponibilidade(self):
return self.__disponibilidade
def setGenero(self, novo):
self.__genero = novo
def setTitulo(self, novo):
self.__titulo = novo
def setDisponibilidade(self, novo):
self.__disponibilidade = novo
def __str__(self):
titulo = self.__titulo
return titulo.title()
class Locadora(Filme):
def __init__(self, filmes=[]):
self.__filmes = filmes
self.__alugados = 0
def listaGenero(self, genero):
print("Filmes de %s\n"%genero)
for i in self.__filmes:
if i.getGenero() == genero:
print(i.getTitulo())
def listaAlugados(self):
return "%i filmes alugados "%self.__alugados
def aluga(self, titulo):
for i in self.__filmes:
if i.getTitulo() == titulo and i.getDisponibilidade() == True:
i.setDisponibilidade(False)
break
else:
print("título indisponível ou invalido")
def devolve(self, titulo):
for i in self.__filmes:
if i.getTitulo() == titulo and i.getDisponibilidade() == False:
i.setDisponibilidade(True)
break
else:
print("título disponível ou invalido")
def setFilme(self, novo):
self.__filmes.append(novo)
def getCatalogo(self):
for i in self.__filmes:
print(i)
| false |
d0c942747f97ffb0f6f506614ccd7ee46c1caa69 | mmxm0/IP_Listas_SI1 | /9.py | 310 | 4.34375 | 4 | '''
Reverso do número. Faça uma função que retorne o reverso de um número inteiro informado. Por exemplo: 127 -> 721.
'''
def reverseNumber(n):
n = str(n)
return n[::-1]
n = int(input("Informe o numero: "))
reverso = reverseNumber(n)
print("O reverso do numero informado é:", reverso)
| false |
a121b4284049a34674c5239c4f487e87381a4234 | mmxm0/IP_Listas_SI1 | /Listas_9.py | 777 | 4.3125 | 4 | from random import randint
'''Faça um programa que crie uma matriz aleatoriamente e guarde em uma lista. As
dimensões da matriz deverão ser informadas pelo usuário. O programa deverá
imprimir a matriz criada na tela, no formato m x n. Ex:
Matriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Exibir na tela:
1 2 3
4 5 6
7 8 9 '''
z = 0
matriz = []
x = int(input("Informe a quantidade de linhas da matriz: "))
y = int(input("Informe a quantidade de colunas da matriz: "))
for i in range(x):
num = ("%d%d" % (randint(0, 9), randint(0, 9)))
num2 = ("%d%d" % (randint(0, 9), randint(0, 9)))
matriz.append([num]*y)
matriz[i][i] = num2
while z < x:
for i in range(y):
print(matriz[z][i], end=" ")
z += 1
print()
| false |
25b9a16a37807b7edc6392f0227ed06a19bcd556 | mmxm0/IP_Listas_SI1 | /Jogo_de_Craps.py | 2,012 | 4.1875 | 4 |
'''
Jogo de Craps.
Faça um programa de implemente um jogo de Craps.
O jogador lança um par de dados, obtendo um valor entre 2 e 12.
Se, na primeira jogada, você tirar 7 ou 11, você um "natural" e ganhou.
Se você tirar 2, 3 ou 12 na primeira jogada, isto é chamado de "craps" e você perdeu.
Se, na primeira jogada, você fez um 4, 5, 6, 8, 9 ou 10,este é seu "Ponto".
Seu objetivo agora é continuar jogando os dados até tirar este número novamente.
Você perde, no entanto, se tirar um 7 antes de tirar este Ponto novamente.
'''
from random import choice
lista1 = [1,2,3,4,5,6]
lista2 = lista1[:]
pontos = [4,5,6,8,9,10]
contadorJogadas = 0
ponto = 0
def jogaDados(lista1, lista2):
dado1 = choice(lista1)
dado2 = choice(lista2)
result = dado1 + dado2
return result
def encontrapontonovamente(ponto, contadorJogadas, valorDado):
if valorDado == 7:
print("Você tirou 7 e perdeu :(")
while valorDado != 7:
valorDado = jogaDados(lista1, lista2)
print('Os dados rolaram e juntos deram: %i' %valorDado)
contadorJogadas +=1
if ponto == valorDado:
print("Você jogou os dados %i vezes \nTirou %i e ganhou!!!" %(contadorJogadas, valorDado))
break
while True:
jogada = input("Quer jogar Craps? [S/N]: ")
jogada = jogada.upper()
if jogada == 'N':
break
valorDado = jogaDados(lista1, lista2)
print('Os dados rolaram e juntos deram: %i' %valorDado)
if valorDado == 7 or valorDado == 11:
print("Você é um natural e ganhou!")
break
if valorDado == 2 or valorDado == 3 or valorDado == 12:
print("CRAPS você perdeu!")
break
for i in pontos:
if i == valorDado:
contadorJogadas += 1
ponto = i
encontrapontonovamente(ponto, contadorJogadas, valorDado)
break
| false |
6bbff894065548d6faf0552fc9b149e8146cb8cb | mmxm0/IP_Listas_SI1 | /funcao_embaralhaPalavra.py | 675 | 4.3125 | 4 | '''Embaralha palavra. Construa uma função que receba uma string como parâmetro e
devolva outra string com os carateres embaralhados. Por exemplo:
se função receber a palavra python, pode retornar npthyo, ophtyn ou qualquer outra
combinação possível, de forma aleatória. Padronize em sua função que todos os caracteres
serão devolvidos em caixa alta ou caixa baixa,
independentemente de como foram digitados.'''
from random import shuffle
def embralhapalavra(p):
p = p.upper()
p = list(p)
shuffle(p)
palavra = ''
for i in p:
palavra += i
print(palavra)
p = input("Informe uma palavra: ")
embralhapalavra(p)
| false |
14f5a244dc9462b2e9beda153b8e0b8145d904a5 | yusheng88/RookieInstance | /Rookie039.py | 832 | 4.40625 | 4 | # -*- coding = utf-8 -*-
# @Time : 2020/6/23 22:52
# @Author : EmperorHons
# @File : Rookie039.py
# @Software : PyCharm
"""
https://www.runoob.com/python3/python3-array-rotation.html
Python 数组翻转指定个数的元素
例如:(ar[], d, n) 将长度为 n 的 数组 arr 的前面 d 个元素翻转到数组尾部。
"""
import pysnooper
@pysnooper.snoop()
def leftRotate(arr, d, n):
for i in range(d):
leftRotatebyOne(arr, n)
@pysnooper.snoop()
def leftRotatebyOne(arr, n):
temp = arr[0]
for i in range(n - 1):
arr[i] = arr[i + 1]
arr[n - 1] = temp
print(temp)
def printArray(arr, size):
for i in range(size):
print("%d" % arr[i], end=" ")
if __name__ == '__main__':
arr = [1, 3, 5, 4, 11, 16, 43, 66]
leftRotate(arr, 2, len(arr))
printArray(arr, len(arr))
| false |
f4ec75527a590154109325705c90c9192b834349 | caianne/mc102 | /labs/lab20.py | 984 | 4.125 | 4 | # Laboratorio 20 - Sudoku
# Funcao: print_sudoku
# A funcao imprime o tabuleiro atual do sudoku de forma animada, isto e,
# imprime o tabuleiro e espera 0.1s antes de fazer outra modificacao.
# Voce deve chamar essa funcao a cada modificacao na matriz resposta, assim
# voce tera uma animacao similar a apresentada no enunciado.
# Essa funcao nao tem efeito na execucao no Susy, logo nao ha necessidade de
# remover as chamadas para submissao.
from lab20_main import print_sudoku
zeroposi = []
a = 0
b = 0
def vazio(resposta):
# Funcao: resolve
# Resolve o Sudoku da matriz resposta.
# Retorna True se encontrar uma resposta, False caso contrario
def resolve(resposta):
if flag:
for i in range(9):
for j in range(9):
if resposta[i][j]==0: # Captação das posições vazias/nulas
coord=(x,y)
zeroposi.append(list(coord))
flag == False
print_sudoku(resposta)
return False | false |
5c4c4b8c30d09c8a7163d24ff3030fa4b3e0ce34 | Shehu-Muhammad/Python_College_Stuff | /Problem4_CupcakeRequest.py | 459 | 4.125 | 4 | # Shehu Muhammad
# Problem 4 -Requests the number of cupcakes ordered and displays the total cost
# May 7, 2018
orders = int(input("What are the total number of cupcake orders? "))
cost = 0
small = 0.75
large = 0.70
if(orders <= 99 and orders>=1):
cost = cost + (orders*small)
elif(orders >= 100):
cost = cost + (orders*large)
else:
print("No cupcakes were ordered.")
print("The total cost for the cupcakes ordered is $",format(cost,'.2f'),".",sep="")
| true |
52f5d2791e39104aba5f6cfcc90a29eac4d8a693 | Shehu-Muhammad/Python_College_Stuff | /Python Stuff/Rowing.py | 543 | 4.28125 | 4 | #Rowing Program
#Shehu Muhammad
#February 5, 2018
rower1 = int(input("Input weight of rower one: "))
rower2 = int(input("Input weight of rower two: "))
weight = rower1 + rower2
#if((weight >= 300) and (weight <=400)):
#print("You are on the team")
#else:
#print("You are not on the team")
#if((weight >= 300) and (weight <=400)):
#print("You are on the team")
#elif(weight<300 or weight>400):
#print("You are not on the team")
if(300 <= weight <= 400):
print("You are on the team")
else:
print("You are not on the team")
| false |
05228bb597c8d13f1e2e6427a2a307e0abf2ee02 | Shehu-Muhammad/Python_College_Stuff | /Python Stuff/Guess.py | 1,156 | 4.125 | 4 | # Guess my number
# Shehu Muhammad
import random
import math
random.seed()
randomNumber = math.floor(random.random() * 100) + 1 # generates a random number between 1 and 100
guess = 0 # initializes guess to zero
count = 0 # initializes count to 0
while (randomNumber != guess): # loops until guess is equal to random number
count = count+1 # increments count by 1 when guess is wrong
guess = int(input("Guess my number: ")) # askes user for a guess
if (guess < randomNumber): # checks if guess is lower than random number
print("Higher!") # prompts user for a higher guess
elif(guess > randomNumber): # checks if guess is higher than random number
print("Lower!") # prompts user for a lower guess
print("Correct! " + str(count) + " tries.") # Prints "Correct" and number of tries counted until the user guessed the random number
| true |
5a1e50c525e772ece7944a9c7609ac8cb5ad79bb | CoderDojoNavan/python | /basics/4_inputs.py | 985 | 4.125 | 4 | """4: Inputs"""
# Sometimes you might want to ask the user a question. To do that, we use
# a special function called `input`. Functions are covered in `5-functions.py`.
# You can ignore the # pylint comment, it is there to tell tools which analyze
# the code that in fact everything is OK with this line.
days = 365 # pylint: disable=C0103
print('there are ' + str(days) + 'in a normal year')
days = int(input('How many days in a leap year? ')) # pylint: disable=C0103
if days == 366:
print('Well Done!')
else:
print('(Its one more than every other year)')
# Try running the above code, and type in your answer.
# What happens if you try to type a letter instead of a number? Try it now and
# come back
# You should get an ValueError saying that you gave an invalid literal for
# int() This is because we use a thing which is called a cast. By default,
# input gives us a string, but we cannot compare string to an int, so we need
# to convert it to an a number - int.
| true |
78b7f69d1513f3d252d07e30f3970be2beec094b | benjaminhuanghuang/dl-study | /keras_first_network.py | 2,038 | 4.78125 | 5 | '''
Develop Your First Neural Network in Python With Keras Step-By-Step
https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
The steps you are going to cover in this tutorial are as follows:
Load Data.
Define Model.
Compile Model.
Fit Model.
Evaluate Model.
Tie It All Together.
'''
from keras.models import Sequential
from keras.layers import Dense
import numpy
# fix random seed for reproducibility
numpy.random.seed(7)
# load pima indians dataset
dataset = numpy.loadtxt("data/pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
# create model
'''
Models in Keras are defined as a sequence of layers.
We create a Sequential model and add layers one at a time until we are happy with our network topology.
We use a fully-connected network structure with three layers.
Fully connected layers are defined using the Dense class
'''
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu')) #input_dim=8 means 8 input variables
model.add(Dense(8, activation='relu')) # 8 neurons in the laryer,
model.add(Dense(1, activation='sigmoid'))
'''
initialize the network weights to a small random number generated from a uniform distribution (‘uniform‘),
in this case between 0 and 0.05 because that is the default uniform weight initialization in Keras.
'''
'''
Compiling the model uses backend library such as Theano or TensorFlow.
The backend automatically chooses the best way to represent the network for training
'''
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
'''
Fit the model
nepochs is the number of iterations
batch_size is the number of instances that are evaluated before a weight update in the network is performed
'''
model.fit(X, Y, epochs=150, batch_size=10)
'''
Evaluate Model
'''
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) | true |
2265d032ca4fc7148a6ff610e6fdd3d095484c5f | charukiewicz/Numerical-Methods | /convergence.py | 1,501 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Christian Charukiewicz (netid: charuki1)
This compares the rates of convergence between the Newton and Secant methods.
The program will print output values and display a plot in matplotlib.
More info:
- http://en.wikipedia.org/wiki/Newton's_method
- http://en.wikipedia.org/wiki/Secant_method
"""
import numpy as np
import matplotlib.pyplot as plt
import math as mth
def f(x):
return float((5-x)*mth.exp(x)-5)
def fd(x):
return float(-1*mth.exp(x)*(x-4))
secx = []
secy = []
newx = []
newy = []
def secant(func, oldx, x):
oldf, f = func(oldx), func(x)
if (abs(f) > abs(oldf)):
oldx, x = x, oldx
oldf, f = f, oldf
xk = 0
while 1:
dx = f * (x - oldx) / float(f - oldf)
if abs(dx) < 10e-8 * (1 + abs(x)):
return x - dx
oldx, x = x, x - dx
oldf, f = f, func(x)
xk = xk + 1
secx.append(xk)
secy.append(mth.log(x))
def newton(f, fd, x):
f_temp = f(x)
fd_temp = fd(x)
xk = 0
while 1:
dx = f_temp / float(fd_temp)
if abs(dx) < 10e-8 * (1 + abs(x)):
return x - dx
x = x - dx
f_temp = f(x)
fd_temp = fd(x)
xk = xk + 1
newx.append(xk)
newy.append(mth.log(x))
print "NEWTON's METHOD:" , newton(f, fd, 5)
print "SECANT METHOD:" , secant(f, 5, 10)
plt.plot(newx,newy,'r--',secx,secy,'b--')
plt.show() | true |
23ce65dc8e50e30045618ac6514ec174dd470e53 | UskovaKate/Coursework | /2-я часть/3.py | 630 | 4.125 | 4 | #Создать прямоугольную матрицу A, имеющую N строк и M столбцов со случайными элементами.
#Найти наименьший элемент столбца матрицы A, для которого сумма абсолютных значений элементов максимальна.
import numpy as np
N = 6
M = 2
A = np.random.randint(low=-4, high=9, size=(N, M))
print("Матрица:\r\n{}".format(A))
sum = A.sum(axis=0)
index = sum.argmin(axis=0)
min = A.min(axis=0)
min = min[index]
print("Наименьшее значение: {}".format(min))
| false |
290f471ddd312bbc70a62082ff334b20ae88f0e0 | UskovaKate/Coursework | /2-я часть/2.py | 588 | 4.15625 | 4 | #Создать прямоугольную матрицу A, имеющую N строк и M столбцов со случайными элементами.
#Найти наибольшее значение среди средних значений для каждой строки матрицы.
import numpy as np
N = 6
M = 2
A = np.random.randint(low=-4, high=9, size=(N, M))
print("Матрица:\r\n{}".format(A))
Average = A.mean(axis=1)
index = Average.argmax(axis=0)
max = Average.max(axis=0)
print("Наибольшее среднее значение: {}".format(max))
| false |
de96cc585410c8356590a971bd86505045a03f9e | azrlzhao/password-safty-check- | /check_password.py | 1,724 | 4.125 | 4 |
#Password security check code
#
# Low-level password requirements:
# 1. The password is composed of simple numbers or letters
# 2. The password length is less than or equal to 8 digits
#
# Intermediate password requirements:
# 1. The password must consist of numbers, letters or special characters (only: ~!@#$%^&*()_=-/,.?<>;:[]{}|\) any two combinations
# 2. The password length cannot be less than 8 digits
#
# Advanced password requirements:
# 1. The password must consist of three combinations of numbers, letters and special characters (only: ~!@#$%^&*()_=-/,.?<>;:[]{}|\)
# 2. The password can only start with a letter
# 3. The password length cannot be less than 16 digits
# apply all the possible letter symbol letters in the array and use for compare
word=r'''~!@#$%^&*()_=-/,.?<>;:[]{}\|'''
number='0123456789'
letter='abcdefghijklmnopqrstuvwxyz'
passward =input("please input your password:")
safty=0
count=0
#check the password should not be zero
while passward.isspace() or len(passward)==0:
passward =input("passward should not be empty")
#meet the low requirment and set a flag
if len(passward) <=7:
safty=1
#second set flag
elif 7<=len(passward)<=15:
safty=2
elif len(passward)>15:
safty=3
#check if the password has multple combination
for each in passward:
if each in number:
count+=1
break
for each in passward:
if each in word:
count+=1
break
for each in passward:
if each in letter:
count+=1
break
# print state
if safty==1 and count==1:
print('low safty ')
elif safty ==3 and count == 3:
print('high safty')
else:
print('median safty')
| true |
ab7b5ff8e907d45ef3cfbec2bb611ada3b68058d | daninick/test | /word_count.py | 1,318 | 4.375 | 4 | import re
filename = input('''
This program returns the words in a .txt file and their count in it.
Enter a .txt file name: ''')
f = open(filename, 'r')
# Read the file and convert it to a string
text = f.read()
# Ignore the empty lines
text = text.replace('\n', ' ')
# All words in the text are separated by space now.
# Make a list of all words in the text using regular expressions.
words = re.findall(r'\w+',text,re.I)
# Create an empty dictionary
d = {}
# For every word in the list of words check if the word exists in the dictionary.
# If it doesn't exist -> add it as a key and set a count of 1 as a value.
# If the word exists in the dictionary -> simply increase the count with 1.
for word in words:
word = word.lower()
# finds the items that contain a digit and do not put them in the dictionary.
# I presume the words has only word characters and no numbers
match = re.search(r'\d',word)
if match:
pass
else:
if word not in d.keys():
d[word] = 1
else:
d[word] = d[word] + 1
# Prints on the terminal all words and their count even the count of the keywords, alphabetically sorted.
print('''
The words in the file are: ''')
for key in sorted(d.keys()):
print(f"{key}: {d[key]}")
print(f'''
Total unique words used: {len(d)}''') | true |
c38e0d609c3414396e23f7ae50b2bf4695477eb6 | rrotilio/MBA539Python | /p20.py | 482 | 4.15625 | 4 | validInt = False
def doRepeat (str1,int1):
i = 0
while (i < int1):
print(str1)
i = i + 1
print("I like to repeat things.")
varStr = str(input("What do you want me to repeat?: "))
while not validInt:
try:
varInt = int(input("How many times should I repeat it?: "))
if(varInt < 0):
print("I can't repeat something negative times! Choose a positve number")
else:
validInt = True
except:
print("Whole numbers only please. Try again.")
doRepeat(varStr,varInt) | true |
856f36bd79f0866552aa760bd9cea652ee4cfdbb | dwzukowski/PythonDojo | /funwithfunctions.py | 2,051 | 4.625 | 5 | def multiply(list, num):
newList = []
for val in list:
newList.append(val*num)
return newList
#we declare a function called layered_multiples which takes one parameter arr
def layered_multiples(arr):
#we declare a variable called new_array which is an empty list
new_array = []
#we instantiate a for loop which iterates through all values in arr
for val in arr:
#we append a list of 1s equal to val in each coresponding index of new_arr
new_array.append([1]*val)
print new_array
layered_multiples(multiply([2,4,5],3))
"""
Hacker Challenge:
Write a function that takes the multiply function call as an argument. Your new function should return the multiplied list as a two-dimensional list. Each internal list should contain the number of 1's as the number in the original list. Here's an example:
def layered_multiples(arr)
# your code here
return new_array
x = layered_multiples(multiply([2,4,5],3))
print x
# output
>>>[[1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
Create a series of functions based on the below descriptions.
Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5.
The function should multiply each value in the list by the second argument. For example, let's say:
#We declare a function called odd_even that takes no parameters
def odd_even():
#We instantiate a for loop beginning at 1 and ending after 2000
for i in range(1,2001):
#Using the condition expression if, we check if the number is even or odd
if i % 2 == 0:
print "The number is " +str(i) + ". This is an even number"
else:
print "The number is " +str(i) + ". This is an odd number"
odd_even()
Odd/Even:
Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number.
""" | true |
a03dbd25a62938ef0ed68df80d0df1df9983125e | dwzukowski/PythonDojo | /comparingArrays.py | 1,379 | 4.3125 | 4 | #we declare a function called compareArrays which takes two parameters, list one and list two
def compareArrays(list_one, list_two):
#we delcare a variable answer which is string
answer = ""
#we compare the lengths of teh two lists; if they are not equal the list cannot be the same
if len(list_one) != len(list_two):
answer= "The lists are not the same"
else:
#we instantiate a for loop begining at zero and ending at the end of the list
for i in range (0,len(list_one)):
#we compare the value at each index of the list; we exit the loop the first time two indexes are not equal
if list_one[i] != list_two[i]:
answer= "The lists are not the same"
break
else:
answer= "The lists are the same"
print answer
list_one = ['celery','carrots','bread']
list_two = ['celery','carrots','bread',]
compareArrays(list_one, list_two)
"""
Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same." Try the following test cases for lists one and two:
list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
""" | true |
d1f1d9a4d2a03bab8643fb8c00c5dcccf7b1462a | dwzukowski/PythonDojo | /classesIntroBike.py | 2,318 | 4.75 | 5 | #we declare a class called bike
class Bike(object):
#we set some instance variables; the miles variable will start at zero for every instance of this class
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
#we declare a method called displayInfo that, when called, displays that instance's price, speed, and total miles traveled
def displayInfo(self):
print "${}".format(self.price)
print self.max_speed
print "{} miles".format(self.miles)
#we declare a method called ride which increments total miles by 10; we return self to allow method chaining
def ride(self):
print "Riding"
self.miles+= 10
return self
#we declare a method called reverse which decrements the instance's total miles by 5; we return self to allow method chaining
def reverse(self):
print "Reversing"
self.miles-= 5
if self.miles < 0:
self.miles = 0
return self
bike1 = Bike(200, "25 MPH")
bike2 = Bike(250, "26 MPH")
bike3 = Bike(200, "25 MPH")
#example of method chaining; ride three times, reverse twice, and display
bike2.ride().ride().ride().reverse().reverse().displayInfo()
"""
Create a new class called Bike with the following properties/attributes:
price
max_speed
miles
Create 3 instances of the Bike class.
Use the __init__() function to specify the price and max_speed of each instance (e.g. bike1 = Bike(200, "25mph"); In the __init__() also write the code so that the initial miles is set to be 0 whenever a new instance is created.
Add the following functions to this class:
displayInfo() - have this method display the bike's price, maximum speed, and the total miles.
ride() - have it display "Riding" on the screen and increase the total miles ridden by 10
reverse() - have it display "Reversing" on the screen and decrease the total miles ridden by 5...
Have the first instance ride three times, reverse once and have it displayInfo(). Have the second instance ride twice, reverse twice and have it displayInfo(). Have the third instance reverse three times and displayInfo().
What would you do to prevent the instance from having negative miles?
Which methods can return self in order to allow chaining methods?
""" | true |
7654c068f8136a957fd0f17a00f00c130c0af639 | dwzukowski/PythonDojo | /typeList.py | 1,091 | 4.34375 | 4 | #we declare a function called typeList that takes one paramater, list
def typeList(list):
newStr = ""
sum = 0
#instantiate a for loop
for i in range(0,len(list)):
if isinstance(list[i], int):
sum+=list[i]
elif isinstance(list[i], float):
sum+=list[i]
elif isinstance(list[i], str):
newStr+= (list[i])+" "
print sum
print newStr
x= ['magical unicorns',19,'hello',98.98,'world']
typeList(x)
"""
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.
Here are a couple of test cases. Think of some of your own, too. What kind of unexpected input could you get?
""" | true |
9b9c1fc50ec7de95e4a841f0ae7127678f242e35 | EduardoZortea18/PythonExercises | /ex008.py | 305 | 4.125 | 4 | distance = int(input('Type some distance in meters: '))
print('The distance of {} meters is equal to: \n'
'{}km \n'
'{}hm \n'
'{}dam \n'
'{}dm \n'
'{}cm \n'
'{}mm \n'.format(distance, distance/1000, distance/100, distance/10, distance*10, distance*100, distance*1000)) | false |
8e662865c92c45a66ab05eb834ac525f87863c30 | 19h61a0507/python-programming-lab | /strpalindrome1.py | 205 | 4.375 | 4 | def palindrome(string):
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")
string=input("enter the string")
palindrome(string)
| true |
bdb456492eb7c89a11f0528f2fa631e76f353031 | peiyong-addwater/2018SM2 | /2018SM2Y1/COMP90038/quizFiveSort.py | 2,748 | 4.28125 | 4 | def insertionSort(arr):
assignment = 0
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
assignment = assignment +1
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
assignment = assignment+1
j -= 1
arr[j+1] = key
assignment = assignment +1
print(arr, assignment)
def shellSort(arr):
# Start with a big gap, then reduce the gap
n = len(arr)
gap = n/2
# Do a gapped insertion sort for this gap size.
# The first gap elements a[0..gap-1] are already in gapped
# order keep adding one more element until the entire array
# is gap sorted
while gap > 0:
for i in range(gap,n):
# add a[i] to the elements that have been gap sorted
# save a[i] in temp and make a hole at position i
temp = arr[i]
# shift earlier gap-sorted elements up until the correct
# location for a[i] is found
j = i
while j >= gap and arr[j-gap] >temp:
arr[j] = arr[j-gap]
j -= gap
# put temp (the original a[i]) in its correct location
arr[j] = temp
gap /= 2
array = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
insertionSort(array)
import math
print(math.log2(3355431+1))
# Python program to implement interpolation search
# If x is present in arr[0..n-1], then returns
# index of it, else returns -1
'''def interpolationSearch(arr, n, x):
# Find indexs of two corners
lo = 0
hi = (n - 1)
# Since array is sorted, an element present
# in array must be in range defined by corner
while lo <= hi and x >= arr[lo] and x <= arr[hi]:
# Probing the position with keeping
# uniform distribution in mind.
pos = lo + int(((float(hi - lo) /
( arr[hi] - arr[lo])) * ( x - arr[lo])))
# Condition of target found
if arr[pos] == x:
return pos
# If x is larger, x is in upper part
if arr[pos] < x:
lo = pos + 1;
# If x is smaller, x is in lower part
else:
hi = pos - 1;
return -1
# Driver Code
# Array of items oin which search will be conducted
arr = [10, 10, 10, 10, 11, 10, 10, 10, \
22, 23, 24, 33, 35, 42, 10]
n = len(arr)
x = 18 # Element to be searched
index = interpolationSearch(arr, n, x)
if index != -1:
print "Element found at index",index
else:
print "Element not found"
# This code is contributed by Harshit Agrawal'''
| true |
2113e0f5ecdfabd6c6758fd5989e5b69a7529d3d | moritz2104/LPTHW | /ex07.py | 717 | 4.125 | 4 | print "Mary had a little lamb." # output a string
print "Its fleece was white as %s." % 'snow' # outputs a string with a format string --> wie geht das in python 3 ???
print "And everywhere Mary went."
print "." * 10 # what'd that do?
print "_" * 80 # what'd that do? Na ist doch klar!
end1 = "C"
end2 = "H"
end3 = "E"
end4 = "E"
end5 = "S"
end6 = "E"
end7 = "B"
end8 = "U"
end9 = "R"
end10 = "G"
end11 = "E"
end12 = "R"
var = "! Yeah Yeah Yeah!"
print end1 + end2 + end3 + end3 + end5 + end6, # hier wird ein Zeilenumbruch durch das Komma verhindert.
print end7 + end8 + end9 + end10 +end11 + end12
print end1 + end2 + end3 + end3 + end5 + end6 + end7 + end8 + end9 + end10 +end11 + end12 + var # bad style, aha | false |
9b1f7b2a6b5cf52bd6406563714300f1e32d1f3d | crazywiden/Leetcode_daily_submit | /Widen/LC543_Diameter_of Binary_Tree.py | 1,564 | 4.25 | 4 | """
543. Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
"""
# actually took me a while
# Runtime: 44 ms, faster than 67.62% of Python3 online submissions for Diameter of Binary Tree.
# Memory Usage: 14.5 MB, less than 100.00% of Python3 online submissions for Diameter of Binary Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if root == None:
return 0
left_depth, left_span = self.maxDepth(root.left)
right_depth, right_span = self.maxDepth(root.right)
return max(left_depth + right_depth, left_span, right_span)
def maxDepth(self, root):
if root == None:
return 0, 0
left_depth, left_span = self.maxDepth(root.left)
right_depth, right_span = self.maxDepth(root.right)
depth = 1 + max(left_depth, right_depth)
span = max(left_depth + right_depth, left_span, right_span)
return depth, span | true |
83163acd94774048c6ed331b41da1d5bb8a904ca | crazywiden/Leetcode_daily_submit | /Widen/LC376_Wiggle_Subsequence.py | 1,871 | 4.25 | 4 | """
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Example 1:
Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.
Example 2:
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Example 3:
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
"""
# two array dp
# Time complexity -- 0(N)
# Space complexity -- O(1)
# Runtime: 40 ms, faster than 70.83% of Python3 online submissions for Wiggle Subsequence.
# Memory Usage: 13.8 MB, less than 10.00% of Python3 online submissions for Wiggle Subsequence.
# I should learn to use two arraries in dp
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
n = len(nums)
if n <= 1:
return n
inc, dec = 1, 1
for x in range(1, n):
if nums[x] > nums[x - 1]:
inc = dec + 1
elif nums[x] < nums[x - 1]:
dec = inc + 1
return max(inc, dec) | true |
628f8ab619e1460c897cdacfb238dd69b0cb94eb | crazywiden/Leetcode_daily_submit | /Widen/LC394_Decode_String.py | 1,811 | 4.15625 | 4 | """
394. Decode String
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
"""
# stack
# time complexity -- O(N)
# Runtime: 24 ms, faster than 94.38% of Python3 online submissions for Decode String.
# Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Decode String.
class Solution:
def decodeString(self, s: str) -> str:
if len(s) == 0:
return ""
stack = []
idx = 0
while idx < len(s):
if s[idx].isnumeric():
multiplier = []
while s[idx].isnumeric():
multiplier.append(s[idx])
idx += 1
stack.append("".join(multiplier))
elif s[idx].isalpha():
stack.append(s[idx])
idx += 1
elif s[idx] == "[":
idx += 1
elif s[idx] == "]":
new_str = []
while stack[-1].isalpha():
new_str.insert(0, stack.pop())
multiplier = int(stack.pop())
new_str = "".join(new_str)
stack.append(new_str*multiplier)
idx += 1
return "".join(stack) | true |
a953d20e0094da3a509afd7ae9a8cda33aeee6cf | crazywiden/Leetcode_daily_submit | /Widen/LC408_Valid_Word_Abbreviation.py | 2,325 | 4.1875 | 4 | """
408. Valid Word Abbreviation
Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.
A string such as "word" contains only the following valid abbreviations:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word".
Note:
Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.
Example 1:
Given s = "internationalization", abbr = "i12iz4n":
Return true.
Example 2:
Given s = "apple", abbr = "a2e":
Return false.
"""
# easy question is always very annoying...
# Runtime: 28 ms, faster than 98.80% of Python3 online submissions for Valid Word Abbreviation.
# Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Valid Word Abbreviation.
import re
class Solution:
def validWordAbbreviation(self, word: str, abbr: str) -> bool:
abbr_char = re.findall("[a-z]+", abbr)
abbr_digit = re.findall("[0-9]+", abbr)
if abbr[0] >= "0" and abbr[0] <= "9":
if int(abbr_digit[0]) > len(word):
return False
if abbr[0][0] == "0":
return False
return self.compare(word[int(abbr_digit[0]):], abbr_char, abbr_digit[1:])
else:
return self.compare(word, abbr_char, abbr_digit)
def compare(self, word, abbr_char, abbr_digit):
start = 0
if len(abbr_char) == 0 and len(word) != 0:
return False
while start < len(word):
if len(abbr_char) != 0:
tmp_seg = abbr_char.pop(0)
if word[start:start+len(tmp_seg)] != tmp_seg:
return False
start = start + len(tmp_seg)
if len(abbr_digit) != 0:
tmp_abbr = abbr_digit.pop(0)
if tmp_abbr[0] == "0":
return False
start += int(tmp_abbr)
if len(abbr_char) == 0 and len(abbr_digit) == 0:
break
if len(abbr_char) == 0 and len(abbr_digit) == 0 and start == len(word):
return True
else:
return False
| true |
7b98a0b5d9e81cc2d8fc1aca7e1e6e26dd164eae | crazywiden/Leetcode_daily_submit | /Widen/LC71_Simplify_Path.py | 1,287 | 4.28125 | 4 | """
71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
"""
# actually simple
# but need to figure out what does canonical path means
# Runtime: 24 ms, faster than 95.52% of Python3 online submissions for Simplify Path.
# Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Simplify Path.
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
elements = path.split("/")
for ele in elements:
if ele == "..":
if stack:
stack.pop()
elif ele == "." or ele == "":
continue
else:
stack.append(ele)
return "/" + "/".join(stack) | true |
94ddc5ac813e101d378660e725d8cf258418e701 | elle-johnnie/Arduino_Py | /PythonCrashCourse/fizzbuzz.py | 762 | 4.1875 | 4 | # fizzbuzz in Python 2.7
##
# I just heard about this at a local meetup - thought I'd give it a go.
# The rules:
# Write a program that prints the numbers from
# 1 to 100. But for multiples of three print Fizz instead of the number and for the multiples of five print
# Buzz. For numbers which are multiples of both three and five print FizzBuzz
# create empty list
nums = []
# append 1-100 as items in num list
for i in range(1, 101):
nums.append(i)
# print unaltered list
print nums
print ('Begin fizzbuzz test... \n')
for i in nums:
if i % 3 == 0 and i % 5 == 0:
print ('fizzbuzz')
elif i % 3 == 0:
print ('fizz')
elif i % 5 == 0:
print ('buzz')
else:
print i
print ('fizzbuzz testing complete.')
| true |
6a26ef4cc53b955a98306b03c895c19e94264020 | elle-johnnie/Arduino_Py | /edX_CS_exercises/number_guess_bisect.py | 988 | 4.3125 | 4 | # The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive).
# The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection
# search, the computer will guess the user's secret number!
# edX wk 2 Algorithms
# solution attempt 01/31/2018 @LJohnson
low = 0
high = 100
number = False
print('Think of a number between 0 and 100.')
while not number:
mid = (high + low)//2
print('Is your number %d ?' % mid)
userinput = input('''Enter 'h' to indicate the guess is too high.
Enter 'l' to indicate the guess is too low.
Enter 'c' to indicate I guessed correctly.''')
if userinput == 'l':
low = mid
elif userinput == 'h':
high = mid
elif userinput == 'c':
print('Awesome I guessed your number correctly!')
number = True
else:
print('Sorry I did not understand your response.')
| true |
fd22c3cadbc5f3c79b997c118b6a62b0adebd935 | AbnerErnaniADSFatec/Python-Codes | /Abner Ernâni dos Anjos - ADS Turma A - Lista de Exercícios 2/Exercício 4 e 5.py | 889 | 4.15625 | 4 | a= int(input('Digite o 1º número: '))
b= int(input('Digite o 2º número: '))
c= int(input('Digite o 3º número: '))
if a > c and a > b:
print('O maior número é o 1º número, %d.' %a)
if b > a and b > c:
print('O maior número é o 2º número, %d.' %b)
if c > b and c > a:
print('O maior número é o 3º número, %d.' %c)
if a < c and a < b:
print('O menor número é o 1º número, %d.' %a)
if b < a and b < c:
print('O menor número é o 2º número, %d.' %b)
if c < b and c < a:
print('O menor número é o 3º número, %d.' %c)
elif a==b==c:
print('Os números são iguais.')
elif a!=c and a==b:
print('O 1º e 2º número são iguais')
elif b!=a and b==c:
print('O 2º e 3º número são iguais')
elif c!=b and c==a:
print('O 1º e 3º número são iguais')
if a!=b!=c:
print('Os números são diferentes')
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.