blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c90a9194582d1df8df43079f6c1000d4c127e56a | Sohaib-50/-NED-FE-CP-pset-DecisionControlStructures | /Q7.py | 824 | 4.1875 | 4 | #Q7. Write a Python program to check if a character entered by the user is an alphabet or a digit or a special character. If the user enters more than one character as input, the program prints some appropriate error message and exit.
#solution1:
ch = input("Enter a single character: ")
if len(ch) == 1:
if "A" <= ch <= "Z" or "a" <= ch <= "z":
print("alphabet.")
elif "0" <= ch <= "9":
print("digit.")
else:
print("special character.")
else:
print("you were supposed to enter one character only!")
#solution2:
ch = input("Enter a single character: ")
if len(ch) == 1:
if ch.isalpha():
print("alphabet.")
elif ch.isdigit():
print("digit.")
else: #must be a special character if not a digit and not an alphabet.
print("special character.")
else:
print("you were supposed to enter one character only!")
| true |
fa5601fcb54e83d8f898149e026e493fd0d40021 | luwinher/Python_Practice | /gPython/fourteen.py | 1,039 | 4.15625 | 4 | #
"""Q14:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 """
import math
number = input("请输入一个数:")
num = int(number)
def prime(num):
flag = 0
primelist = list()
for n in range(2,num+1):
for s in range(2,n):
# print("%d,%d"%(n,s))
if n%s==0:
flag=1
break
#print(flag)
if flag==0:
primelist.append(n)
else:
flag=0
return primelist
primes = prime(num)
#print(primes)
nflag = 1
numlist = list()
while(num!=1 and primes):
for i in primes:
if num%i==0:
numlist.append(i)
num = num/i
nflag = 0
#print(numlist)
if numlist[-1]==int(number):
print("%d=%d*%d"%(int(number),1,int(number)))
else:
numlist.sort()
numlist.reverse()
print("%d="%int(number),end='')
nx = numlist.pop()
print(nx,end='')
while(numlist):
print("*",end='')
nx = numlist.pop()
print(nx,end='')
print()
| false |
b75f7809adeab9ab4823030149f66beb482ded74 | shivam9028/hello-world | /shiva.py | 242 | 4.375 | 4 | def factorial(num):
"""This function calls itself to find
the factorial of a number"""
if num == 1:
return 1
else:
return (num * factorial(num - 1))
num = 5
print("Factorial of", num, "is: ", factorial(num)) | true |
85d775c1ee93ff51b5f10e54c8131aa6c8b5dae3 | angelbill5914/mobiLehigh2016 | /Tutorial/ex32.py | 725 | 4.375 | 4 |
#Sets up various lists
the_counts = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#Loop runs with number as a variable that changes values as it goes through the list
for number in the_counts:
print "This is count %d" %number #Prints out each each of the elements in the string
for fruit in fruits:
print "A fruit of type: %s" % fruit
for i in change:
print "I got %r" % i
#Sets up an empty list
elements = []
for i in range(0,6): #Contains numbers 0, 1, 2, 3, 4, 5!!
print "Adding %d to the list." % i
elements.append(i) #Adds the numbers into the list "element"
for stuff in elements:
print "Element was: %d" % stuff
| true |
54370a1fce2a70024b32303d9359167326c298a4 | LucasFernandes16/AulasLPC | /LPC-2.py | 1,120 | 4.125 | 4 | # a=2
# b=-1
# print(a>=b)
#print('ola mundo',2,2.5, True, False)
#numero=3
#print(f'O NUMERO {numero} é par')
#nome = (input('digite seu nome: '))
#= int(input('digite sua idade'))
#print(f'sua idade é de{idade} e seu nome {nome}')
#
#print(f'seu peso é de {peso} Kg')
#num = int(input('Digite um número: '))
#if num % 2 == 0:
# print(f'O número {num} é par')
#else:
# print(f'O número {num} é ímpar')
#num = float(input('Digite um número: '))
#if num > 0:
# print('Este número é positivo')
#elif num == 0:
# print('Este número é neutro')
#else:
# print('Este número é negativo')
#resposta = int(input('digite sua idade'))
#if resposta>=18 and resposta <=65:
# print('voce é obrigado a votar')
#else:
# print('nao precisa votar')
#print('1. Idoso')
#print('2. Gestante')
#print('3. Cadeirante')
#print('4. Nenhum destes')
#resposta=int( input('Você é: ') )
#if (resposta==1) or (resposta==2) or (resposta==3) :
# print('Você tem direito a fila prioritária')
#else:
# print('Você não tem direito a nada. Vá pra fila e fique quieto')
#a = 4
#b = 2
#print(not a > b) | false |
7e948a3a0907a1183c7d597a3d9bb2201362484d | austincreates/python_programming_3640 | /in-class_code/exercise 1 in class sept 19.py | 566 | 4.1875 | 4 | def usbmi(height, weight):
bmi = 703 * weight/(height ** 2)
if bmi >= 30:
print ("Your bmi is {:.1f}. You are obese.".format(bmi))
elif 30 > bmi >= 25:
print ("Your bmi is {:.1f}. You are overweight".format(bmi))
elif 25 > bmi > 18.5:
print ("Your bmi is {:.1f}. You are normal weight".format(bmi))
else:
print ("Your bmi is {:.1f}. You are underweight".format(bmi))
h = int(input("Please insert your height here: "))
w = int(input("Please insert your weight here: "))
h = float(h)
w = float(w)
usbmi(h, w)
| false |
cf44cd5785b730d60b50f4fcc1f560d9a2aa9554 | safkat33/LeetCodeProblems | /String/ZigZagConversion.py | 1,174 | 4.40625 | 4 | '''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
'''
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = ["" for i in range(numRows)]
idx = 0
downwards = True
for i in range(len(s)):
rows[idx] += s[i]
if downwards:
if idx+1 < numRows:
idx += 1
else:
downwards = False
idx -= 1
else:
if idx > 0:
idx -= 1
else:
downwards = True
idx += 1
res = ""
for i in range(numRows):
res += rows[i]
return res
| true |
0a44b4c80c5c40355200daf78d85e6f6d710c58b | safkat33/LeetCodeProblems | /ArrayProblems/MaximumProductThreeNumbers.py | 776 | 4.34375 | 4 | """
Maximum Product of Three Numbers
Share
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [1,2,3,4]
Output: 24
"""
from typing import List
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
res = None
for i in range(len(nums) - 2):
for j in range(i + 1, len(nums) - 1):
for k in range(j + 1, len(nums)):
if res == None:
res = nums[i] * nums[j] * nums[k]
else:
temp = nums[i] * nums[j] * nums[k]
if temp > res:
res = temp
return res
| true |
6922369ea0f3c7b6a34080ebd3f27b4fae295601 | jrmcfadd/Google-Training | /canvas.py | 884 | 4.21875 | 4 | def fib(x):
'''Fibonnaci Numbers : takes a number (x) and returns the resulting Fibonnaci number'''
if x >= 2:
answer = fib(x-1) + fib(x-2)
else:
return 1
return answer
def fact(n):
# assuming that n is a positive integer or 0
if n >= 1:
return n * fact(n - 1)
else:
return 1
sep = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
print(sep)
print("Factorials")
print(sep)
print("0! =", fact(0))
print("1! =", fact(1))
print("2! =", fact(2))
print("3! =", fact(3))
print("6! =", fact(6))
print(sep)
print(sep)
print("Fibonnaci")
print(sep)
print("Fibonnaci of -> 0 is -> " + str(fact(0)))
print("Fibonnaci of -> 1 is -> " + str(fact(1)))
print("Fibonnaci of -> 2 is -> " + str(fact(2)))
print("Fibonnaci of -> 3 is -> " + str(fact(3)))
print("Fibonnaci of -> 6 is -> " + str(fact(6)))
print(sep) | false |
dcb40076231779acf43e35188cc5cffe8a0b538f | alfonso-torres/eng84_OOP_python | /animal.py | 1,201 | 4.28125 | 4 | # Let's create are first class
# Syntax class is the key word then name of the class
# Creating an Animal class
class Animal():
# name = "Dog" # class variable
def __init__(self): # self refers the current class
self.alive = True
self.spine = True
self.lungs = True
def move(self):
return "moving left right and centre "
def eat(self):
return " keep eating to stay alive "
def breath(self):
return " keep breathing if you want to live"
# Creating an object of our Animal class
# cat = Animal() # this will store all the data available in Animal class into cat
# oriental_long_hair = Animal()
# print(oriental_long_hair.breath())
# print(cat.eat()) # eat() is Abstraction
# ABSTRACTION -> THE USER DOESN'T NEED TO KNOW WHAT IS HAPPENING BEHIND BUT HE JUST KNOW THAT WITH CAT HE HAS DIFFERENTS OPTIONS WITH cat.
# oriental_long_hair.lungs = False # Polymorphism because he changed the value and it's using his value, not from parent.
# Polymorphism here we utilised to override the value of lungs particularly for oriental_long_hair
# print(oriental_long_hair.lungs)
# pass # pass is a key word used to by pass the code
| true |
368b087dbf49c5fbfba90893383e1f1ff40f2314 | KobeB87/Examples | /string.py | 513 | 4.28125 | 4 | #coding:utf-8
str = "Hello world world !"
print(str)
print(str.replace("world", "planet earth"))
str = "elem1|elem2|elem3"
print(str.split("|"))
str = "12345678"
print("Chaine : {}".format(str))
print("12 is present : {}".format("12" in str))
print("isalpha : {}".format(str.isalpha()))
print("isalnum : {}".format(str.isalnum()))
print("isdigit : {}".format(str.isdigit()))
print("isdecimal : {}".format(str.isdecimal()))
print("islower : {}".format(str.islower()))
print("isupper : {}".format(str.isupper())) | false |
dc598b01dfd3ccab2be3caf42a7471a56bd3e8cd | kimurakousuke/MeiKaiPython | /chap13/list1304c.py | 230 | 4.15625 | 4 | # 打印输出从文件读取的所有行字符串(遍历的对象是文件对象)
f = open('hello.txt') # 打开(文本+读取模式)
for line in f:
print(line, end='')
f.close() # 关闭
| false |
48d9b1c8c4598109770102f8e70f7b825723c3f6 | kimurakousuke/MeiKaiPython | /chap02/list0212.py | 438 | 4.125 | 4 | # 读取两个整数并进行加减乘除(其二:读取和转换合并,以单一语句实现)
a = int(input('整数a:'))
b = int(input('整数b:'))
print('a + b 等于', a + b, '。')
print('a - b 等于', a - b, '。')
print('a * b 等于', a * b, '。')
print('a / b 等于', a / b, '。')
print('a // b 等于', a // b, '。')
print('a % b 等于', a % b, '。')
print('a ** b 等于', a ** b, '。')
| false |
248b12a0873fbff164b7fd422ce6cd0be222db21 | kloyd/coursera.python | /pay.py | 765 | 4.21875 | 4 | # Write a program to prompt the user for hours and rate per hour using
# input to compute gross pay.
# Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate
# for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour
# to test the program (the pay should be 498.75).
# You should use input to read a string and float() to convert the string to a number.
# Do not worry about error checking the user input - assume the user types numbers properly.
inputhours = input("Enter Hours:")
hours = float(inputhours)
inputrate = input("Rate:")
rate = float(inputrate)
if (hours > 40):
regHours = 40
overHours = hours - 40
else:
regHours = hours
overHours = 0
pay = regHours * rate + overHours * rate * 1.5
print(pay) | true |
6054f7326ee48b805a51e423e87238aba4b40a8c | bpmnnit/project_euler | /problem_26.py | 1,295 | 4.25 | 4 | #!/usr/bin/env python3
from operator import itemgetter
# Python3 program to find repeating
# sequence in a fraction
# This function returns repeating sequence
# of a fraction.If repeating sequence doesn't
# exits, then returns empty string
def fractionToDecimal(numr, denr):
# Initialize result
res = ""
# Create a map to store already seen
# remainders. Remainder is used as key
# and its position in result is stored
# as value. Note that we need position
# for cases like 1/6. In this case,
# the recurring sequence doesn't start
# from first remainder.
mp = {}
# Find first remainder
rem = numr % denr
# Keep finding remainder until either
# remainder becomes 0 or repeats
while ((rem != 0) and (rem not in mp)):
# Store this remainder
mp[rem] = len(res)
# Multiply remainder with 10
rem = rem * 10
# Append rem / denr to result
res_part = rem // denr
res += str(res_part)
# Update remainder
rem = rem % denr
if (rem == 0):
return ""
else:
return res[mp[rem]:]
rep_len = []
for i in range(1, 1001):
res = fractionToDecimal(1, i)
rep_len += [(i, len(res), res)]
print(max(rep_len, key=itemgetter(1)))
# if (res == ""):
# print(i, "No recurring sequence")
# else:
# print(i, res) | true |
ff945c57e761cb35d25f12d0a26dbd5a8d05f12f | aritrochakraborty29/Hacktoberfest2020 | /Data Structures/Python/Queue/dqueue.py | 1,014 | 4.25 | 4 | # Python Program to demonstrate the FIFO principle using doeque
from collections import deque
print("Queues utilize the FIFO (First In First Out) Principle")
print()
q = deque() # Initializating Empty Queue
print("Initial empty queue :", q) # Printing empty queue
# Adding items to the queue
q.append("Hey")
q.append("there!")
q.append("This")
q.append("is")
q.append("a")
q.append("Queue!")
print("After adding items into the queue:", q) # Printing queue with all elements
q.popleft() # Removing an element from the queue
print("After removing an item from the queue:", q)# Printing queue after removing an element
q.append("What?!") # Adding another element to the queue
print("After adding an extra item to the queue:", q) # Printing the new queue
# Removing all the elements from the queue
q.popleft()
q.popleft()
q.popleft()
q.popleft()
q.popleft()
q.popleft()
print("After removing all the items:", q) # Printing the empty queue
print("Trying to remove any more items will result in an error!")
| true |
a9ec6bd30804f2789c939f64dd40120f52af3dfa | navarroj00/Vigenere-Cipher | /vignere.py | 2,325 | 4.1875 | 4 | '''
This program encodes a message using the Vignere Cipher and decrypts it afterwards.
CS 111, Fall 2018
Date: October 2nd, 2018
Names: Zack Johnson and Jordan Navarro
'''
def main():
# Header.
print("* * * VIGNERE CIPHER * * *")
# Ask the user for a message to encode and a password.
msg = input("Enter a message to encrypt: ")
password = input("Enter a password to encrypt this message: ")
# Convert message and password to lowercase and remove spaces.
msg = msg.lower()
msg = msg.replace(" ", "")
password = password.lower()
password = password.replace(" ", "")
# Store the alphabet.
codeAlphabet = "abcdefghijklmnopqrstuvwxyz"
# Implement the encrypt algorithm as described in the PDF.
cipherText = ""
for i in range(len(msg)):
# Find the position in the alphabet of the ith letter of the message.
m = msg[i]
msgIndex = codeAlphabet.find(m)
# Find the position in the alphabet of the ith letter of the password.
# If the password is shorter than the message, then the % (modulo) loops back to the beginning of the password.
p = password[i % len(password)]
keyLetterIndex = codeAlphabet.find(p)
# Find the new letter in the alphabet and append it to the code.
cipherLetter = codeAlphabet[(msgIndex + keyLetterIndex) % 26]
cipherText = cipherText + cipherLetter
# Print out the encrypted message.
print("\nYour encrypted message is:", cipherText)
# Implement the decrypt algorithm as described in the PDF.
test = ""
for i in range(len(cipherText)):
# Find the position in the alphabet of the ith letter of the message.
c = cipherText[i]
cipherIndex = codeAlphabet.find(c)
# Find the position in the alphabet of the ith letter of the password.
p = password[i % len(password)]
keyLetterIndex = codeAlphabet.find(p)
# Find the new letter in alphabet and subtract it from the code.
testLetter = codeAlphabet[(cipherIndex - keyLetterIndex) % 26]
test = test + testLetter
# Print out the decrypted message.
print("\nCheck -- your decrypted message is:", test)
# Footer.
print("* * * END VIGNERE CIPHER * * *")
main()
| true |
17a59d1e41ef0b6382b76ce2078b74f22978804a | MrAch26/Developers_Institute | /WEEK 5/Day 1/OOP-lesson-day1/code.py | 925 | 4.25 | 4 | # We have complex variables such as: List, Dict.
# We can create our own complex variables by defining new classes.
class Student():
def __init__(self, name, age, courses={}):
self.name = name
self.age = age
self.courses = courses
def sayHi(self):
print(f"Hello my name is {self.name} and I am {self.age} years old")
def haveBirthday(self):
print("Happy Birthday")
self.age += 1
def register(self, course_name, previous_grade=None):
self.courses[course_name] = previous_grade
print(f"You just registered for {course_name}")
class Text():
def __init__(self, value):
self.value = value
def upper(self):
uppertext = ""
for letter in self.value:
uppertext += chr(ord(letter) - 32)
return uppertext
def lower(self):
lowertext = ""
for letter in self.value:
lowertext += chr(ord(letter) + 32)
return lowertext
def capitalize(self):
return self.upper()[0] + self.value[1:] | true |
ae5fa3bbdede400a5f5946ce8bbc092d5ee4dcee | sonutiwari/Algorithms | /sorting/SelectionSort.py | 2,350 | 4.25 | 4 | import random, time
"""A class to implement insertion sort."""
class SelectionSort(object):
"""A class to implement insrtion sort.
To use:
>>> is = SelectionSort()
>>> is.selection_sort([2, 3, 1, 9, 8, 5, 4, 6, 7])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> is.insertion_sort_descending([2, 3, 1, 9, 8, 5, 4, 6, 7])
[9, 8, 7, 6, 5, 4, 3, 2, 1]
"""
def selection_sort(self, list_of_nums) -> list:
""" The method for selection sort.
Args:
list_of_nums: list of random integers.
Returns:
list_of_nums: list of integers in sorted(Ascending) order.
"""
n = len(list_of_nums)
for j in range(0, n - 1):
smallest = j
i = j + 1
while i < n:
if list_of_nums[i] < list_of_nums[smallest]:
smallest = i
i += 1
list_of_nums[smallest], list_of_nums[j] = list_of_nums[j], list_of_nums[smallest]
return list_of_nums
def selection_sort_descending(self, list_of_nums) -> list:
""" The method for normal insertion sort.
Args:
list_of_nums: list of random integers.
Returns:
list_of_nums: list of integers in sorted(Descending) order.
"""
n = len(list_of_nums)
for j in range(0, n - 1):
largest = j
i = j + 1
while i < n:
if list_of_nums[i] > list_of_nums[largest]:
largest = i
i += 1
list_of_nums[j], list_of_nums[largest] = list_of_nums[largest], list_of_nums[j]
return list_of_nums
# Testing the code.
insSort = SelectionSort()
print(insSort.selection_sort([2, 3, 1, 9, 8, 5, 4, 6, 7]))
print(insSort.selection_sort_descending([2, 3, 1, 9, 8, 5, 4, 6, 7]))
# Testing the runtime in realtime.
integers = [0] * 10000 # placeholder for 10k integers.
# Generating 10k integers randomly.
for i in range(10000):
integers[i] = random.randint(100, 10000000) + 1
# Showing runtime of insertion sort for 10k elements.
# ideally it should take around 10 seconds in a normal
# laptop but it may vary depending on configuration of
# System used to run the method.
start_time = time.time()
insSort.selection_sort(integers)
print("--- %s seconds ---" % (time.time() - start_time)) | true |
e95b082f3c1639b30f16132b15fc76a14f64e5b7 | JacobCollstrup/PythonBootCamp | /DiceRoller/main.py | 566 | 4.125 | 4 | # Main Program
from Dice import DiceRoll
Condition = "y"
while Condition == "y":
type = int(input("What type of dice do you want to roll? (Input whole number larger than 0.): "))
number = int(input("How many times do you want to roll it? (Input whole number larger than 0.):"))
dice_rolls = DiceRoll(type, number)
print("Your rolls are...")
print("Roll : Count")
for roll, count in dice_rolls.items():
print(roll, " : ", count)
Condition = input("Press 'y' to continue and roll again, press any key to stop.") | true |
c981b9f867880676873125d880a680892e4ba461 | davidobrien1/programming-and-scripting | /collatz.py | 249 | 4.15625 | 4 | # David O'Brien, 2018-02-09
# Collatz: https://en.wikipedia.org/wiki/Collatz_conjecture
n = int(input("Please enter an integer: "))
while n > 1:
if(n % 2 == 0):
n = n/2
print(n)
elif(n % 2 == 1):
n = n * 3 + 1
print(n)
| false |
c4435436f81b6a7bb7fb544f3998240b77aed64d | cona-dev/python-prac | /quiz/quiz9.py | 1,543 | 4.21875 | 4 | """
Quiz 9)
동네에 항상 대기 손님이 있는 맛있는 치킨집이 있습니다.
대기 손님의 치킨 요리 시간을 줄이고자 자동 주문 시스템을 제작하였습니다.
시스템 코드를 확인하고 적절한 예외처리 구문을 넣으시오.
조건1: 1보다 작거나 숫자가 아닌 입력값이 들어올 때는 ValueError로 처리
출력 메세지 : " 잘못된 값을 입력하였습니다."
조건2: 대기 손님이 주문할 수 있는 총 치킨량은 10마리로 한정
치킨 소진 시 사용자 정의 에러 [SoldOutError]를 발생시키고 프로그램 종룔
출력 메세지 : " 재고가 소진되어 더 이상 주문을 받지 않습니다. "
"""
class SoldOutError(Exception):
pass
chicken = 10
waiting = 1
while(True):
try:
print("남은 치킨 : {}".format(chicken))
order = int(input("치킨 몇마리 주문하시겠습니까?"))
if order > chicken:
print("재료가 부족합니다.")
raise SoldOutError
elif order <= 0:
raise ValueError
else:
print("대기번호 {} : {} 마리 주문이 완료되었습니다.".format(waiting, order))
waiting += 1
chicken -= order
if chicken == 0:
raise SoldOutError
except ValueError:
print("*** 잘못된 값을 입력하였습니다.")
except SoldOutError:
print("*** 재고가 소진되어 더 이상 주문을 받지 않습니다.")
break
| false |
458efcb85f9a109d2eb5208b6d9ce2fbaffd9929 | cona-dev/python-prac | /quiz/quiz6.py | 1,010 | 4.40625 | 4 | """
Quiz6) 표준 체중을 구하는 프로그램을 작성하시오
* 표준 체중 : 각 개인의 키에 적당한 체중
(성별에 따른 공식)
남자 : 키(m) * 키(m) * 22
여자 : 키(m) * 키(m) * 21
조건1: 표준 체중은 별도의 함수 내에서 계산
* 함수명 : std_weight
* 전달값 : 키(height), 성별(gender)
조건2: 표준 체중은 소수점 둘째자리까지 표시
-- 출력 예시
키 175cm 남자의 표준 체중은 67.38kg 입니다.
"""
def std_weight(gender, height):
height = height / 100
if gender == "f":
return height * height * 21
else:
return height * height * 22
gender = input("당신의 성별은? (f 또는 m) : ")
height = int(input("당신의 키는? : "))
weight = round(std_weight(gender, height), 2)
if(gender == "f"):
print("키 {0}cm 여자의 표준 체중은 {1}kg 입니다.".format(height, weight))
else:
print("키 {0}cm 남자의 표준 체중은 {1}kg 입니다.".format(height, weight))
| false |
c6b8aaafc1751f1685f4ecdfb6fc35b557077b19 | Cogswatch/LeapYear | /testleapyear.py | 409 | 4.15625 | 4 | # import leapyear
def leapYear(year):
if (year % 400 == 0) or ((year % 4 == 0) and not (year % 100 == 0)):
print("Output - " + str(year) + " is a leap year")
return True
else:
print("Output - " + str(year) + " is not a leap year")
return False
def test_leapyear():
assert leapYear(1992) == True
assert leapYear(2000) == True
assert leapYear(1900) == False | false |
2c030e95eab326fd05fcf95b7cc020cfe7a821b5 | jh25737/LPTHW | /ex20.py | 830 | 4.15625 | 4 | from sys import argv
script, input_file = argv
#defines print_all which reads and prints all the lines
def print_all(f):
print f.read()
#defines rewind funciton, which sets the current line to 0
def rewind(f):
f.seek(0)
#defines the print line function, which prints the linenumber and current line
def print_a_line(line_count, f):
print line_count, f.readline()
#sets and opens the input file selected in argv
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
#pritns one line at a time
current_line = 1
print_a_line(current_line,current_file)
current_line +=1
print_a_line(current_line, current_file)
current_line +=1
print_a_line(current_line, current_file) | true |
9a5ba72b3e0481a3448023b24169c27bb4522c4c | kren1504/Training_codewars_hackerrank | /breakCamelCase.py | 400 | 4.375 | 4 | """
Complete the solution so that the function will break up camel casing, using a space between words.
Example
solution("camelCasing") == "camel Casing"
"""
def breakCamelCase(s):
res = ""
for letra in s:
if letra.isupper():
res += " "+letra
else:
res+=letra
return res
if __name__ == "__main__":
print(breakCamelCase("camelCasing")) | true |
c3b9006aa91dd127f4c12c4db60e76c834350eb3 | PraptiPatel/PraptiPatel_InternTasks | /Task-3/Task_3_programs/Program2.py | 286 | 4.4375 | 4 | # Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder=0.
# If the remainder is 1, then it is an odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num," is Even")
else:
print(num," is Odd")
| true |
ce4924d07e759fd227845504ad05b0a0dd416b7e | HaidiChen/Coding | /python/linkedlist/merge_two_lists.py | 698 | 4.1875 | 4 | # merge two sorted singly linked lists
# just like merging two sorted arrays, but in this case
# we use iterator to traverse these two linked lists and
# choose the node with smaller data first.
# the time complexity is O(m + n)
# space complexity is O(1)
from listnode import ListNode
class Solution:
def merge_two_lists(self, L1, L2):
new_head = tail = ListNode()
L1, L2 = L1.next, L2.next
while L1 and L2:
if L1.data < L2.data:
tail.next = L1
L1 = L1.next
else:
tail.next = L2
L2 = L2.next
tail = tail.next
tail.next = L1 or L2
return new_head
| true |
de67d107892ed54e35f748adeae2a419eb3f29dd | HaidiChen/Coding | /python/binarytree/is_symmetric.py | 890 | 4.375 | 4 | # check if a given binary tree is symmetric.
# the solution is:
# suppose we are looking at node N, we check if N.left and N.right are
# symmetric, if so, check
# 1) N.left.right and N.right.left
# 2) N.left.left and N.right.right
# time complexity is O(n)
# space complexity is O(h)
class Solution(object):
def is_symmetric(self, tree):
return not tree or self._check_symmetric(tree.left, tree.right)
def _check_symmetric(self, left_child, right_child):
if not left_child and not right_child:
return True
if left_child and right_child:
return (left_child.data == right_child.data
and
self._check_symmetric(left_child.left, right_child.right)
and
self._check_symmetric(left_child.right, right_child.left)
)
return False
| false |
6016ca069a7780b10f36701952dcaebece130e2f | HaidiChen/Coding | /python/others/sort_3_unique.py | 1,674 | 4.25 | 4 | # given an array which has only 3 unique numbers (1,2,3)
# sort the array in O(n) time
# the solution is:
# 1) we can count the number of 1, 2, and 3 and rebuild
# a new array from 1 to 3 using the numbers we get.
# 2) we can do this in place by swapping 1 to the leftmost
# place and swapping 3 to the rightmost place. pay attention
# to swapping the 3 here. if you are swappring two 3s. e.g.,
# if array is [3,1,2,3], then you are going to swap the index
# 0 and index 3 as the first element is 3. But after the swap,
# we can see that the first element is still 3, so we need to
# keep the index at 0 to swap it again.
# the space complexity is O(1)
class Solution:
def sort_with_new_list(self, array):
count1, count2, count3 = 0, 0, 0
for n in array:
if n == 1:
count1 += 1
elif n == 2:
count2 += 1
elif n == 3:
count3 += 1
return [1] * count1 + [2] * count2 + [3] * count3
def sort_in_place(self, array):
index_one = 0
index_three = len(array) - 1
# index of the element we are looking at
i = 0
while i <= index_three:
if array[i] == 1:
array[i], array[index_one] = (array[index_one],
array[i])
index_one += 1
i += 1
elif array[i] == 3:
array[i], array[index_three] = (array[index_three],
array[i])
# only change the rightmost index
# leave the index i stay still
index_three -= 1
else:
i += 1
| true |
4f23aa1d97861ba1a15a9a6e8a1483f4908b90b9 | HaidiChen/Coding | /python/heap/sort_almost_sorted_array.py | 1,362 | 4.125 | 4 | import itertools
import heapq
# sort the almost sorted array
# this kind of array ensures that every element
# is at most k away from its final sorted place
# this solution has the following idea
# when we are looking at (k + 1)th element, we
# know that the smallest element in ths (k + 1)
# elements subarray should be put at the begining
# of this subarray, why? Because the smallest one
# is k away from its final sorted place, so the
# furthest place where the smallest element is put
# is going to be the (k + 1)th place.
# so we store the k + 1 elements at a time and
# extract the minimum element followed by adding
# another element to keep the number of elements
# as k + 1. To efficiently extract the min element,
# we use min-heap
# time complexity is O(nlogk)
# space complexity is O(k)
def sort_almost_sorted_array(array, k):
result = []
min_heap = []
# put the first k elements into the min_heap
for x in array[:k]:
heapq.heappush(min_heap, x)
# add the new element to min_heap and extract
# the smallest one
for x in array[k:]:
smallest = heapq.heappushpop(min_heap, x)
result.append(smallest)
# if we have elements left in heap, extract
# the smallest one by one
while min_heap:
smallest = heapq.heappop(min_heap)
result.append(smallest)
return result
| true |
e10921477d72f6689033882f618c0043236504ce | HaidiChen/Coding | /python/sortsearch/merge_two_sorted_arrays.py | 824 | 4.25 | 4 | # given two sorted arrays A and B, merge them
# into A, assume that A has enough empty space
# at the end to hold all elements of B
# if we start from the begining of the two arrays,
# we need to face the shifting operation which is
# expensive.
# so, instead of starting from the begining, we
# can iterate from the end of two arrays and put
# the largest one at the correct place.
# time complexity is O(m + n) where m and n are
# true lengths of A and B
def merge_two_sorted_arrays(A, m, B, n):
i, j = m - 1, n - 1
last_idx = m + n - 1
while i >= 0 and j >= 0:
if A[i] > B[j]:
A[last_idx] = A[i]
i -= 1
else:
A[last_idx] = B[j]
j -= 1
last_idx -= 1
while j >= 0:
A[last_idx] = B[j]
j -= 1
last_idx -= 1
| true |
b2e05bf1a79f039a283dd51c302670fc027b465e | glitton/python_project | /reef_recommender_draft.py | 2,301 | 4.125 | 4 | # This program recommends a reef depending on various criteria such as ability, location, and photography
# create csv file of reefs, convert list to dictionary and read the file
import csv
input_reef = csv.DictReader(open("reef_master.csv"))
#Ask how many dives had in the last year, determines ability
def dive_ability(ability):
if ability <= 30:
diver_skill = "Beginner"
elif 30 < ability <= 100:
diver_skill = "Intermediate"
elif ability > 100:
diver_skill = "Advanced"
return diver_skill
def location(location_input):
if location == "m":
location = "Monterey Bay"
elif location == "c":
location = "Carmel"
# 1 menu, compare ability with csv Skill level and then print out appropriate reefs
def reef_skill_level(reef_ability):
recommend_reef = []
for reef in input_reef:
if reef["Skill Level"] == reef_ability:
recommend_reef.append(reef)
return recommend_reef
#2 menu, function that shows reef based on location. Choices are Monterey or Carmel
def reef_location(location):
recommend_reef = []
for reef in input_reef:
if reef["Location"] == location_list:
recommend_reef.append(reef)
return recommend_reef
# for reef in input_reef:
# for key, value in reef.items():
# if location == value:
# recommend_reef.append(reef)
# return recommend_reef
# print out reef recommendations
def display_reef(recommend_reef_list):
for reef in recommend_reef_list:
print "Reef Name:", reef["Name"], "Location:", reef["Location"], "Depth:", reef["Depth"], "Access:", reef["Access"], "Visibility:", reef["Viz"], "Level:", reef["Skill Level"], "Photography:", reef["Photography"], "Cautions:", reef["Cautions"]
ability = int(raw_input("How many dives have you had in the last 2 years? "))
reef_ability = dive_ability(ability) # calls dive_ability function, assigns variable
recommend_reef_list = reef_skill_level(reef_ability) # call reef_skill_level function using dive_ability function
display_reef(recommend_reef_list)
# location_input = raw_input("Where would you like to dive? Enter 'm' for Monterey and 'c' for Carmel: ")
# location_list = location(location_input)
# recommend_reef_list = reef_location(location_list) # call reef_location function using reef_location function, displays reefs
# print display_reef(recommend_reef_list)
| true |
4b531b68672179305ddf180bbd9fd3fbd77fb373 | ericgarig/daily-coding-problem | /099-longest-sequesnce.py | 720 | 4.125 | 4 | """
Daily Coding Problem - 2019-01-15.
Given an unsorted array of integers, find the length of the longest
consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive
element sequence is [1, 2, 3, 4]. Return its length: 4.
"""
def solve(arr):
"""Find the length of the longest consecutive sequence."""
arr.sort()
run = 0
max_run = 0
prev = arr[0] - 2 # some non-consecutive previous value
for i in arr:
if prev + 1 == i:
run += 1
prev = i
else:
if run > max_run:
max_run = run
run = 1
prev = i
return max_run
print(solve([100, 4, 200, 1, 3, 2])) # 4
| true |
5be10adb54f954842e734103dc1d77e379c8bf72 | ericgarig/daily-coding-problem | /065-clockwise-spiral.py | 983 | 4.65625 | 5 | """
Daily Coding Problem - 2018-12-12.
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
You should print out the following ( return-delimitted ):
1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12
"""
def print_clockwise(arr):
"""Print an array in a clockwise spiral."""
rows = range(len(arr) + 1)
cols = range(len(arr[0]) + 1)
while rows or cols:
# left to right
for i in rows:
print(arr[cols[0]][i])
# top to bottom
# right to left
# bottom to top
# cols and rows decrease by 1 on both ends
return True
# 1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12
arr = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
print(print_clockwise(arr))
| true |
b138435b703dbb66614995b9093abcccc80ef51e | noahbass/algos | /sort/03-insertion-sort-linked-list-recursive.py | 953 | 4.1875 | 4 | # Insertion Sort with a Linked List (Recursive): an in-place, stable sort
#
# B(n) = n-1 (entire list is already in order)
# W(n) = (n*(n-1))/2 (entire list is in decreasing order)
#
# Input: L[0:n-1] a linked list
# Output: L[0:n-1] sorted in increasing order
def insertion_sort(l, size):
if size <= 1:
return
insertion_sort(l, size-1)
last = l[size - 1]
i = size - 2
while i >= 0 and l[i] > last:
l[i + 1] = l[i]
i -= 1
l[i + 1] = last
def make_item(data, next_item):
return (data, next_item)
def get_data(item):
return item[0]
def get_next(item):
return item[1]
if __name__ == "__main__":
one = [1, 10, 2, 5, -8, 473, 8]
insertion_sort(one, len(one))
two = [438, 23, -12, 0, 43, 0, 12, -9, 84]
insertion_sort(two, len(two))
assert one == [-8, 1, 2, 5, 8, 10, 473]
assert two == [-12, -9, 0, 0, 12, 23, 43, 84, 438]
print(one)
print(two)
| true |
ffb56ad014488113a40de490d81626b1148577bf | thomasolsen/IS105 | /Lab1/ex6.py | 864 | 4.4375 | 4 | # Formatted variables in the string to print the variables i want.
x = "There are %d types of people." % 10
# a variable
binary = "binary"
# Another variable
do_not = "don't"
# Same as x, formatted variables do get em to print, need () and , to get multiple formats printed.
y = "Those who know %s and those who %s." % (binary, do_not)
# prints the strings so humans can read them.
print x
print y
# Same as over with the formatted variables in the string.
print "I said %r." % x
print "I also said: '%s'." % y
# boolean value for true or false.
hilarious = False
# Formatted variable in the string.
joke_evaluation = "Isn't that joke so funny?! %r"
# prints the varbiables with the answer false.
print joke_evaluation % hilarious
# Variables ready to print.
w = "This is the left side of..."
e = "a string with a right side."
# Output variables.
print w + e
| true |
16dc2c568be4b74aa539bc619d6650ae282394d0 | KhvostenkoIhor/khvostenko | /Lesson_7/Lesson_7_DZ_DOP_2_Khvostenko_I_V.py | 1,400 | 4.1875 | 4 | print("""
Задание 2:
В списке целых, заполненном случайными числами, определить минимальный и
максимальный элементы, посчитать количество отрицательных элементов,
посчитать количество положительных элементов, посчитать количество нулей.
Результаты вывести на экран.
""")
import random
numbs = int(input("Сколько чисел вы хотите ввести? "))
a = int(input("Введите начало диапазона "))
b = int(input("Введите конец диапазона "))
x = []
neg = []
poz = []
null = []
for i in range(numbs):
n = random.randint(a, b)
x.append(n)
for i in x:
if i > 0:
poz.append(i)
elif i < 0:
neg.append(i)
elif i == 0:
null.append(i)
print("Все введённые числа: ", x)
print("Минимальное число в списке =", min(x))
print("Максимальное число в списке =", max(x))
print("Количество положительных чисел в списке: ", len(poz))
print("Количество отрицательных чисел в списке: ", len(neg))
print("Количество нулей в списке: ", len(null)) | false |
250c9fd7c5efc00d6119803fff7cfecd3917a389 | KhvostenkoIhor/khvostenko | /Lesson_4/Pract_Mod_3.py | 1,859 | 4.15625 | 4 | """Задание 1
Пользователь вводит с клавиатуры два числа. Нужно
показать все числа в указанном диапазоне.
a = int(input("Введите первое число "))
b = int(input("Введите второе число "))
if a > b:
a, b = b, a
else:
pass
for x in range(a, b):
print(x)
Задание 2
Пользователь вводит с клавиатуры два числа. Нужно
показать все нечетные числа в указанном диапазоне.
a = int(input("Введите первое число "))
b = int(input("Введите второе число "))
if a > b:
a, b = b, a
else:
pass
print("Нечётные числа в диапазоне от", a, "до", b)
for x in range(a, b):
if x % 2 > 0:
print(x)
Задание 3
Пользователь вводит с клавиатуры два числа. Нужно
показать все четные числа в указанном диапазоне.
a = int(input("Введите первое число "))
b = int(input("Введите второе число "))
if a > b:
a, b = b, a
else:
pass
print("Чётные числа в диапазоне от", a, "до", b)
for x in range(a, b):
if x % 2 == 0:
print(x)
Задание 4
Пользователь вводит с клавиатуры два числа. Нужно показать все числа в указанном диапазоне в порядке
убывания."""
a = int(input("Введите первое число "))
b = int(input("Введите второе число "))
if a > b:
a, b = b, a
else:
pass
numbers = []
for el in range(a, b):
numbers.append(el)
numbers.reverse()
for x in numbers:
print(x) | false |
a38a4fc9f0fc87a7a79d7fc8bf9ecbc51411cd29 | mayanknahar/Python-Learn | /comparison.py | 1,130 | 4.375 | 4 | <<<<<<< HEAD
# Comparison:
#Equal: ==
#Not Equal: !=
#Greater: >
#less: <
#Greater or Equal: >=
#less or Equal: <=
#Object Identity: is
a=int(input("Enter any digit for output"))
if a>0 and a<=10:
print("the number is smaller than 10")
elif a>10:
print("the number is greater than 10")
else:
print("the number is 0")
#Boolean:
#and
#or
#not
user='Admin'
logged=True
if user=='Admin' and logged:
print("Welcome to the portal")
else:
=======
# Comparison:
#Equal: ==
#Not Equal: !=
#Greater: >
#less: <
#Greater or Equal: >=
#less or Equal: <=
#Object Identity: is
a=int(input("Enter any digit for output"))
if a>0 and a<=10:
print("the number is smaller than 10")
elif a>10:
print("the number is greater than 10")
else:
print("the number is 0")
#Boolean:
#and
#or
#not
user='Admin'
logged=True
if user=='Admin' and logged:
print("Welcome to the portal")
else:
>>>>>>> 22423b49ef698b803dd276de9de45006fcad6613
print("Bad credentials") | false |
063590d3543b9de625db73a0362e1d3a5850ffe1 | kssonu1811/Assigment | /assigment file/1. Python Basics.py | 1,491 | 4.875 | 5 | # 1. Write a program to print your name.
name = "sajan kumar"
print(name)
# 2. Write a program for a Single line comment and multi-line comments.
# this is single line Comment
"""
this is multi-line comment process
we can write multipul line in side in here
"""
#3. Define variables for different Data Types int, Boolean, char, float, double and print on the Console.
# int data type
int = 1234
print(type(int))
# Boolean datatype
bool = True
bool1 = False
print(type(bool))
print(type(bool1))
# char data type
str = "hello"
print(type(str))
# float data type
float = 1.234
print(type(float))
# double data type
"""Python does not have an inbuilt double data type, but it has a float type that designates a floating-point number. I can count double in Python as float values which are specified with a decimal point."""
data = 9.9
print(data)
print(type(data))
"""Python double star operator"""
x = 1
y = 2
c = x ** y
print(c)
z = 2 * (4 ** 2) + 3 * (4 ** 2 - 10)
print(z)
"""Python double slash"""
print(3 / 2)
print(3 // 2)
# Define the local and Global variables with the same name and print both variables and understand the scope of the variables
""" Global Variable: Outside of all the functions
Local Variable: Within a function block """
Global_Variable = 15
def GV (x):
Local_Variable = 10
print(x*Local_Variable)
GV(Global_Variable)
"""
Output
sajan kumar
<class 'int'>
<class 'bool'>
<class 'bool'>
<class 'str'>
<class 'float'>
9.9
<class 'float'>
1
50
1.5
1
150
""" | true |
bd1565b657be6e5512dcfdc747001bbe351e16b0 | kssonu1811/Assigment | /assigment file/11files.py | 1,471 | 4.375 | 4 | # 1. Write a program to read text file
f=open("sample.txt","r")
while True:
line=f.readline()
if line=='':break
print (line)
f.close()
# 2. Write a program to write text to .txt file using InputStream
lines = ['sample', 'How to write text files in Python']
with open('sample.txt', 'w') as f:
for line in lines:
f.write("welcome in sample.txt :")
f.write(line)
f.write('\n')
f.close()
# 3. Write a program to read a file stream
f = open("abc.txt",'r')
data = f.read()
print(data)
f.close
# 4. Write a program to read a file stream supports random access
f = open("abc.txt",'r')
data = f.read()
data2 =f.seekable()
print(data)
print(data2)
f.close
# 5. Write a program to read a file a just to a particular index using seek()
with open("abc.txt","r+") as f:
text=f.read()
print(text)
print("The Current Cursor Position: ",f.tell())
f.seek(17)
print("The Current Cursor Position: ",f.tell())
f.write("KSS!!!")
f.seek(0)
text=f.read()
print("Data After Modification:")
print(text)
f.close()
# 6. Write a program to check whether a file is having read access and write access permissions
import os,sys
fname = input("enter file name :")
if os.path.isfile(fname):
print("file exists:",fname)
f=open(fname,"r")
else:
print("file does not exist:",fname)
sys.exit(0)
print("the content of file is:")
data=f.read()
print(data)
| true |
693a658a168b88f4dd7d06d44e1768a1cf76bb23 | AnasHamed73/sources | /PycharmProjects/sandbox/venv/Strings.py | 1,747 | 4.53125 | 5 | #!/usr/bin/python2.7
# A comment
############# STRINGS ##################
print r"this is a raw string. any special chars like \n\r\e will not be interpreted"
print """
\
(new lines can be escaped with a backslash)
This is a multi-line
string.
"""
print '''Another form
of multi-line strings,
this time with single quotes
'''
rep = 3 * 'Pep'
print "strings can be multiplied in number by using *,\
and concatenated with +! Viz, " + rep
mul_strs = 'This is ' 'my only line'
print "strings can be defined with multiple juxtaposed literals,\
which are automatically concatenated, viz, " + mul_strs
print """strings can be treated as character arrays (there is no character type in python),
viz, """ + mul_strs[0] + """. Indices are allowed to be negative. Negative indices
start with the end of the array and go back as the numbers get smaller, viz, """ + mul_strs[-1]
print """slicing works by specifying start and/or end indices, viz, """ + mul_strs[0:4] + """
if only the begin index is specified, the end is assumed to be the end of the string, viz, """\
+ mul_strs[4:] + """
if only the end index is specified, the start is assumed to be the first character of the string, viz, """\
+ mul_strs[:4] + """
if no indices are specified, the entire thing is returned, viz, """ + mul_strs[:]
print "Strings are immutable in python, so trying to assign a specific char in a string is an error"
# mul_strs[0] = 'Q' # <-- error
print "nonsensical slices are handled gracefully: " + mul_strs[0:73]
print len(mul_strs)
split_str = "The split function splits the string according to the given separator".split(' ')
print split_str
print ' '.join(['The', 'join', 'function', 'does', 'the', 'opposite', 'of', 'split'])
| true |
61bb902a8e18931e0866a975cb4b2864c361a7f3 | AnasHamed73/sources | /PycharmProjects/sandbox/venv/Iteration.py | 2,533 | 4.5625 | 5 |
# iterables can be traversed in reverse order using the
# reversed() call
for i in reversed(xrange(1, 10)):
print i,
# using enumerate, you can retrieve the index of the current
# element in the iteration, as well as the element itself
for i, v in enumerate(['val1', 'val2', 'val3']):
print i, v
# to enumerate dictionary entries as opposed to just keys
# or just values, use the iteritems() method
diccus = dict(key1=1, key2=2, key3=3)
for k, v in diccus.iteritems():
print k, v
# using zip, you can iterate over multiple iterables at once
questions = ['does it rain?', 'who is the walrus?', 'how high the moon?',
'how about this question?']
answers = ['sometimes', 'Paul', 'pretty high']
for q, a in zip(questions, sorted(diccus.values())):
print q, a
########## FUNCTIONAL STUFF ##########
def even_predicate(i):
return i % 2 == 0
# filter can be given a predicate by which to filter items in an iterable
# with this, we obtain the list of even numbers from 1 to 10
print filter(even_predicate, range(1, 11))
def double_function(x):
return x * 2
# with map you can apply a certain function to each element in an iterable
# with this, we obtain a list in which
# each item of the original list is doubled
print map(double_function, range(1, 11))
# reduce applies a bi-function, which produces a single value from two values
# with this, we are adding every element in the list
print reduce(lambda i, j: i + j, range(1, 11))
########## COMPREHENSIONS ##########
# this notation is called a comprehension. It is another way of creating lists
# here, we are initializing a list by squaring each element from 1 to 10
# this statement is identical to the one directly underneath it
print[x**2 for x in range(1, 11)]
print map(lambda x: x**2, range(1, 11))
# comprehensions can be nested like so
print[(x, y) for x in [1, 2, 3] for y in [4, 1, 2] if x != y]
# equivalent to:
combinations = []
for x in [1, 2, 3]:
for y in [4, 1, 2]:
if x != y:
combinations.append((x, y))
print combinations
two_dim = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
# this comp transposes the matrix two_dim
# this is an example of a comprehension that has another
# comprehension as its expression
print[[row[i] for row in two_dim] for i in range(len(two_dim[0]))]
# equivalent to:
trans = []
for i in range(len(two_dim[0])):
columns = []
for j in range(len(two_dim)):
columns.append(two_dim[j][i])
trans.append(columns)
print trans
| true |
863f6d95c410b2499de3ae94d30ae88f9b2f765d | Garfas/Mantas | /Lesson_10/Lesson_10_Functions.py | 2,084 | 4.375 | 4 | # Lesson 10: Functions
# Create at least 5 different functions by your own and test it.
# Create a function that adds a string ending to each member in a list.
# Create a mini python program which would take two numbers as an input and would return their sum, subtraction, division, multiplication.
# Create a function that returns only strings with unique characters
# a = 2
# b = 5
# def additinio(number1, number2):
# sum = number1 + number2
# return sum
# # # print(number1) jeigu rasysim taip mes klaida
# # c = additinio(10, 15)
# # print(c)
# def print_smth():
# print('hello world')
# a = print_smth()
# print(a)
# my_list = [1, 2, 3]
# my_list = my_list.append(4)
# print(my_list)
# import random
# def get_random_number():
# print(random.randint(0, 10))
# print(get_random_number)
# def find_sum(num1, num2):
# '''Return the sum of num1 and num2.'''
# return num1 + num2 #returns the sum of the number
# variable = find_sum(5,10)
# variable = find_sum(variable, 5)
# print(variable)
# def even_odd(num):
# '''Return 'even' if num is even, and 'odd' if num is odd.
# Paramneters:
# num (int): Any integer Returns:
# def check_if_exist(a=None):
# if a:
# return a
# a = check_if_exist("A")
# print(a)
#Home works
# Create at least 5 different functions by your own and test it.
# Create a function that adds a string ending to each member in a list.
# Create a mini python program which would take two numbers as an input and would return their sum, subtraction, division, multiplication.
# unit_nm = input("newtonmeter:")
# unit_ftlbs_to_unit_nm = ("1.35582")
# operation = input()
# # ftlbs_to_nm = input('1.35582') # 1nm = 1.35582ftlbs
# def ftlbs_to_nm(unit_nm, unit_ftlbs) -> int :
# if operation == '*':
# print('{} * {} =')
# print(unit_nm * unit_ftlbs_to_unit_nm)
# #finde the product of unit_nm and unit_ftlbs_to_unit_nm
# return operation
| true |
bb06d00dbbb3cde8db832280164868023e3ae40f | Daan-Grashoff/INFDEV01-1-assignments-0913610 | /Assignment4/warmup.py | 1,022 | 4.1875 | 4 | __author__ = 'Mac'
# Fahrenheit to celcius
# input for farenheit
input_fahrenheit = input('Give ur Fahrenheit input ')
# formula Fahrenheit to celcius
celcius = (input_fahrenheit - 32) * 5/9
# round celcius
celcius = round(celcius, 2)
# print celcius on screen
print 'celcius is: ',celcius
# celcius to kelvin
# input for celcius
input_celcius = input('Give ur Celcius input ')
while input_celcius < -273.15:
input_celcius = input('Give a correct Celcius input ')
# formula Fahrenheit to celcius
kelvin = input_celcius + 273.15
# print kelvin on screen
print 'Kelvin is: ',kelvin
# absolute number
input_absnumber = input('Give ur absolute number ')
# build in function
absolute = abs(input_absnumber)
# check if number is below 0
if input_absnumber < 0:
# flips number
input_absnumber = -input_absnumber
else:
input_absnumber = input_absnumber
print 'self, Your absolute number is: ',input_absnumber
# using a build in function
print 'build in, Your absolute number is: ',absolute
| false |
ca123d5a250dbbfddd0436111c3164b16064250a | ShashankPatil20/Crash_Course_Python | /Week_4/Dictonaries_Quiz.py | 1,249 | 4.40625 | 4 | """
1.Question 1
The email_list function receives a dictionary, which contains domain names as keys,
and a list of users as values. Fill in the blanks to generate a list that contains complete
email addresses (e.g. diana.prince@gmail.com).
"""
def email_list(domains):
emails = []
for names, users in domains.items():
for user in users:
emails.append(user + "@" + names)
return (emails)
print(email_list(
{"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": ["barbara.gordon", "jean.grey"],
"hotmail.com": ["bruce.wayne"]}))
"""
2.Question 2
The groups_per_user function receives a dictionary, which contains group names
with the list of users. Users can belong to multiple groups.
Fill in the blanks to return a dictionary
with the users as keys and a list of their groups as values.
"""
def groups_per_user(group_dictionary):
user_groups = {}
for group, users in group_dictionary.items():
for user in users:
if user not in user_groups:
user_groups[user] = []
user_groups[user].append(group)
return user_groups
print(groups_per_user({"local": ["admin", "userA"],
"public": ["admin", "userB"],
"administrator": ["admin"] }))
| true |
304148104d2ea48ba263277e2db68634c08069ae | ShashankPatil20/Crash_Course_Python | /Week_3/While_Loop_Quiz.py | 2,741 | 4.53125 | 5 | #1. Fill in the blanks to make the print_prime_factors function print all the prime factors of a number. A prime factor
# is a number that is prime and divides another without a remainder.
Ans.
def print_prime_factors(number):
# Start with two, which is the first prime
factor = 2
# Keep going until the factor is larger than the number
while factor <= number:
# Check if factor is a divisor of number
if number % factor == 0:
# If it is, print it and divide the original number
print(factor)
number = number / factor
else:
# If it's not, increment the factor by one
factor +=1
return "Done"
print_prime_factors(100)
# Should print 2,2,5,5
# DO NOT DELETE THIS COMMENT
#2.
# Fill in the empty function so that it returns the sum of all the divisors of a number, without including it.
# A divisor is a number that divides into another without a remainder.
#Ans.
import math
def sum_divisors(num):
# Final result of summation of divisors
if num == 0:
return 0
else:
result = 0
# find all divisors which divides 'num'
i = 2
while i <= (math.sqrt(num)):
# if 'i' is divisor of 'num'
if (num % i == 0):
# if both divisors are same then
# add it only once else add both
if (i == (num / i)):
result = result + i;
else:
result = result + (i + num / i);
i = i + 1
# Add 1 to the result as 1 is also
# a divisor
hell = int(result + 1)
return (hell)
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
#3. The multiplication_table function prints the results of a number passed to it multiplied by 1 through 5.
# An additional requirement is that the result is not to exceed 25, which is done with the break statement.
# Fill in the blanks to complete the function to satisfy these conditions.
#Ans.
def multiplication_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = number*multiplier
# What is the additional condition to exit out of the loop?
if result>25 :
break
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1
multiplication_table(3)
# Should print: 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15
multiplication_table(5)
# Should print: 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
multiplication_table(8)
# Should print: 8x1=8 8x2=16 8x3=24 | true |
7d13aa28a897c5043a5ce176805fae39b36404cf | Younggle/python_learn | /string_test2.py | 949 | 4.15625 | 4 | ## --------------------string methods --------------
#from string import join
rand_string = ' life is A beautiful struggle '
print (rand_string)
#delete space on the left
rand_string1= rand_string.lstrip()
print (rand_string1)
#delete space on the right
rand_string2= rand_string.rstrip()
print (rand_string2)
#delete spaces on the right and left
rand_string3= rand_string.strip()
print (rand_string3)
print (rand_string)
print ()
# capitalize first letter
print (rand_string.capitalize())
#capitalize every letter
print (rand_string.upper())
#lowercase all letter
print (rand_string.lower())
print ("")
test_list = ['yangle','is','a','good','man']
print(''.join(test_list))
print ('*'.join(test_list))
print("")
test_list2=rand_string.split()
print (test_list2)
print (rand_string)
print ("how many 'if' :",rand_string.count("if"))
print ("where is 'is' :",rand_string.find("is"))
print (rand_string.replace("struggle","journey")) | true |
722f7dcdc0147e6b5a067dca52d783074f8cf55c | Younggle/python_learn | /if test.py | 1,508 | 4.125 | 4 | #------ if test -----
#name=raw_input('Enter User ID:')
#name = 'yangle'
#if name == 'yangle':
# print("hello ,my dad")
#
#else:
# print('go away,')
# ---------------- user loading (if...elif & while)----------------------
# can input times
input_times=5
while input_times >=1:
name = raw_input("what's your name?'")
pass_wd = raw_input("press password:")
if name == 'yangle' and pass_wd == 'yl1234':
print("welcome!")
break
elif name != 'yangle' and pass_wd == 'yl1234':
print('name or password not current')
input_times=input_times-1
remaining_times = str(input_times)
print('you still have ' + remaining_times + ' times to input')
if input_times == 0:
print('you are not allow enter')
break
elif name =='yangle' and pass_wd !='yl1234':
print('name or password not current')
input_times = input_times - 1
remaining_times = str(input_times)
print('you still have '+ remaining_times + ' times to input')
if input_times == 0:
print('you are not allow enter')
break
else:
# print("fuck off!")
print('your password not current')
input_times = input_times - 1
remaining_times=str(input_times)
print('you still have ' + remaining_times + ' times to input')
if input_times == 0:
print('your input times is over,you are not allow enter')
#------------------- | false |
b374dca4b0863e73be1e5174dfd6fe6de8514703 | AviralS16/Python-Class | /Sept27 Homework.py | 704 | 4.25 | 4 | print("This is a English to Pig Latin translator")
word_input = input("Enter a word: ")
word_to_list = list(word_input)
first_letter = word_to_list[0]
print(first_letter.upper())
if first_letter.upper() == "A" or first_letter.upper() == "E" or first_letter.upper() == "I" or first_letter.upper() == "O" or first_letter.upper() == "U":
word_to_list.append("-way")
pig_latin_word = "".join(word_to_list)
print("Your word in Pig Latin is: " + pig_latin_word)
else:
word_to_list.append(first_letter)
word_to_list.append("-ay")
del(word_to_list[0])
pig_latin_word = "".join(word_to_list).lower()
print("Your word in Pig Latin is: " + pig_latin_word) | false |
4c431acf622dd65cbb10b881deae15d21160fd96 | rajankumar17/Python-Workspace | /5. Chapter 5/06_set_operations.py | 588 | 4.3125 | 4 | # Demonstrate set operations on unique letters from two words
a = set('abracadabra')
b = set('alacazam')
print(a) # {'a', 'r', 'b', 'c', 'd'} # unique letters in a
print(a - b) # letters in a but not in b {'r', 'd', 'b'}
print(a | b) # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
print(a.union(b)) # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
print(a & b) # letters in both a and b {'a', 'c'}
print(a.intersection(b)) # letters in both a and b {'a', 'c'}
print(a ^ b) # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'} | false |
eb57f332f0197e8f2ba2c3bec4a8c4c98687fcd7 | rajankumar17/Python-Workspace | /11. Chapter 11/08_operator_overloading.py | 535 | 4.28125 | 4 | class MyNumber:
def __init__(self, num):
self.num = num
def __add__(self, num2):
print("Lets add")
return self.num + num2.num
def __mul__(self, num2):
print("Lets multiply")
return self.num * num2.num
n1 = MyNumber(4)
n2 = MyNumber(6)
sum = n1 + n2 #without __add__ n1 and n2 will be not added.because it does not understand n1 or n2 which is MyNumber and not a number
mul = n1 * n2
#div = n1 / n2 # __truediv__ should be overloaded else it will give error
print(sum)
print(mul)
| true |
0e5e51f803f286f3e5309663c1ab7dcc9f0b4d99 | rajankumar17/Python-Workspace | /Code Practice/CollectionsTuplePractice.py | 1,166 | 4.46875 | 4 | # Collections tuple - practice
# 1 - Create a tuple of tech terms
technological_terms = ('python', 'pycharm IDE', 'tuple', 'collections', 'string')
print('(1) - This is the tuple collections : ' +str(technological_terms))
# 2 - Print a sentence using cell extraction : Regular & negative
#we are ninja developers. We write python code in pycharm IDE, and now practicing tuple collections topic, that contains string variables.
print("(2) - we are ninja developers. We write " +technological_terms[0] +" code in " +technological_terms[-4]
+", and now practicing " +technological_terms[2] +" collections topic, that contains " +technological_terms[-1] +" variables.")
# 3 - Insert 'float' and 'list' variables into the tuple
technological_terms_list = list(technological_terms)
technological_terms_list.append('float')
technological_terms_list.append('list')
technological_terms = tuple(technological_terms_list)
print("(3) - This is our new tuple with the added cells : " +str(technological_terms))
# 4 - Create a single cell tuple
single_cell_tuple = (1,)
print("(4) - Print the single cell tuple : " +str(single_cell_tuple))
print(type(single_cell_tuple))
| true |
3c6aa3315cced2802f3d5160b9790facb465b607 | rajankumar17/Python-Workspace | /2. Chapter 2/02_operators.py | 868 | 4.15625 | 4 | a = 3
b = 4
c,d=5,6
print(a,b,c,d)
print(-a,-b,-c,-d) #negate
# Arithmetic Operators
print("The value of 3+4 is ", 3+4)
print("The value of 3-4 is ", 3-4)
print("The value of 3*4 is ", 3*4)
print("The value of 3/4 is ", 3/4)
print("The value of 3**4 is ", 3**4) #power
print("The value of 3**4 is ", pow(3,4)) #power
# Assignment Operators
a = 34
print(a)
a -= 12
print(a)
a *= 12
print(a)
a /= 12
print(a)
# Comparison Operators
b = (14<=7)
print(b)
b = (14>=7)
print(b)
b = (14<7)
print(b)
b = (14>7)
print(b)
b = (14==7)
print(b)
b = (14!=7)
print(b)
# Logical Operators
bool1 = True
bool2 = False
print("The value of bool1 and bool2 is", (bool1 and bool2))
print("The value of bool1 or bool2 is", (bool1 or bool2))
print("The value of not bool2 is", (not bool2))
#Number system
print(bin(25))
print(hex(25))
print(oct(25))
print(0b11001)
print(0x19)
print(0o31) | true |
66b46ea6313be3cafcc4cb4c021ea4f6cef03072 | MayankAgarwal/GeeksForGeeks | /check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not.py | 1,359 | 4.28125 | 4 | '''
URL: http://www.geeksforgeeks.org/check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not/
====
Python 2.7 compatible
Problem statement:
====================
Given a sequence of moves for a robot, check if the sequence is circular or not. A sequence of moves is circular if first and last positions of robot are same. A move can be on of the following.
G - Go one unit
L - Turn left
R - Turn right
'''
from operator import add
import math
moves = raw_input("Enter the moves: ")
start_position = [0,0]
current_position = [0,0]
'''
heading = [1,90] - 1 step North
[1, -90] - 1 step South
[1,0] - East
[1,+-180] - West
'''
heading = [1,0]
for move in moves:
if move.upper() == "G":
angle = heading[1]
step = heading[0]
# move_coord holds the x and y coordinate movement for the robot
move_coord = [ round(step*math.cos(math.radians(angle))), round(step*math.sin(math.radians(angle))) ]
current_position = map(add, current_position, move_coord)
elif move.upper() == "L":
# turn the robot 90 degrees anti-clockwise
heading = map(add, heading, [0, 90])
elif move.upper() == "R":
# turn the robot 90 degrees clockwise
heading = map(add, heading, [0, -90])
if start_position == current_position:
print "Given sequence of moves is circular"
else:
print "Given sequence of moves is NOT circular" | true |
aae8dd2cf499b24692908b50765b4027dae9d594 | banerjeesamrat/automatetheboringstuff.com-LearningAutomationwithPython | /Chapter5-Dictionaries and Structuring Data/inventory.py | 1,422 | 4.375 | 4 | """
You are creating a fantasy video game. The data structure to model the player’s
inventory will be a dictionary where the keys are string values describing the
item in the inventory and the value is an integer value detailing how many of
that item the player has.For example, the dictionary value
{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
means the player has 1 rope, 6 torches, 42 gold coins, and so on.
Write a function named displayInventory() that would take any possible
“inventory” and display it like the following:
Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 62
Hint: You can use a for loop to loop through all the keys in a dictionary.
# inventory.py
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
# FILL IN THE CODE HERE
print("Total number of items: " + str(item_total))
displayInventory(stuff)
"""
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
# FILL IN THE CODE HERE
print(str(v)+ ' '+str(k))
item_total=item_total+inventory.get(k,0)
print("Total number of items: " + str(item_total))
displayInventory(stuff)
| true |
ab68980815e67a5a416dc1abba4ca07773d9e8f1 | banerjeesamrat/automatetheboringstuff.com-LearningAutomationwithPython | /Chapter6-ManipulatingStrings/pw.py | 776 | 4.15625 | 4 | #! /usr/bin/python3.5
# First Project of An Insecure Password Locker Program
# Author: Samrat Banerjee
# Date: 15-03-2018
# The dictionary will be the data structure that organizes your account and password data.
# Step1-Program Design and Data Structures
PASSWORDS={'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
# Step2-Handle Command Line Arguments
import sys,pyperclip
if len(sys.argv)<2:
print('Usage: python pw.py[account]-copy account password')
sys.exit()
account=sys.argv[1] # first command line arg is the account name
# Step3-Copy the Right Password
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for '+account+' copied to clipboard')
else:
print('There is no account named '+account)
| true |
4db0a5a727fe0d1a2b00236f47efcb2ee62ed0de | FrancoCalle/Python_4_DataScience | /Module_1/tutorial_python_clase5.py | 2,810 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Python para Economistas: Quinta Clase
Autor: Franco Calle
- The flow of execution, arguments, and parameters
- Adding new functions
- Definitions and uses
- Annonimous functions Lambda
- Mapping and filtering
- Numpy module
"""
import numpy as np
import pandas as pd
import time
import random
import matplotlib.pyplot as plt
# Creando una funcion
#Ejemplo 1
def miPrimeraSuma(a,b):
return a+b
miPrimeraFuncion(1,2)
suma = miPrimeraFuncion(1,2)
print(suma)
#Ejemplo 2
def miSegundaSuma(a=None,b=None):
if a != None and b != None:
return a+b
elif a == None or b != None:
return b
elif a != None or b == None:
return a
else:
return None
miSegundaSuma(None,None)
# Funciones anonimas usando lambdas
suma = lambda x, y: x + y
suma(1,2)
resta = lambda x, y: x - y
resta(1,2)
# Mapping a function over lists:
dataX = [3, 4 , 6, 5, 10, 15]
dataY = [5, 7 , 0, 8, 2, 4]
map(suma, dataX, dataY)
list(map(suma, dataX, dataY))
list(map(resta, dataX, dataY))
list(map(lambda x, y: x + y, dataX, dataY))
list(map(lambda x, y: x - y, dataX, dataY))
# Filtrando una list:
alphabets = ['a', 'b', 'c', 'e', 'i', 'j', 'u']
# Funcion que filtra vocales:
def filtraVocales(letra):
vocales = ['a', 'e', 'i', 'o', 'u']
if(letra in vocales):
return True
else:
return False
filteredVowels = filter(filtraVocales, alphabets)
list(filteredVowels)
filteredVowels = list(filter(lambda x: x in ['a', 'e', 'i', 'o', 'u'], alphabets))
# Numpy module
import numpy as np
miMatrix = np.ones((5,5))
miMatrix = np.ones((5,5,5))
miMatrix = np.zeros((5,5))
miMatrix = np.random.rand(5,5)
print(miMatrix)
# Numpy Arrays has multiple methods included
myArray = np.array([[1, 2],[1, 2]])
myArray.sum(0)
myArray.sum(1)
myArray.mean(1)
myArray.max(1)
myArray.min(1)
myArray.max(1)
myArray.std(1)
myArray.transpose()
for row in miMatrix:
print(row)
for col in miMatrix.transpose():
print(col)
#Variable aleatoria normalmente distribuida:
xi = np.random.normal(1,.5) # Variable aleatoria con media 1 y variancia 5
X = np.random.normal(1,.5, 10000) # Mil ocurrencias:
Xbar = X.mean()
Sigma2 = sum((Xbar-X)**2)/X.shape[0]
Sigma = np.sqrt(Sigma2)
plt.hist(X)
#Variable aleatoria que proviene de una binomial:
X = np.random.binomial(100, 0.2, 100000) # Variable aleatoria con media 1 y variancia 5
plt.hist(X)
(X>=30).mean() # Probabilidad de que la moneda caiga cara 30 veces de las 100
# Cual es la probabilidad que hayan dos terremotos dos dias seguidos en Peru
T = np.random.binomial(1, 0.02, 1000000) # Variable aleatoria con media 1 y variancia 5
ii = 0
for dd in range(1,1000000):
if T[dd] == 1 and T[dd-1] == 1:
ii += 1
print(str(ii), 'veces en', str(round(1000000/365)), "Anhos")
| false |
912bfde18a1ab0c7e0a7cf8dfb381e7efee00bb4 | dushyantss/ctci-python | /ch01_arrays_and_strings/q01_is_unique.py | 942 | 4.21875 | 4 | #! /usr/bin/python
"""
Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
"""
def is_unique(s: str):
return is_unique_no_additional_ds(s)
def is_unique_no_additional_ds(s: str):
"""
Since we cannot modify a string, I've had to create a list from the string.
If we are provided a mutable string, we could sort in place.
Time: O(n log(n)), Space: O(1)
"""
l = list(sorted(s))
for i, c in enumerate(l):
if i <= len(l) - 2:
if c == l[i + 1]:
return False
return True
def is_unique_with_set(s: str):
"""
Time: O(n), Space: O(n)
"""
char_set = set()
for char in s:
if char in char_set:
return False
char_set.add(char)
return True
if __name__ == "__main__":
import sys
for line in sys.stdin:
print(is_unique(line))
| true |
4922fc896aee3529cfbaeb6d5016b42f3ae1b3b8 | dushyantss/ctci-python | /ch04_trees_and_graphs/q04_check_balanced.py | 1,003 | 4.3125 | 4 | """
Check Balanced: Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
"""
from binary_tree import BinaryNode
IMBALANCED = -1
def check_balanced(node):
if not node:
return 0
left_height = check_balanced(node.left)
if left_height < 0:
return IMBALANCED
right_height = check_balanced(node.right)
if right_height < 0:
return IMBALANCED
if abs(left_height - right_height) > 1:
return IMBALANCED
return 1 + max(left_height, right_height)
if __name__ == '__main__':
tree = BinaryNode(0)
tree.left = BinaryNode(1)
tree.right = BinaryNode(2)
# tree.right.left = BinaryNode(6)
tree.left.left = BinaryNode(3)
tree.left.right = BinaryNode(4)
tree.left.right.right = BinaryNode(5)
print(check_balanced(tree))
print(check_balanced(tree.left))
| true |
e88cf0a20377040c9826cccdae9b1fe73d8ac8d7 | dushyantss/ctci-python | /ch01_arrays_and_strings/q09_string_rotation.py | 919 | 4.34375 | 4 | #! /usr/bin/python
"""
String Rotation:Assumeyou have a method isSubstring which checks if one word is a substring of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g.,"waterbottle" is a rotation of"erbottlewat").
"""
def string_rotation(s1: str, s2: str):
# We have to use is_substring
# In the rotation, there will be two parts of the string which will switch places.
# e.g. in waterbottle and erbottlewat; wat is first part and erbottle is the second part
return len(s1) == len(s2) and is_substring(s1 + s1, s2)
def is_substring(word: str, probable_substring: str):
return probable_substring in word
if __name__ == "__main__":
import sys
for line in sys.stdin:
str1, str2 = line.split(", ")
str2 = str2[:-1] # This is done to remove the ending \n
print(string_rotation(str1, str2))
| true |
12519a672bb72be8c01a271c897cbe3cdda33614 | dushyantss/ctci-python | /ch01_arrays_and_strings/q06_string_compression.py | 1,042 | 4.625 | 5 | #! /usr/bin/python
"""
String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return
the original string. You can assume the string has only uppercase and lowercase letters (a - z).
"""
def compress(text: str):
if not text:
return text
prev = text[0]
count = 1
result = []
for _, c in enumerate(text, 1):
if c != prev:
result.append(prev)
result.append(str(count))
prev = c
count = 1
else:
count += 1
result.append(prev)
result.append(str(count))
new_text = "".join(result)
if len(text) > len(new_text):
return new_text
else:
return text
if __name__ == "__main__":
import sys
for line in sys.stdin:
# Remove newline character
print(compress(line[:-1]))
| true |
bbf6487101656ed0b21f4356af8b88843390808d | gitgogo/learn-python | /python-code/chapter7_7.py | 343 | 4.1875 | 4 | #coding=utf-8
#颠倒输入的字典
raw_dict={}
ch_dict={}
key=raw_input('input the key of dict: ')
value=raw_input('input the value: ')
raw_dict[key]=value
ch_dict[value]=key
print 'the raw dict is %s\nthe changed dict is %s'%(str(raw_dict),str(ch_dict))
# dict1=dict(raw_input('input a dict: '))
# print {dict1.values()[0]:dict1.keys()[0]} | false |
f7893f09e112acc946b4d870d105faddb66475a9 | Sanchez-Antonio/python-learn-in-spanish | /programacion orientada a objetos/1.atributos y metodos.py | 1,284 | 4.28125 | 4 |
#------------------encapsulamiento-----------------------------------
#creación de la clase
class makepeople():
#propiedades del metodo padre
eyes = 2
life = False
hands = 2
foot = 2
hair = True
#metodo
def resucitar(self): #self(hace referencia al propio objeto, es decir el parametro que se le pasa es el objeto)
self.life = True #self.para contatenar con el objeto(self)
#metodo para verificar el estado
def estado(self):
if self.life == True:
print("esta vivo")
else:
print("está muerto")
#---------------------------------encapsulamiento------------------
# se encuentra encapsulada la clase, sus intancias solo són
# accesibles desde afuera con metodos
#instanciar la clase(se crea el objeto)
alexcibor = makepeople()
#segundo objeto instanciado a la clase padre
cristiancibor = makepeople()
print(f"el cibor alex se encuentra--> {alexcibor.life}")
#llamo al metodo para cambiar una de sus propiedades y darle vida
alexcibor.resucitar()
print(f"el cibor alex se encuentra -->{alexcibor.life}")
#uso un metodo para imprimir el estado del cibor ya que
#está encapsulado desde afuera
print(alexcibor.estado())
print("-------segunda instancia estado--------")
print(cristiancibor.estado())
| false |
8b8a1c1d3ccc1785269cfddbddaa2c78a12e1059 | wolfatthegate/HackerRank-Practice | /src/isAny.py | 687 | 4.125 | 4 |
'''
In the first line, print True if has any alphanumeric characters. Otherwise, print False.
In the second line, print True if has any alphabetical characters. Otherwise, print False.
In the third line, print True if has any digits. Otherwise, print False.
In the fourth line, print True if has any lowercase characters. Otherwise, print False.
In the fifth line, print True if has any uppercase characters. Otherwise, print False.
'''
if __name__ == '__main__':
s = 'aK47'
print (any(c.isalnum() for c in s))
print (any(c.isalpha() for c in s))
print (any(c.isdigit() for c in s))
print (any(c.islower() for c in s))
print (any(c.isupper() for c in s)) | true |
fb1dd5392af4804e65ee941d30d508001e0f398a | benryan03/Python-Practice | /basic-part1-exercise036-add_if_int.py | 450 | 4.3125 | 4 | #https://www.w3resource.com/python-exercises/python-basic-exercises.php
#36. Write a Python program to add two objects if both objects are an integer type.
a = input("Enter something: ")
b = input("Enter something else: ")
try:
a = int(a)
except ValueError:
pass
try:
b = int(b)
except ValueError:
pass
if type(a) == int and type(b) == int:
print("Result: " + str(a + b))
else:
print("One or more inputs is not an int.") | true |
40b935d7dfdbdc64d4c495dd50e5a1b1ff4426f2 | benryan03/Python-Practice | /basic-part1-exercise017-within100.py | 427 | 4.3125 | 4 | #https://www.w3resource.com/python-exercises/python-basic-exercises.php
#17. Write a Python program to test whether a number is within 100 of 1000 or 2000. Go to the editor
x = int(input("Enter a number: "))
if x >= 900 and x <= 1100:
print(str(x) + " is within 100 of 1,000.")
elif x >= 1900 and x <= 2100:
print(str(x) + " is within 100 of 3,000.")
else:
print(str(x) + " is not within 100 of 1,000 or 2,000.") | true |
e46047bb4466f5339df28bd4d1bbc8e589e6ea28 | benryan03/Python-Practice | /basic-part1-exercise008-colors.py | 257 | 4.1875 | 4 | #https://www.w3resource.com/python-exercises/python-basic-exercises.php
#7. Write a Python program to display the first and last colors from the following list.
color_list = ["Red","Green","White" ,"Black"]
print(color_list[0])
print(color_list[3])
| true |
2bb652fc4c1684368f8d8746167c2edcca6bbd5d | Esteban1891/python_coursera | /strings.py | 446 | 4.3125 | 4 | str = "hello world"
#methods
print(str.upper()) # generate words in uppercase
print(str.lower()) # generate words or strings in lowercase
print(str.capitalize()) #generate the first word in upper
print(str.count("o")) #count words in my strings
print(str.endswith("d")) # tested with bool if is true o false last end word
print(str.replace('hello', 'HELLO').split()) # generate to replace words also split strings
print(str.startswith('hello'))
| true |
f27dca928d78cd87d3799618319ba6cd4214cfdd | Chris-hu-liao/corona | /Hello.py | 416 | 4.15625 | 4 | print("hello world")
name=input("Best country in the world: ")
print(name)
name=name.lower()
if (name=="Canada"):
print(name +"is the best")
elif (name=="Norway"):
print(name.Lower()+"is the second best")
else:
print("BOOO WRONG ANSWER")
fruits=['apple, grannysmtih, gale','banana','peach, sweet,not sweet','orange,mandarin,bloodrange','banana,big,small']
for fruit in fruits:
print(fruit)
| true |
50e5a3aa9d9337c15fbfb1c99398c308cd1e7723 | ganzaro/trade_demo | /app/mini_red/list_ops.py | 1,359 | 4.15625 | 4 |
"""
GET key : Return the List value identified by key
SET key value : Instantiate or overwrite a List identified by key with value value
DELETE key : Delete the List identified by key
APPEND key value : Append a String value to the end of the List identified by key
POP key : Remove the last element in the List identified by key, and return that elt
TODO
assert value type is list
"""
class ListMap():
def __init__(self):
self._mapz = {}
def set_kv(self, k, v):
"""Adds the pair (k, v) """
# assert type(v) == list
self._mapz[k] = v
def contains(self, k):
"""Returns true if the map contains the given key"""
return k in self._mapz
def get(self, k):
"""Returns the value associated with the key"""
if self.contains(k):
return self._mapz[k]
else:
raise KeyError("Key not found")
def delete_key(self, k):
self._mapz.pop(k, None)
def append_value(self, k, v):
"""Append a value to the end of the List identified by key"""
lst = self.get(k)
lst.append(v)
self.set_kv(k, v)
def pop_key(self, k):
"""Remove the last List element identified by key,
and return that element """
lst = self.get(k)
val = lst.pop()
return val
| true |
9838ff59705652a2f3947021f99dbfda31511da8 | smgross/learning_python | /object.py | 1,218 | 4.28125 | 4 | #!/bin/env python
import sys
import re
import os.path
class Animal(object):
"""
THis is an example from Treading on Python Volume 1
"""
def __init__(self,name):
self.name = name
def talk(self):
"""
Make the beast talk
"""
print "Generic animal sound!"
### How do I print the name passed into the object constructor?
#Following code does not work!
#def printname(name):
# print "Name is %s" % name
# print name
# print "self.name is %s " % self.name
def printself(self):
#print "Self is %s" % self
#print self
print "self.name is %s " % self.name
# The following is a subclass
class Dog(Animal):
def talk(self):
print "%s says 'Bark, bark!'" % self.name
class Cat(Animal):
def talk(self):
print "%s says 'Meow, meow!'" % self.name
print "\nInvoking Animal, a creature called 'Thing1'"
creature = Animal("Thing1")
creature.talk()
creature.printself()
print "\nIvoking Animal, an iguana named 'Freddy'"
iguana = Animal("Freddy")
iguana.printself()
print "\nInvoking Dog, a dog named 'Zephyr'"
zephyr = Dog("Zephyr")
zephyr.talk()
zephyr.printself()
print "\nInvoking Cat, a cat name 'Kitty'"
kitty = Cat("Kitty")
kitty.talk()
kitty.printself()
| false |
a148a68aba913a8f2984dafbb8e1de86e7f78fed | NenadPantelic/DailyInterviewPro | /20_04_04_sorting_a_list_with_3_unique_numbers.py | 1,038 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 6 13:40:40 2020
@author: nenad
"""
"""
Problem description:
Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
Example 1:
Input: [3, 3, 2, 1, 3, 2, 1]
Output: [1, 1, 2, 2, 3, 3, 3]
Challenge: Try sorting the list using constant space.
"""
# Universal solution for any three numbers
from collections import Counter
def sortNums(nums):
counter = Counter()
# count occurences of elements - O(n)
for val in nums:
counter[val] += 1
# sort values present in array
values = sorted(counter.keys())
offset = 0
# O(n) - based on freqs update value of every element
for val in values:
i = 0
# set counter[val] values of elements with value val
while i < counter[val]:
# new positions
nums[i+offset] = val
i += 1
offset += counter[val]
return nums
print (sortNums([3, 3, 2, 1, 3, 2, 1]))
# [1, 1, 2, 2, 3, 3, 3] | true |
204431a3e96ae5fc337db1ec562867f3707a4b2f | emmett-shang/my-pandas | /variable_types.py | 788 | 4.4375 | 4 | list = ['abcd', 786, 2.23, 'john', 70.2]
tinylist = [123, 'johnny']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 2) # Prints list two times
print(list + tinylist)
str = 'Hello World!'
print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST")
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print(counter)
print(miles)
print(name)
| true |
bee968892f9aa109d0cf47779d8f6e814eb9041b | emmett-shang/my-pandas | /sandbox/printing_odd_and_even_numbers.py | 525 | 4.34375 | 4 | """
# https://www.datacamp.com/community/tutorials/python-list-comprehension
"""
# print odd numbers from 0 to 20
print("This is the odd number list from 0 to 20:")
numbers = range(0, 21)
for n in numbers:
if n % 2 != 0:
print(n)
# print event numbers from 30 to 50
print("This is the even number list from 30 to 50:")
numbers_E = range(30, 51)
for nE in numbers_E:
if nE % 2 == 0:
print(nE)
print("This list doubles every number from 0 to 20:")
new_list = [n * 2 for n in numbers]
print(new_list)
| true |
791da0ab8e0cbb62d3e7033c1c081d1a7b30fe97 | emmett-shang/my-pandas | /classes.py | 1,056 | 4.125 | 4 | class Greeter(object):
# Constructor
def __init__(self, name):
self.name = name # Create an instance variable
# Instance method
def greet(self, loud=True):
if loud:
print('HELLO, %s!' % self.name.upper())
else:
print('Hello, %s' % self.name)
def shake_hand(self, soft=False):
if soft:
print('Shake hands, %s!' % self.name)
else:
print('Ow, %s!' % self.name)
def bow(self, hard=True):
if hard:
print('greetings your majesty, %s!' % self.name)
else:
print('morning, %s!' % self.name)
g = Greeter('Fred') # Construct an instance of the Greeter class
g.shake_hand()
g = Greeter('Ivy')
g.greet()
g.shake_hand()
g.bow()
g = Greeter('Daddy')
g.greet()
g.shake_hand()
g.bow()
g = Greeter('Mummy')
g.greet()
g.shake_hand()
g.bow()
g = Greeter('Emmett')
g.shake_hand() # Call an instance method; prints "Hello, Fred"
g.shake_hand(soft=True) # Call an instance method; prints "HELLO, FRED!" | false |
3dc2f9d111f557589dc627380d766c4046cf82d2 | sandeepjoseph/Python-Assignments | /phw1.py | 2,097 | 4.125 | 4 | #Program to find the number a user guessed
#Author : Sandeep Joseph
#Date : 09/12/2014
#Version: V1.0
#import Statements
import sys
print("--------------------------Number Guess Game------------------------\n")
#Initial Variable declaration
choice = True
MyName1 = input("Please enter your name : ")
l = len(MyName1)
MyName11 = MyName1[0].upper()
MyName = MyName11+MyName1[1:l]
#Iterating loop for multiple user attempts
while choice == True:
invalid = False
count = 0
hi = 100
lo = 1
mid = ( hi + lo ) // 2
print("\nDear "+MyName+" Please Guess A Number between 0 and 100!!!")
UserResponse = " "
while UserResponse.lower() != "yes":
CalculatedGuess = mid
UserResponse = input("\nIs "+ str(mid) +" your Number??\n")
if UserResponse.lower() == "no":
UserResponse1 = input("\nIs your number higher??\n")
if UserResponse1.lower() == "yes":
lo = CalculatedGuess + 1
mid = (lo + hi) // 2
elif UserResponse1.lower() == "no":
hi = CalculatedGuess - 1
mid = (lo + hi) // 2
else:
print("\nInvalid User Input!!!\n")
invalid = True
break
else:
print("\nInvalid User Input!!!\n")
invalid = True
count += 1
if invalid != True:
print("\nThe Number you guessed : "+str(CalculatedGuess))
print("\nNumber of Attempts : "+str(count))
ch = input("\nDo you wish to play again??\nplease enter yes/no!!\n")
if ch.lower() == "yes":
choice = True
continue
elif ch.lower() == "no":
choice == False
print("\nThank you "+MyName+" visit back again!!")
sys.exit() #system termination of program
#------------------------------------------------------------------------------#
| true |
074fe9675e6deb8c5f30adf9e16a227e4980dc44 | citlali-trigos-raczkowski/introduction-to-computer-science | /6.0001/4-Caeser-Cipher/ps4a.py | 1,877 | 4.375 | 4 | # Problem Set 4A
# Name: Citlali Trigos
# Collaborators: none
# Date: 6/7/20
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'ab'
'''
if len(sequence) ==1: return [sequence]
permutations = []
for word in get_permutations(sequence[1:]):
for i in range(len(word)+1):
permutations.append(word[:i] + sequence[0] +word[i:])
return permutations
if __name__ == '__main__':
# # Put three example test cases here (for your sanity, limit your inputs
# to be three characters or fewer as you will have n! permutations for a
# sequence of length n)
def test(input, correct_output):
output = get_permutations(input)
output.sort(), correct_output.sort()
if not output == correct_output:
print('Failed on input: ' + input)
return 'passed'
correct_ab = ['ab', 'ba']
correct_abc = ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
correct_abcd = ['abcd', 'bacd', 'bcad', 'bcda', 'acbd', 'cabd', 'cbad', 'cbda', 'acdb', 'cadb', 'cdab', 'cdba', 'abdc', 'badc', 'bdac', 'bdca', 'adbc', 'dabc', 'dbac', 'dbca', 'adcb', 'dacb', 'dcab', 'dcba']
if test('ab', correct_ab) == test('abc', correct_abc) == test('abcd', correct_abcd) =='passed':
print('*****************')
print('Supa nice: All tests passed!')
| true |
064edc7cbd55c1e8e0510d049c28ce00c2c458b2 | jordan-hamilton/325-Homework-1 | /insertsort.py | 1,313 | 4.15625 | 4 | #!/usr/bin/env python3
# Open the file with the passed name as read only, using the readlines method to insert each line into a list, then
# return the created list.
def openFile(fileName):
with open(fileName, 'r') as file:
contents = file.readlines()
return contents
# Append each element in the passed list onto a new line, writing to a file with the name passed in the second argument
def appendListToFile(listToWrite, fileName):
with open(fileName, 'a') as file:
for number in listToWrite:
file.write('%s ' % number)
file.write('\n')
# Open the data.text file, convert the list created from each line into a list of integers, then append the result of
# insertion sort into insert.txt
def main():
text = openFile('data.txt')
for line in text:
toSort = line.split()
del toSort[0]
toSort = list(map(int, toSort))
appendListToFile(insertionSort(toSort), 'insert.txt')
# Insertion sort as adapted from psuedocode in Cormen, p. 18
def insertionSort(numbers):
for j, key in enumerate(numbers[1:], start=1):
i = j - 1
while i >= 0 and numbers[i] > key:
numbers[i + 1] = numbers[i]
i -= 1
numbers[i + 1] = key
return numbers
if __name__ == "__main__":
main()
| true |
01e81b0156c5b47410ef48534c9adfbd1c055073 | simsalabimb/python_exercises | /list_ends.py | 418 | 4.15625 | 4 | '''
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new
list of only the first and last elements of the given list.
For practice, write this code inside a function.
'''
def main():
def grab_ends(a):
return print(a[0],a[-1])
#Get list of numbers from user input
a = [int(x) for x in input().split()]
grab_ends(a)
if __name__ == '__main__':
main() | true |
4ff8ee95d9098da1a5eb3b9f9aaff4ad0f54cd58 | simsalabimb/python_exercises | /reverse_word_order.py | 451 | 4.28125 | 4 | '''
Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order.
'''
def reverse_sentence(sentence):
phrase = sentence.split()
phrase.reverse()
return " ".join(phrase)
def main():
word = input("Give me a sentence to reverse: ")
result = reverse_sentence(word)
print(result)
if __name__ == '__main__':
main() | true |
1cc560c87581fd45943a526b1001685ece455e4b | kinseyreeves/Interview-Questions | /leet/lc_median_sorted.py | 821 | 4.1875 | 4 | """
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
"""
def arr_merge(a, b):
out = []
i = 0
j = 0
while i < len(a) and j < len(b):
if (a[i] < b[j]):
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
if i < len(a):
out += a[i:]
elif j < len(b):
out += b[j:]
return out
def get_med(arr):
if (len(arr) % 2 == 0):
val = (arr[int(len(arr) / 2) - 1] + arr[int(len(arr) / 2)]) / 2
else:
val = arr[int(len(arr) / 2)]
return val
print(get_med([1, 2, 3, 4, 5]))
print(arr_merge([1], [1, 5, 9, 10, 11]))
| true |
e02d644668cd8f11b963088c7769ed88ef830c69 | kinseyreeves/Interview-Questions | /binary_tree.py | 2,149 | 4.125 | 4 | """
Binary-tree implementation with different functionality.
for reference.
Kinsey Reeves
"""
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert_node(element, tree):
# print(tree.data)
if (element <= tree.data):
# print("less")
if (tree.left):
insert_node(element, tree.left)
else:
tree.left = Node(element)
else:
# print("right")
if (tree.right):
insert_node(element, tree.right)
else:
tree.right = Node(element)
def in_order_print_tree(tree):
if (tree):
in_order_print_tree(tree.left)
print(tree.data, end='')
in_order_print_tree(tree.right)
def create_tree(lst):
root = Node(lst[0])
for i in lst[1:]:
# print("inserted")
insert_node(i, root)
return root
def print_depth(tree):
print("tree depth: ")
print(_depth(tree))
def _depth(tree):
if (not tree):
return 0
if (_depth(tree.left) > _depth(tree.right)):
return _depth(tree.left) + 1
return _depth(tree.right) + 1
def size(tree):
if not tree:
return 0
else:
return size(tree.left) + size(tree.right) + 2
def is_balanced(tree):
if not tree:
return True
if abs(_depth(tree.left) - _depth(tree.right)) <= 1:
return is_balanced(tree.left) and is_balanced(tree.right)
return False
def print_levels(tree):
print('', end='')
open_set = set()
open_set.add(tree)
while len(open_set) > 0:
t = open_set.pop()
print(t.data, end=' ')
if (t.left):
open_set.add(t.left)
if (t.right):
open_set.add(t.right)
print('\n')
def print_structure(tree):
if (tree):
return f'[ {tree.data} ' + f'{print_structure(tree.left)} ' + f' {print_structure(tree.right)}]'
else:
return 'Nil'
t = create_tree([1, 2, 1, 4, 5, 2])
in_order_print_tree(t)
print('\n')
print_levels(t)
print_depth(t)
print(is_balanced(t))
print_levels(t)
# in_order_print_tree(t)
print(print_structure(t))
| true |
f273245bcf003609820d665c26252f14d985a76c | Pragati-Gawande/100-days-of-code | /Day_13/Kaggle Games Dataset.py | 1,876 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Pandas Lab Exercise
#
#
# ## Part - 1
# We shall now test your skills in using Pandas package. We will be using the [games Dataset](https://www.kaggle.com/gutsyrobot/games-data/data) from Kaggle.
#
# Answer each question asked below wrt the games dataset.
# ** Import pandas as pd.**
# In[1]:
import pandas as pd
# ** Read games.csv as a dataframe called games.**
# In[2]:
games = pd.read_csv("games.csv")
# ** Check the head of the DataFrame. **
# In[3]:
games.head()
# ** Use .info() method to find out total number of entries in dataset**
# In[4]:
games.info()
# **What is the mean playin time for all games put together ?**
# In[6]:
games['playingtime'].mean()
# ** What is the highest number of comments received for a game? **
# In[7]:
games['total_comments'].max()
# ** What is the name of the game with id 1500? **
# In[8]:
games[games['id']==1500]['name']
# ** And which year was it published? **
# In[9]:
games[games['id']==1500]['yearpublished']
# ** Which game has received highest number of comments? **
# In[10]:
games[games['total_comments']==games['total_comments'].max()]
# ** Which games have received least number of comments? **
# In[11]:
games[games['total_comments']==games['total_comments'].min()]
# ** What was the average minage of all games per game "type"? (boardgame & boardgameexpansion)**
# In[13]:
games.groupby('type').mean()['minage']
# ** How many unique games are there in the dataset? **
# In[14]:
games['id'].nunique()
# ** How many boardgames and boardgameexpansions are there in the dataset? **
# In[15]:
games['type'].value_counts()
# ** Is there a correlation between playing time and total comments for the games? - Use the .corr() function **
# In[18]:
games[['playingtime','total_comments']].corr()
# In[ ]:
| true |
d572b66bcfd482ccced82bf7f6e3f50059364423 | AshleyBrooks213/Unit3Sprint2 | /SprintChallenge/demo_data.py | 1,726 | 4.25 | 4 | """Sprint Challenge for Unit 3 - Sprint 2 - SQL Queries"""
import sqlite3
"""Create connection to new database"""
conn = sqlite3.connect("demo_data.sqlite3")
print("Connection Successful")
"""Instantiate cursor"""
curs = conn.cursor()
print("Cursor Successful")
"""Create Table Statement"""
CREATE_TABLE_QUERY = """
CREATE TABLE IF NOT EXISTS demo (
s VARCHAR(5),
x INT,
y INT
);
"""
"""Execute Create Table Statement"""
curs.execute(CREATE_TABLE_QUERY)
"""Commit new table on the connection"""
conn.commit()
print("Table Successfully Created!!!")
"""Get Data - Should always be a list of tuples"""
data = (('g', 3, 9),
('v', 5, 7),
('f', 8, 7))
"""Insert data into table"""
INSERT_ROWS_INTO_DEMO = """
INSERT INTO demo(s, x, y)
VALUES (?, ?, ?);
"""
for row in data:
curs.execute(INSERT_ROWS_INTO_DEMO, row)
"""Commit inserted data on the connection"""
conn.commit()
print("Data Successfully Inserted!")
"""PART 1 SQL QUERIES"""
"""How many rows are there? - It should be 3!"""
row_count = """
SELECT COUNT(*)
FROM demo;
"""
"""Execute First Query"""
response = curs.execute(row_count).fetchall()
print(response)
"""How many rows are there where both x and y are at least 5?"""
xy_at_least_5 = """
SELECT COUNT(*)
FROM demo
WHERE x > 4 AND y > 4;
"""
"""Execute Second Query"""
response2 = curs.execute(xy_at_least_5).fetchall()
print(response2)
"""How many unique values of y are there?"""
unique_y = """
SELECT COUNT(DISTINCT(y))
FROM demo;
"""
"""Execute Third Query"""
response3 = curs.execute(unique_y).fetchall()
print(response3)
"""Close cursor"""
curs.close()
| true |
b24131970fffdeb8af7bf1a156a753417c7f2a2e | TangentialDevelopment/Web-Development-Projects | /MI 250/programs/existing programs before week 13/week 1.py | 2,513 | 4.53125 | 5 | #project 1
#1. The listing in problem 2.29 defines a function. Modify this function to take as parameters the height (in stories), the feet per story, and the gravity (in meters).
#Verify that your function gives different answers for different parameter values, and the same answer for the values in the original listing.
#2. Create a new function that converts the number of feet to the number of meters. It should take the number of feet as a parameter. The function should print the number of meters.
#3. Look up the equation for the volume of a sphere. Write a function that prints out the volume of the earth in miles.
#4. Look up the conversion to convert miles to kilometers. Write a function that takes a diameter of a sphere (in miles) and prints out the volume of that sphere in kilometers.
import math
def compute(): #1
#base data
#heightInStories = 3
#feetPerStory = 10
#gravityMeters = 9.81
#correct answer: 1.36536448741
heightInStories = input("enter height in stories: ")
feetPerStory = input("enter feet per story: ")
heightInFeet = heightInStories * feetPerStory
metersPerFoot = 0.3048
heightInMeters = heightInFeet * metersPerFoot
gravityMeters = input("enter gravity (in meters): ")
timeToFall = sqrt((2*heightInMeters)/gravityMeters)
print("time to fall (second)s:")
print(timeToFall)
#test data
#1 feet = 0.3048 meters
#15 feet = 4.572 meters
#12.4 feet = 3.77952 meters
def convert(): #2
feet = input("enter distance in feet: ")
conversionFactor = 0.3048
meterConversion = feet * conversionFactor
print("Meters after conversion:")
print(meterConversion)
#test data
#radius = 3959
#volume = ~260,000,000,000
def findEarthVolume(): #3
radius = input("enter radius of Earth in miles: ")
volume = float(4) / 3 * math.pi * radius ** 3
print ("volume of earth in cubic miles: ")
print(volume)
#test data
#1 mile = ~2.18243862694 kilometers^3
#15 mile = ~7365.73036591 kilometer^3
#6.2 mile = 520.136233081 kilometer^3
#conversion 1 mile to 1.60934 km
def convertToFindVolume(): #4
diameter = float(input("enter radius of Earth in miles: "))
diameterConverted = diameter * 1.60934
print(diameterConverted)
radius = diameterConverted / 2
print(radius)
volume = float(4) / 3 * math.pi * radius ** 3
print ("volume in cubic kilometers: ")
print(volume)
#def main(): for testing purposes
#compute()
#convert()
#findEarthVolume()
#convertToFindVolume()
#main() | true |
48b3f3f7984f81496177d99d3b27d4e4ed69549d | PROTECO/pythonJunio18 | /Básico/Martes/Tipos de datos/diccionarios.py | 1,066 | 4.15625 | 4 | # -*- coding: utf-8 -*-
############################
# Tipo de dato diccionario
############################
#Formato del diccionario diccionario={llave:valor}
#LLave debe ser inmutable, y valor puede ser cualquiera1
diccionario={"Jorge":"1234","Julio":1765675,"Gali":2543,"Luis":True,"Aldo":[1,2,4]}
print("La contraseña de Jorge es: ",diccionario["Jorge"])
print("La contraseña de Julio es: ",diccionario["Julio"])
print("La contraseña de Gali es: ",diccionario["Gali"])
print("La contraseña de Aldo es: ",diccionario["Aldo"])
calificaciones={"Jorge":10,"Gali":9,"Aldo":6,"Julio":8,"Luis":"NP"}
print("Calificación de Jorge: ", calificaciones["Jorge"])
print("Calificación de Jorge: ",calificaciones.get("Jorge"))
#Modificar un valor
calificaciones["Jorge"]=8
print("Calificación de Jorge: ", calificaciones["Jorge"])
#El método values me devuelve los valores de todas las llaves del diccionario
print(calificaciones.values())
#El método ítems me devuelve un diccionario que contiene en tuplas la llave y el valor
print(calificaciones.items())
| false |
e85c8e8d2dcd8ad2d946c338ba50aa8b6695b541 | koolhead17/python-learning | /while.py | 310 | 4.375 | 4 | print("Playing with while loop")
print("###### starting while loop #######")
num = 0
while num < 3:
print("The value of the number is: " + str(num))
print("The number is inside while loop")
num = num + 1
print(" ######## ending While loop ##########")
print("The loop gets over as num > 3")
| true |
1ada4100cbd15ea075c5de5bae5a002621a07a01 | koolhead17/python-learning | /string_inrevrse.py | 300 | 4.15625 | 4 | alphabet = input('enter a string and we will reverseit for you:' )
print('you have entered: ', alphabet, sep=' ')
print('lenght of string','is: ', len(alphabet), sep=' ' )
rev_alphabet = alphabet[-1:-(len(alphabet)+1):-1]
print('the revese of string you have typed is: ', rev_alphabet, sep=' ')
| true |
924886af28f7c8e59f703e377a39cb5277c341e0 | koolhead17/python-learning | /nested-elif.py | 451 | 4.25 | 4 | age = int(input("Please enter your age: "))
if age > 18:
print("Your age is " + str(age) + " years, you are eligible to vote.")
elif age == 17:
print("Your age is " + str(age) + " years, you have to wait for one more year for voting.")
elif age == 18:
print("Your age is " + str(age) + " years, you are a first time voter. Vote wisely")
else:
print("Your age is " + str(age) + " years, you are eligible to vote.")
| false |
967c4197643112c9e5087efa150d2db0cdd642e7 | pratik-kurwalkar/Python-Playground | /03_Arithmatic.py | 214 | 4.125 | 4 | #Arithmatic
import math
print(10 / 3)#returns float value
print(10//3)
print(10%3)
print(10*3)
print(10**3)#prints 10 to power of 3
val = 2.97
print(str(round(val))+' '+str(math.floor(val)))
#read documentation
| true |
4b1be7125f1969ed4ec29d9707069df12e6966ef | acenturione/LPTHW | /ex6.py | 1,145 | 4.59375 | 5 | # Learn Python the Hard Way Exercise 6
# defines x variable as string with an int inserted into the string
x = "There are %d types of people." % 10
# defines a binary variable
binary = "binary"
# defines do_not as a string vairable
do_not = "don't"
# defines y as a string with two other strings inserted as format charactors
y = "Those who know %s and those who %s." % (binary, do_not)
# print variable x
print x
# print variable y
print y
# print string with x variable inserted, which is another string
print "I said: %r." % x
# print string with y variable inserted, which is another string
print "I also said: '%s'." % y
# defines hilarious varable as boolean, False.
hilarious = False
# defines joke_evaluation varable as a string with a format character instered in the end
joke_evaluation = "Isn't that joke so funny?! %r"
# prints the joke_evaluation varable and names the inserted character
print joke_evaluation % hilarious
# defines w variable as a string
w = "This is the left side of..."
# defines e variable as a string
e = "a string with a right side."
# prints string variable w and e joined together.
print w + e
| true |
a82e00fc463728a3587febe7cbb38e6070bda9d1 | artykreaper/intro-python-code | /bouncing balls.py | 1,463 | 4.21875 | 4 | # Animated bouncing balls
# KidsCanCode - Intro to Programming
from tkinter import *
import random
import time
# Define ball properties and functions
class Ball:
def __init__(self, canvas, color, size):
self.canvas = canvas
self.id = canvas.create_oval(10,10,size,size, fill=color)
self.canvas.move(self.id, 245, 100)
self.yspeed = -1
self.xspeed = random.randrange(-3, 3)
def draw(self):
self.canvas.move(self.id, self.xspeed, self.yspeed)
pos = self.canvas.coords(self.id)
if pos[1] <= 0:
self.yspeed = random.randrange(1,10)
if pos[3] >= 400:
self.yspeed = random.randrange(-10,-1)
if pos[0] <= 0:
self.xspeed = random.randrange(1,10)
if pos[2] >= 500:
self.xspeed = random.randrange(-10,-1)
# Create window and canvas to draw on
tk = Tk()
tk.title("Game")
canvas = Canvas(tk, width=500, height=400, bd=0)
canvas.pack()
tk.update()
# Create a list of 20 balls, each with a random size and color
ball_list = []
color_list = ['blue', 'red', 'green', 'papaya whip', 'brown', 'lavender']
for i in range(20):
color = random.choice(color_list)
size = random.randrange(10, 100)
ball_list.append(Ball(canvas, color, size))
# Animation loop
while True:
# animate each ball in the list of balls
for ball in ball_list:
ball.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.01)
| true |
92c8cadc6f3e01f4ca015b4a0de6083250d5a1c2 | kamoniz/Year9Design01PythonKM | /MathExample.py | 432 | 4.34375 | 4 | a = input("input a number: ")
a = float(a)
b = input("input a number: ")
b = float(b)
#We can add two numberical values
c = a + b
print(c)
#We can subtract two numerical values
d = a - b
print(d)
#The abs function will take the absolute value of a - b
#This is useful because by doing this we don't care which
#is larger, we just get the difference.
e = abs(a - b)
print(e)
f = a * b
print(f)
g = a / b
print(g)
h = a //b
print(h) | true |
1fab5c99cfd40715c5d27d8405fc06ae60075a1d | cifpfbmoll/practica-4-python-juliajacaDAM | /pr4_ej1.py | 867 | 4.40625 | 4 | '''
Práctica 4. Ejercicio 1
Pida al usuario 5 números y diga cuál es el mayor y cuál el menor
'''
print('''
De los 5 números que introduzcas, yo te diré cuál es el mayor y cual el menor
--------------------------------------------------
''')
num_1 = float(input("Introduce el primer número \n"))
num_2 = float(input("Introduce el segundo número \n"))
num_3 = float(input("Introduce el tercer número \n"))
num_4 = float(input("Introduce el cuarto número \n"))
num_5 = float(input("Introduce el quinto número \n"))
lista_numeros = list() # también se puede lista_numeros = []
lista_numeros.append(num_1)
lista_numeros.append(num_2)
lista_numeros.append(num_3)
lista_numeros.append(num_4)
lista_numeros.append(num_5)
lista_numeros.sort()
print(f'''El menor número de los que has introducido es {lista_numeros[0]}
y el mayor es {lista_numeros[-1]}''')
| false |
61c4079d5a380f4d2fd4b53d0e3fc26c437ecc94 | Yalchin403/HackerRankExercises | /mediums/Extra_Long_Factorials.py | 973 | 4.34375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the extraLongFactorials function below.
def extraLongFactorials(n):
print(main(n))
factorial_cache = {}
def main(n):
if n in factorial_cache:
return factorial_cache[n]
if n == 1:
value = 1
else:
value = n * main(n-1)
factorial_cache[n] = value
return value
"""
I don't think this concept is much useful here, may be much effective
if we were to write fibonacci series with recursion, but I just wanted to
apply...
If you pay attention, I've used simple memoization concept here:
So, basically what I've done is caching each value of n-th factorial in the memory
and return it if it is already in cache, else calculate it with recursion to calculate
each value and save it in the dictionary so that we can use it whenever we need.
"""
if __name__ == '__main__':
n = int(input())
extraLongFactorials(n)
| true |
459e8f8e7381fa3c1cf598a45af835d53d469879 | createdbyjames/dev | /other/UCSC Classes/Python/tree_def.py | 2,480 | 4.65625 | 5 | #!/usr/bin/env python
"""
A Tree class, to make tree objects, and a Forest class.
The Forest class is a "container" class because it
contains the tree objects.
In UML (Unified Modeling Language), this container
relationship, which is very common, is pictured:
--------
| |
| Forest |
| |
--------
/ \
\ / A diamond means "has a".
| Forest has a Tree.
--------
| |
| Tree |
| |
--------
"""
import random
class Tree:
"""Instantiate: Tree(20) to make a tree 20 ft tall.
"""
def __init__(self, height):
self.height = height
def Print(self):
print "tree, %.1f feet tall" % (self.height)
class Forest:
"""Instantiate: Forest(size='medium')
if size == 'large', it will have 8 trees.
== 'medium', it will have 5 trees.
== 'small', it will have 2 trees.
"""
def __init__(self, size='medium'):
if size not in ("small", "medium", "large"):
raise ValueError, """Intantiate with:
Forest([size='medium']) where size can be 'small', 'medium',
or 'large', not '%s'.""" % size
self.size = size
self.number_of_trees = 8 if self.size == 'large' else 5 if self.size == 'medium' else 2
self.trees = [Tree(random.randrange(1,200))
for count in range(self.number_of_trees)]
def Print(self):
print "%s forest with %d trees:" % (self.size,
self.number_of_trees)
for tree in self.trees:
tree.Print()
print
def main():
for size in 'small', 'medium', 'large':
forest = Forest(size)
forest.Print()
try:
forest = Forest('huge')
except ValueError, info:
print info
if __name__ == '__main__':
main()
"""
$ tree_def.py
small forest with 2 trees:
tree, 157.0 feet tall
tree, 35.0 feet tall
medium forest with 5 trees:
tree, 22.0 feet tall
tree, 114.0 feet tall
tree, 12.0 feet tall
tree, 112.0 feet tall
tree, 129.0 feet tall
large forest with 8 trees:
tree, 102.0 feet tall
tree, 98.0 feet tall
tree, 113.0 feet tall
tree, 49.0 feet tall
tree, 185.0 feet tall
tree, 58.0 feet tall
tree, 130.0 feet tall
tree, 167.0 feet tall
Intantiate with:
Forest([size='medium']) where size can be 'small', 'medium', or 'large', not 'huge'.
$
"""
| true |
17e1d5e249fe6e20b62975cc62969493b887e455 | createdbyjames/dev | /other/UCSC Classes/Python/UCSC_Python/lab_13_Magic/lab13_2.py | 1,720 | 4.125 | 4 | #!/usr/bin/env python
"""
lab13_2.py Tree and Forest classes with __str__.
"""
import random
import sys
class Tree:
"""Instantiate: Tree(20) to make a tree 20 ft tall.
"""
def __init__(self, height):
self.height = height
def __str__(self):
return "tree, %.1f feet tall" % (self.height)
class Forest:
"""Instantiate: Forest(size="medium")
if size == "large", it will have 8 trees.
== "medium", it will have 5 trees.
== "small", it will have 2 trees.
"""
def __init__(self, size="medium"):
if size not in ("small", "medium", "large"):
raise ValueError, """Intantiate with: Forest([size="medium"]) where size can be "small", "medium", or "large", not "%s".""" % size
self.size = size
self.number_of_trees = 8 if self.size == "large" else 5 if self.size == "medium" else 2
self.trees = [Tree(random.randrange(1,200))
for count in range(self.number_of_trees)]
def __str__(self):
say = "%s forest with %d trees:" % (self.size,
self.number_of_trees)
say += ", ".join([str(t) for t in self.trees])
return say
def main():
forest = Forest("small")
print "printing:"
print "\t", forest
print "Format replacement:\n\t%s" % forest
print "And with str:\n\t" + str(forest)
if __name__ == "__main__":
main()
"""
$ lab13_2.py
printing:
small forest with 2 trees:tree, 172.0 feet tall, tree, 68.0 feet tall
Format replacement:
small forest with 2 trees:tree, 172.0 feet tall, tree, 68.0 feet tall
And with str:
small forest with 2 trees:tree, 172.0 feet tall, tree, 68.0 feet tall
$
"""
| true |
2a322a15088f6c8cd2546dd896534f249dd64039 | createdbyjames/dev | /other/UCSC Classes/Python/UCSC_Python/lab_06_Comprehensions/lab06_5.py | 1,948 | 4.25 | 4 | #!/usr/bin/env python
"""Provides CountVowels, a vowel counting function."""
import string
def CountVowels(phrase):
"""Returns the number of vowels in the "phrase" input.
'y' is not counted if it is the first character.
is not counted if it is preceded by a vowel.
is counted in 'ying' if it is at the end of the word.
is counted at the end of the word, if preceded by
a consonant.
is counted if it is preceded and followed by a
consonant.
"""
ALWAYS_VOWELS = "aeiou"
spurious = string.punctuation + '0123456789_'
count = 0
for word in phrase.lower().split():
word = word.strip(spurious)
l_word = len(word)
for index, char in enumerate(word):
if char in ALWAYS_VOWELS:
count += 1
continue
if char != 'y' or index == 0:
# now, char is 'y' and not the first char
continue
if word[index-1] in ALWAYS_VOWELS:
# preceded by a vowel
continue
if word.endswith('ying') and index == l_word - 4:
count += 1
continue
# now, it is a 'y' preceded by a consonant
if (index == l_word - 1 # at end of word
or word[index+1] not in ALWAYS_VOWELS):
# or followed by a consonant
count += 1
continue
return count
def main():
"""Tests the CountVowels function."""
for test in (
"""Math, science, history, unraveling the mysteries,
that all started with the big bang!""",
"boy way hey myth satyr fly flying spying",):
print CountVowels(test), test
if __name__ == "__main__":
main()
"""
$ lab06_5.py
24 Math, science, history, unraveling the mysteries,
that all started with the big bang!
11 boy way hey myth satyr fly flying spying
$ """
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.