blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f67dc059f382699180b17a1c9d2ca2708504f2db | AmazingCaddy/PythonCode | /exercise/MyOperator.py | 560 | 4.125 | 4 | #!/usr/bin/env python
#coding: utf-8
def Operator():
x = int(raw_input('Enter x: '))
y = int(raw_input('Enter y: '))
print 'x + y = ' + str(x + y)
print 'x - y = ' + str(x - y)
print 'x * y = ' + str(x * y)
print 'x / y = ' + str(x / y)
print 'x // y = ' + str(x // y)
print 'x % y = ' + str(x % y)
print 'x ** y = ' + str(x ** y)
print 'x & y = ' + str(x & y)
print 'x | y = ' + str(x | y)
print 'x ^ y = ' + str(x ^ y)
print '~x ~y = ' + str(~x) + ' ' + str(~y)
print 'not x = ' + str(not x)
if __name__ == '__main__':
Operator() | false |
83d5431831804d453b09cf5670061394685d3418 | TylerHJH/DataStructure | /lab1_e3.py | 762 | 4.34375 | 4 | """
Input:
First we have a empty list Hailstone.
n: Get a number n and put it into the list, then judge whether is even or odd.
If it's even, put n/2 into the list Hailstone, else put 3n+1 into the list.
Then continue to judge whether the calculated number n/2 or 3n+1 is odd or even and do the same operation as
before.
Output:
length: When the number becomes 1 finally, put 1 into the list and get the length of the list.
"""
Hailstone = []
n = int(input("Enter a number n of Hailstone(n):"))
n0 = n
Hailstone.append(n)
while n != 1:
if n % 2 == 0:
n = n/2
else:
n = 3 * n + 1
Hailstone.append(n)
length = len(Hailstone)
print("The length of Hailstone({}) is {}".format(n0, length))
| true |
a04385440109a511922a3d4b5c52973a1fe94eeb | biu9/cs61a | /lab01.py | 1,402 | 4.15625 | 4 | def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
total = 1
for i in range(n,n-k,-1):
total = total * n
n = n-1
return total
def sum_digits(y):
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> a = sum_digits(123) # make sure that you are using return rather than print
>>> a
6
"""
"*** YOUR CODE HERE ***"
sum = 0
while y>0:
sum = sum + y%10
y = int(y/10)
return sum
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR CODE HERE ***"
count = 0
flag = 0
while n>0:
digit = n%10
n = int(n/10)
if digit == 8:
count = count + 1
else:
count = 0
if count == 2:
flag = 1
return True
break
if flag == 0:
return False
| false |
57d5bbcba5804c546fe168de0c62bf3397c3836d | YOON93KYS/python_renshu | /basic/5-4-2/main2.py | 408 | 4.1875 | 4 | '''
5-4-2. 実践演習
1)5-3-2の関数(def)で定義したadd関数でnum_1とnum_2を足した値を返すように変更せよ
2)add関数に10,20を渡して戻り値を受け取り、出力せよ
(目標20分)
'''
'''
#2)add関数に10,20を渡して戻り値を受け取り、出力せよ
'''
def add_3(num_1, num_2):
return(num_1 + num_2)
print(add_3(10, 20))
| false |
053bbf84269b6a100eace6160769e4e370108201 | Muoleehs/Muoleeh | /Task_7.py | 673 | 4.15625 | 4 | import statistics
from array import *
# The * above implies the need to work with all array functions
arr = array ('I', [])
# 'I' represents a type code for unsigned/positive integers as the task demands
length = int(input("Enter the length of the array: "))
# This collects the number of integers expected in the array
for i in range(length):
x = int(input("Input Number: "))
arr.append(x)
# The code above collects the numbers to be in the array using a for-loop in the range of numbers collected in variable "z"
# The append function also inserts the numbers into the array
std = statistics.stdev(arr)
print("The standard deviation is ",std)
| true |
85afdfdc5b985e0ed5a51ad251690345e69d94bd | magatj/Job_And_Res_Parser | /Random_Word.py | 2,857 | 4.125 | 4 | import random
import pandas as pd
def rand_word():
'''Transform excel column and row files to a dictionary'''
word_list = []
q1 = input('What is the file location \n (file must only have on column with a header and values \n\
example: C:/Users/jesse/Desktop/Word_list.xlsx)')#'C:/Users/jesse/Desktop/Word_list.xlsx'
q1 = q1.replace('\\','/')
wb = pd.read_excel(q1) #workbook
df = pd.DataFrame.to_dict(wb)
word_inv = list(df.values())[0]
ini_inp = 'Generate Random Word?'
add = ''
while len(word_list) != len(word_inv):
inp = input(ini_inp + add).strip().upper()
if inp == 'Y':
total_words = len(word_inv)
rand_num = random.randrange(total_words)
random_word = word_inv[rand_num]
'''while random word is in the word_list keep generating new word'''
while random_word in word_list:
rand_num = random.randrange(total_words)
random_word = word_inv[rand_num]
continue
'''when random word not in word_list append word_list and print the word'''
if random_word not in word_list:
word_list.append(random_word)
print(random_word)
ini_inp = '' #removing initial input text
add = 'Generate Another One?'
'''when word_list has the same values as word_inv print print warning and ask if file wants to be saved'''
if len(word_list) == len(word_inv):
print('No More Words')
question = input('Do you want to save your list (Y | N)?').strip().upper()
'''If file to be saved, specify location and name on where it will be saved'''
if question == 'Y':
q = input('Provide folder path to save results: \n(example: C:\\Users\\user\\Desktop\)')
q = q.replace('\\','/')
q2 = input('Enter File Name').strip().upper()
new_dict = {'Word_List': [i for i in word_inv.values()]}
df = pd.DataFrame(new_dict)
df.to_excel(q+q2+'.xlsx', index =False, encoding='utf-8')
break
elif inp == 'N':
break
'''Update dictionary if user wants to add new word'''
elif inp == 'ADD':
key = len(word_inv)+1
value = input('what word you want to add?')
word_inv.update({key:value})
add = 'Generate Another One'
else:
print('Select Y | N | ADD')
if __name__ == "__main__":
rand_word() | true |
d80e96637b85bc4db58a814e19d7f2724efdded7 | se7enis/learn-python | /webapp/cgi-bin/createDBtables.py | 682 | 4.15625 | 4 | import sqlite3
connection = sqlite3.connect('coachdata.sqlite') # establish a connection to a database; this disk file is used to hold the database and its tables
cursor = connection.cursor() # create a cursor to the data
cursor.execute("""CREATE TABLE athletes(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
name TEXT NOT NULL,
dob DATE NOT NULL
)""")
cursor.execute("""CREATE TABLE timing_data(
athlete_id INTEGER NOT NULL,
value TEXT NOT NULL,
FOREIGN KEY (athlete_id) REFERENCES athletes
)""")
connection.commit() # commit any changes, making them permanent
connection.close() # close your connection when you're finished
| true |
be349070298d6a455ad7b1613d2eee5f1dbfe3a5 | Ubagaly/lessons_py | /Lessons 1/zadacha1.py | 396 | 4.125 | 4 | # Решение 1 задания
name=input("Введите Ваше имя:")
surname=input("Введите Вашу фамилию:")
age=int(input("Cколько Вам лет?:"))
c=int(input("Введите любое целое число:"))
print (f"{name} {surname} в данный момент Вам: {age} ")
age_c=age+c
print (f"Через {c} лет Вам будет: {age_c} ")
| false |
5d52ea7ca0578936a860b55dc5e14396e09272b9 | kas/ctci | /02-linked-lists/07.py | 681 | 4.21875 | 4 | # implement a function to check if a linked list is a palindrome
from doublylinkedlist import DoublyLinkedList
def palindrome(doubly):
palindrome = False
s = ''
itr_nd = doubly.head
while itr_nd:
s += str(itr_nd.data)
itr_nd = itr_nd.next_node
if s[::-1] == s:
palindrome = True
return palindrome
doubly = DoublyLinkedList()
doubly.append('k')
doubly.append('a')
doubly.append('y')
doubly.append('a')
doubly.append('k')
doubly.print()
print(palindrome(doubly))
doubly = DoublyLinkedList()
doubly.append('c')
doubly.append('a')
doubly.append('n')
doubly.append('o')
doubly.append('e')
doubly.print()
print(palindrome(doubly)) | false |
b6600be05f7aaab0b30065fdd8efefb6897181e4 | sujay-dsa/ISLR-solutions-python | /Chapter-2-Intro-to-statistical-learning.py | 1,707 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 20 22:28:35 2018
Here I try to map the commands specified in R to
the python equivalent. All commands are as mentioned
in ISLR chapter 2.
@author: Sujay
"""
# Basic Commands
# creating a vector (python equivalent is list)
x=[1,2,3,4]
y = [1,4,3,7]
type(x)
# Finding the length
# R command : length (x)
len(x)
# adding two lists
# R command: x+y
# In python plain x+y will concatenate the two lists.
# So numpy arrays make it easier.
import numpy as np
np.array(x) + np.array(y)
# Creating a matrix
# R command : x=matrix (data=c(1,2,3,4) , nrow=2, ncol =2)
# R reads this data column wise so we need to specify the order explicitly
x_2 = np.array([1,2,3,4]).reshape((2,2),order="F")
# matrix (c(1,2,3,4) ,2,2,byrow =TRUE)
np.array([1,2,3,4]).reshape((2,2))
# R command : sqrt(x)
# R command : x^2
np.sqrt(x)
np.sqrt(x_2)
np.square(x_2)
# R command: rnorm(50)
np.random.randn(50)
# R command : y= x + rnorm(50, mean = 50, sd= 0.1)
# cor(x,y)
x= np.random.randn(50)
y= x + (0.1*np.random.randn(50) + 50)
np.corrcoef(y,x)
##### Graphics ########################
# x= rnorm(100)
# y= rnorm(100)
# plot (x, y)
# plot(x,y,xlab=" this is the x-axis",ylab=" this is the y-axis",
# main=" Plot of X vs Y")
import matplotlib.pyplot as plt
x = np.random.randn(50)
y = np.random.randn(50)
plt.scatter(x,y)
############ Indexing data ###################
# A=matrix (1:16 ,4 ,4)
# A[2,3]
A = np.array([list(range(1,17))]).reshape((4,4), order="F") # gotta give last number +1
A[1,2] # python indexing starts from 0
# A[c(1,3) ,c(2,4) ]
# A[-c(1,3),]
A[np.ix_([0,2],[1,3])]
A[np.ix_(range(3),range(1,4))]
np.delete(A, [0,2], axis=0)
| true |
3a30077f0f59df38612411201149dad154069646 | Zerl1990/2020_python_workshop | /12_lists.py | 385 | 4.25 | 4 | # A list can contain values of different types
my_list = ["Hello", "Hi", 10, False]
# Print values in list
print(f'This is my list: {my_list}')
print(f'First Value: {my_list[0]}')
print(f'Second Value: {my_list[1]}')
print(f'Third Value: {my_list[2]}')
print(f'Fourth Value: {my_list[3]}')
# Add extra value
my_list.append("extra value")
print(f'List after adding value {my_list}')
| true |
707ddc672d67b78308356f7a14e85973d414ad6a | Zerl1990/2020_python_workshop | /11_tuples.py | 293 | 4.125 | 4 | # A tuple can contain values of different types
tuples = ("Hello", "Hi", 10, False)
# Print tuple information
print(f'This is my tuple: {tuples}')
print(f'First Value: {tuples[0]}')
print(f'Second Value: {tuples[1]}')
print(f'Third Value: {tuples[2]}')
print(f'Fourth Value: {tuples[3]}')
| false |
dcdfb53769710b6345d2363183167b1adb075ffa | joelcede/programming_languages | /python3/BitCounting.py | 718 | 4.25 | 4 | '''
Write a function that takes an integer as input,
and returns the number of bits that are equal to one in the binary
representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010,
so the function should return 5 in this case.
'''
def count_binary_number():
number = int(input('Write a number: '))
convert_binary = bin(number)
if number < 0:
return count_binary_number()
else:
result_binary = convert_binary[2::]
counts_ones = result_binary.count('1')
print("The binary representation of {} is: {}, Count Ones: {}"
.format(number,result_binary,counts_ones))
count_binary_number()
| true |
7ddf9b6a3da88ae4dde1a83da6425d387f8fe6c4 | AnasBrital98/Regression-analysis | /Linear_Regression_Using_Least_square_Method.py | 1,076 | 4.21875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
x , y = make_regression(n_samples=100 , n_features= 1 , noise=10)
"""
Our Linear Model Looks like this : Y_estimated = theta[0] + theta[1] * x .
our goal is to compute the coefficients Theta[0] and Theta[1] that will fit our data correctly,
Using Least Square Method .
"""
# Calculating The Mean for x and y
X_mean = np.mean(x)
Y_mean = np.mean(y)
# Calculating The Coefficient Theta_1
num = np.sum( (x[i] - X_mean)*(y[i] - Y_mean) for i in range(len(x)) )
den = np.sum( (x[i] - X_mean)**2 for i in range(len(x)) )
theta_1 = num / den
# Calculating The Coefficient Theta_0
theta_0 = Y_mean - theta_1 * X_mean
# Calculating The Estimated Y
Y_estimated = theta_0 + theta_1 * x
# Plot The Result
plt.figure()
plt.scatter(x , y , color='blue')
plt.plot(x , Y_estimated ,"-r" ,label = 'Estimated Value' )
plt.xlabel('Independent Variable')
plt.xlabel('dependent Variable')
plt.title('Linear Regression Using Least Square Method')
plt.legend(loc = 'lower right')
plt.show()
| false |
f36c3605339edeea69b4c8b982fe343a9378e85d | Praful-Prasad/COMPLETED | /COMPLETED/ex1/13. Fibonacci.py | 235 | 4.28125 | 4 |
n=int(input('Enter a number : '))
print("Fibonacci series till n = ")
sum2=0
sum=1
print(0,end=" ")
print(1, end =" ")
for i in range(0,n+1):
sum3=sum+sum2
sum2=sum
sum=sum3
print(sum,end= " ")
| false |
02760cdd7504f5ea11125f313bbe196469866d76 | chyld/berkeley-cs61a | /misc/lab01/lab01_extra.py | 663 | 4.25 | 4 | from functools import reduce
"""Coding practice for Lab 1."""
# While Loops
def factors(n):
"""Prints out all of the numbers that divide `n` evenly.
>>> factors(20)
20
10
5
4
2
1
"""
"*** YOUR CODE HERE ***"
nums = [x for x in range(1, n+1) if not(n%x)]
nums.sort()
return nums
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 0)
1
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
"""
"*** YOUR CODE HERE ***"
return reduce(lambda acc, val: acc * val, range(n-k+1, n+1), 1)
| true |
236385c58e9fd1f164336b632cee97ceab94f215 | sameervirani/week-1-assignments | /fizzbuzz.py | 367 | 4.28125 | 4 | #Take input from the user. If the input is divisible by 3 then print "Fizz",
#if the input it divisible by 5 then print "Buzz".
#If the input is divisible by 3 and 5 then print "Fizz Buzz".
user1 = int(input("Enter number: "))
if user1 % 3 == 0 and user1 % 5 == 0:
print("Fizz Buzz")
elif user1 % 3 == 0:
print("Fizz")
elif user1 % 5 == 0:
print("Buzz")
| true |
1b5a6eca3df1fa66ecf3d3b56b2e41f273af07a5 | Nabdi22/TTA | /DFD-Code.py | 598 | 4.125 | 4 | print("Hello Welcome to Nafisa's Shoe Shop")
shoe_size = int(input("Please enter your shoe size: "))
if shoe_size > 6:
print("You will need to shop from the Adult Section")
else:
print("You will need to shop from the Junior Section")
print("Please choose from our three different brands which are Nike, Addidas or Vans")
Brand = input("Which Shoe Brand would you like to buy: Nike, Addidas and Vans: ")
beg_sen = "You are a "
print(beg_sen + str(shoe_size) + " and have ordered "+ Brand + ".")
print("We have your order, Thank you for shopping at Nafisa's Shoe Shop")
| true |
e1284e6ec7edccbd7e16479288c8b9a48ecc4dc0 | lakshyarawal/pythonPractice | /Mathematics/computing_power.py | 875 | 4.15625 | 4 | """ Computing Power: Find x raised to the power y efficiently """
import math
""" Naive Solution: """
def comp_power(a, b) -> int:
power_result = 1
if b == 0:
return power_result
for i in range(b):
power_result = power_result * a
return power_result
""" Efficient Solution: Divide the power into smaller factors by diving into 2 and then multiply """
def comp_power_eff(a, b) -> int:
if b == 0:
return 1
temp = comp_power_eff(a, b // 2)
temp = temp * temp
if b % 2 == 0:
return temp
else:
return temp*a
def main():
val1 = int(input("Enter your value: "))
val2 = int(input("Enter another value: "))
ans = comp_power(val1, val2)
ans2 = comp_power_eff(val1, val2)
print(ans)
print(ans2)
# Using the special variable
# __name__
if __name__ == "__main__":
main()
| true |
4125cc5cddbea0f79f8b4ab1312c78eeb8493274 | dvanduzer/advent-of-code-2020 | /day2-2.py | 1,295 | 4.1875 | 4 | """
For example, suppose you have the following list:
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.
In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies.
How many passwords are valid according to their policies?
"""
passblob = """
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
"""
with open('input_day2') as f:
passblob = f.read()
passlist = passblob.split('\n')
valid_count = 0
for line in passlist:
kv = line.split(': ')
if len(kv) != 2:
continue
pw = list(kv[1])
rule = kv[0].split(' ')
if len(rule) != 2:
continue
char = rule[1]
pos = rule[0].split('-')
if len(pos) != 2:
continue
first = int(pos[0]) - 1
second = int(pos[1]) - 1
if (pw[first] == char) ^ (pw[second] == char): # XOR
valid_count += 1
print(valid_count)
| true |
ed0443b6c95d9ec77dafc2dfdd66e0a86a5ed180 | DvorahC/Practice_Python | /exercice2_easy.py | 723 | 4.15625 | 4 | """
Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year that they will turn 100 years old.
Extras:
Add: asking the user for another number and printing out that many copies of the previous message.
(Hint: order of operations exists in Python)
Print out that many copies of the previous message on separate lines.
(Hint: the string "\n is the same as pressing the ENTER button)
"""
name = input('What is your name? ')
age = int(input('How old are you? '))
print(f'Hello {name}, in {(100 - age)+ 2014} you will be 100 years old!')
new_number = int(input('Enter a second number please: '))
for n in range(0, new_number):
print('WHAOU \n') | true |
f7c25cf743a72a8029f30f5ea059efbc67c7cdc2 | jeremyt0/Practice-Tasks | /reverse.py | 560 | 4.4375 | 4 |
task = """In python, you have a list of values n elements long called value_list.
Create a second list that is the reverse of the first, starting at the last element,
and counting down to the first."""
def reverseList(list1):
newlist = []
n=0
while n<len(list1):
newlist.append(list1[len(list1)-1])
list1.pop(len(list1)-1)
return newlist
def main():
print("Hello reverse py")
value_list = []
n = 12
for a in range(n):
value_list.append(a)
x = reverseList(value_list)
print(x)
if __name__=="__main__":
main() | true |
4ad39a656ac13778c9f38d91e6cc475336d94863 | sasikrishna/python-programs | /com/ds/Stack.py | 1,085 | 4.125 | 4 | class Stack:
""""
Stack implementation in python.
"""
def __init__(self):
self.stack = [];
self.top = -1;
def push(self, value):
self.stack.append(value);
self.top += 1;
return True;
def peek(self):
if self.top == -1:
return;
return self.stack[self.top];
def pop(self):
if self.top == -1:
return;
ele = self.stack[self.top];
self.stack.pop(self.top);
self.top -= 1;
return ele;
def print_stack(self):
print(self.stack)
if __name__ == '__main__':
stack = Stack()
stack.push(5)
stack.push(4)
stack.push(3)
stack.print_stack()
print('Element at top is ', stack.pop());
stack.print_stack()
print('Element at top is ', stack.pop());
stack.print_stack()
stack.push(1)
stack.print_stack()
print('Element at top is ', stack.pop());
print('Element at top is ', stack.pop());
print('Element at top is ', '- OOPS Stack is empty' if stack.peek() == None else stack.pop());
| false |
cb5993d7038d87f1d89a16986304b04eed125b58 | Amirpatel89/CS-Fundamentals | /Day1/Bubblesort.py | 343 | 4.15625 | 4 | array = [5, 3, 2, 4, 1]
def bubble_sarray(list) =
swapped = True;
while swapped == True:
while swapped: False
for i in range(len(a) - 1):
if list[i]>list[i+1]:
temp = list[i]
list[i] = list[i+1]
list[i+1] = temp
bubbleSort(list)
print sorted_array:
| true |
fb5d104195bc067404b8b128105e5762497b73d9 | joannaluciana/Python-OOP- | /oop/day2/hwday2/6 he lambda.py | 1,080 | 4.5 | 4 | #6. Write a Python program to square and cube
# every number in a given list
# of integers using Lambda. Go to the editor
#Click me to see the sample solution
items = [1, 2, 3, 4, 5]
squared = list (map(lambda x: x**2, items))
print(squared)
#13 Write a Python program to count the even, odd numbers in
#a given array of integers using Lambda. Go to the editor
#Click me to see the sample solution
items = [3,3,3,3,8,8,8,9,13,26,19,38]
even= list(filter(lambda x: x%2==0, items))
odd= list(filter(lambda x: x%2!=0, items))
print(f"number of even numbers is: {len(even)} and odd numbers is: {len(odd)}")
#17. Write a Python program to find numbers divisible by
#nineteen or thirteen from a list of numbers using Lambda. Go to the editor
#Click me to see the sample solution
number_19 = list(filter(lambda x: x%19==0 or x%13==0, items))
print(number_19)
#18. Write a Python program to find palindromes in a given list of strings using Lambda
items= ["assa","kaja","kajak","lool"]
palindr=list(filter(lambda word: word==word[::-1], items))
print(palindr)
| true |
968b2b4e002d1fae4de0d40a9efd38e34e32c58d | jmontara/become | /Recursion/recursion_start.py | 693 | 4.40625 | 4 | # recursive implementations of power and functions
def power(num,pwr):
""" gives number to the power
inputs:
num - int, number
pwr - int, power
outputs:
ret - int, number to the power
"""
if pwr == 0:
return 1
else:
return num * power(num, pwr - 1)
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num-1)
num = 3
pwr = 3
print num, "to the power of ", pwr, " = ", power(num,pwr)
print num, "factorial = ", factorial(num)
num = 4
print num, "to the power of ", pwr, " = ", power(num,pwr)
print num, "factorial = ", factorial(num)
num = 0
print num, "to the power of ", pwr, " = ", power(num,pwr)
print num, "factorial = ", factorial(num) | true |
f7e90d0db53004d861dba2c1e87bda1a52f80930 | muskanmahajan37/learn-em-all | /learnemall/datasets/iris.py | 2,069 | 4.1875 | 4 | ## Core Functionality to Load in Datasets
import numpy as np
import pathlib
from sklearn.model_selection import train_test_split
def load_data(split=False,ratio=None,path='./data/iris.csv'): ## generalized function to load data
"""
Loads in data from ./data/dataset.csv
Parameters:
=====================================
1) dataset : takes in name of dataset to be loaded as input for eg. (dataset=iris)
2) split : split the data in train and test datsets
3) ratio : ratio with which train and testing dataset need to be split. By default 80/20 (trian/test) ratio
Returns:
======================================
Returns a Dict. which contains:
1) X : A 2-D numpy array representing our Dataset, with each row corresponding to a new entry
and each column corresponding to diffrent features
2) y : A numpy array with corresponding classes that each row represents
3) X_train : In case of split it represents data that will be used in for training
4) X_test : In case of split it represents data that will be used for testing purposes
5) y_train : Corresponding classes of each row in training data
6) y_test : Corresponding classes of each row in testing data
7) class_names : Name of classes of the given dataset
8) features : Feature set of given dataset
"""
if not pathlib.Path(path): ## if data is not available
print('This Dataset is currently not supported. Please download via external source')
return
## load in the data
data = np.genfromtxt(path,delimiter=',')
X,y = data[:,:-1],data[:,-1] ## set in our X and y variables
if not split:
return X,y
else:
X_train,X_test,y_train,y_test = train_test_split(X,y,train_size=ratio,random_state=0,shuffle=True,stratify=y)
return X_train,X_test,y_train,y_test
def class_names():
return ['Iris-setosa','Iris-versicolor','Iris-virginica']
def features():
return ['Sepal Length', 'Sepal Width', 'Petal Length' , 'Petal Width'] | true |
66fcb60cbdb27745ab8e04b104c226b1b37a1889 | congsonag/udacity-data-structures-algorithms-python | /list-based collections/Queue.py | 1,883 | 4.34375 | 4 | """Make a Queue class using a list!
Hint: You can use any Python list method
you'd like! Try to write each one in as
few lines as possible.
Make sure you pass the test cases too!"""
class Element:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, head=None):
if type(head) == type(1):
self.head = Element(1)
else:
self.head = head
def insert_start(self, new_value):
new_element = Element(new_value)
new_element.next = self.head
self.head = new_element
def insert_end(self, new_value):
new_element = Element(new_value)
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def delete_start(self):
if self.head:
temp = self.head.value
self.head = self.head.next
return temp
def delete_end(self):
if self.head.next:
current = self.head
while current.next.next:
current = current.next
current.next = None
elif self.head:
self.head = None
class Queue:
def __init__(self, head=None):
self.storage = LinkedList(head)
def enqueue(self, new_value):
self.storage.insert_end(new_value)
def peek(self):
return self.storage.head.value
def dequeue(self):
return self.storage.delete_start()
# Setup
q = Queue(1)
q.enqueue(2)
q.enqueue(3)
# Test peek
# Should be 1
print(q.peek())
# Test dequeue
# Should be 1
print(q.dequeue())
# Test enqueue
q.enqueue(4)
# Should be 2
print(q.dequeue())
# Should be 3
print(q.dequeue())
# Should be 4
print(q.dequeue())
q.enqueue(5)
# Should be 5
print(q.peek())
| true |
9252f3ade60fe56615ae4d47bc1325b009fc0782 | Tsedao/Structure_and_Interpretation_of_Computer_Programs | /lab/lab04/lab04.py | 2,583 | 4.1875 | 4 | # Q2
def if_this_not_that(i_list, this):
"""Define a function which takes a list of integers `i_list` and an integer
`this`. For each element in `i_list`, print the element if it is larger
than `this`; otherwise, print the word "that".
>>> original_list = [1, 2, 3, 4, 5]
>>> if_this_not_that(original_list, 3)
that
that
that
4
5
"""
"*** YOUR CODE HERE ***"
for i in range (0, len(i_list)):
if i_list[i] <= this:
print ('that')
else:
print (i_list[i])
# Q4
def coords(fn, seq, lower, upper):
"""
>>> seq = [-4, -2, 0, 1, 3]
>>> fn = lambda x: x**2
>>> coords(fn, seq, 1, 9)
[[-2, 4], [1, 1], [3, 9]]
"""
"*** YOUR CODE HERE ***"
return [[i,fn(i)] for i in seq if lower <= fn(i) <= upper]
# Q5
def make_city(name, lat, lon):
"""
>>> city = make_city('Berkeley', 0, 1)
>>> get_name(city)
'Berkeley'
>>> get_lat(city)
0
>>> get_lon(city)
1
"""
return [name, lat, lon]
def get_name(city):
"""
>>> city = make_city('Berkeley', 0, 1)
>>> get_name(city)
'Berkeley'
"""
return city[0]
def get_lat(city):
"""
>>> city = make_city('Berkeley', 0, 1)
>>> get_lat(city)
0
"""
return city[1]
def get_lon(city):
"""
>>> city = make_city('Berkeley', 0, 1)
>>> get_lon(city)
1
"""
return city[2]
from math import sqrt
def distance(city1, city2):
"""
>>> city1 = make_city('city1', 0, 1)
>>> city2 = make_city('city2', 0, 2)
>>> distance(city1, city2)
1.0
>>> city3 = make_city('city3', 6.5, 12)
>>> city4 = make_city('city4', 2.5, 15)
>>> distance(city3, city4)
5.0
"""
"*** YOUR CODE HERE ***"
return sqrt((get_lat(city1) - get_lat(city2)) ** 2 + (get_lon(city1) - get_lon(city2)) ** 2)
# Q6
def closer_city(lat, lon, city1, city2):
"""
Returns the name of either city1 or city2, whichever is closest to
coordinate (lat, lon).
>>> berkeley = make_city('Berkeley', 37.87, 112.26)
>>> stanford = make_city('Stanford', 34.05, 118.25)
>>> closer_city(38.33, 121.44, berkeley, stanford)
'Stanford'
>>> bucharest = make_city('Bucharest', 44.43, 26.10)
>>> vienna = make_city('Vienna', 48.20, 16.37)
>>> closer_city(41.29, 174.78, bucharest, vienna)
'Bucharest'
"""
"*** YOUR CODE HERE ***"
city3 = make_city('city3', lat, lon)
if distance(city1, city3) < distance(city2, city3):
return get_name(city1)
else:
return get_name(city2)
| false |
3d659dc37006707dad08aedbde8b2f9df9437e09 | bnmcintyre/biosystems-analytics-2020 | /extra/01_dna/dna.py | 1,670 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Author : bnmcintyre
Date : 2020-02-04
Purpose: count the frequency of the nucleotides in a given piece of DNA
"""
import argparse
import os
import sys
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='get dna',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('dnaseq',
metavar='str',
help='DNA Sequence')
return parser.parse_args()
#---------------------------------------------------
def count_nucs(args):
dnaseq = args.dnaseq
acount = 0
tcount = 0
ccount = 0
gcount = 0
for i in range(len(dnaseq)):
if dnaseq[i].lower() == 'a':
acount = acount + 1
elif dnaseq[i].lower() == 't':
tcount = tcount + 1
elif dnaseq[i].lower() == 'c':
ccount = ccount + 1
elif dnaseq[i].lower() == 'g':
gcount = gcount + 1
print(f'{acount} {ccount} {gcount} {tcount}')
apercent = int((acount/len(dnaseq)) * 100)
tpercent = int((tcount/len(dnaseq)) * 100)
cpercent = int((ccount/len(dnaseq)) * 100)
gpercent = int((gcount/len(dnaseq)) * 100)
print(f'Percent A: {apercent}, '
f'Percent T: {tpercent}, '
f'Percent C: {cpercent}, '
f'Percet{gcount}')
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
count_nucs(args)
# --------------------------------------------------
if __name__ == '__main__':
main()
| true |
928d0729cfdcc0880182ed0a9453f190ff9f9f4a | jessiditocco/calculator2-01-18 | /calculator.py | 922 | 4.28125 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
while True:
token = raw_input("> ")
token = token.split()
operator = token[0]
if operator == "q":
break
elif operator == "+":
print add(float(token[1]), float(token[2]))
elif operator == "-":
print subtract(float(token[1]), float(token[2]))
elif operator == "*":
print multiply(float(token[1]), float(token[2]))
elif operator == "/":
print divide(float(token[1]), float(token[2]))
elif operator == "square":
print square(float(token[1]))
elif operator == "cube":
print cube(float(token[1]))
elif operator == "pow":
print power(float(token[1]), float(token[2]))
elif operator == "mod":
print mod(float(token[1]), float(token[2]))
| true |
5143231de6f9ce460c87056834ce6915d7960579 | amithmarilingegowda/projects | /python/python_programs/reverse_list.py | 712 | 4.71875 | 5 | import sys
# Option #1
# ---------
# Using in-built function "reversed()": This would neither reverse a list in-place(modify the original list),
# nor we create any copy of the list. Instead, we get a reverse iterator which we use to cycle through the list.
#
# Option #2
# ---------
# Using in-build function "reverse()": This would reverse the elements/objects of list in-place but no copy will be
# created.
#
# Option #3
# ---------
# Using Slicing technique
#
# Reversing a list using slicing technique
def Reverse(list):
return list[::-1]
list = [10, 11, 12, 13, 14, 15]
# Original List
print "Original List: ", list
# Reversed List
print "Reversed List: ",
print(Reverse(list))
| true |
6786b1a9403fd5127628622b32ad046207ec7fc9 | charliechocho/py-crash-course | /voting.py | 289 | 4.15625 | 4 | age = 101
if age >= 18 and age <= 100:
print("you're old enough to vote!!")
elif age > 100:
print("You're more than 100 years?!? Have you checked the obituaries?? ")
print("If you're not in there, go ahead and vote")
else:
print("Wait til' you're 18 and then you can vote") | true |
b2dd7887583c3d0af946550fb0603ac9ce35e158 | amitchoudhary13/Python_Practice_program | /string_operations.py | 661 | 4.4375 | 4 | #!usr/bin/python
'''
Basic String operations
Write a program to read string and print each character separately.
a) Slice the string using slice operator [:] slice the portion the strings to create a sub strings.
b) Repeat the string 100 times using repeat operator *
c) Read string 2 and concatenate with other string using + operator.
'''
#user input
str1 = raw_input()
str2 = raw_input()
#for loop to read string and print each character separately
for i in str1:
print "current letter is", i
#a
str3 = str1[2:5]
print "Sub string is", str3
#b
print "Repeated string is ", str1 * 100
#c
print "Concatenated string is ", str1 + str2
| true |
5713a0f09fbf8439b257469c668d67170992e716 | amitchoudhary13/Python_Practice_program | /odd_or_even.py | 263 | 4.125 | 4 | #!/usr/bin/python
'''Write a program to find given number is odd or Even'''
#variable declaration
a = 10
b = a % 2
if b == 0 : #if Implementation for even
print "Given number is", a, "even"
else: #if Implementation for odd
print "Given number is", a, "odd"
| true |
c41cb4db3290f33593118e98dbc208ec7a9bd332 | amitchoudhary13/Python_Practice_program | /fibonacci_series.py | 719 | 4.375 | 4 | #!/usr/bin/pyhton
'''20.Write a program to generate Fibonacci series of numbers. Starting numbers are 0 and 1, new number in the series is generated by adding previous two numbers in the series. Example : 0, 1, 1, 2, 3, 5, 8,13,21,..... a) Number of elements printed in the series should be N numbers, Where N is any +ve integer. b) Generate the series until the element in the series is less than Max number.'''
nterms=int(input("Enter the no of terms"))
a=0
b=1
if nterms<=0:
print("please enter positive number")
elif nterms==1:
print("Fibonacci series:",a)
elif nterms==2:
print a
print b
else:
print a
print b
while(nterms>2):
numnext=a+b
print numnext
a=b
b=numnext
nterms=nterms-1
| true |
e6cfee1b13d05dd52fdf6ee8312688bfcadf8098 | SaiPhani-Erlu/pyScript | /3_DeepDive/CaseStudy1/01_CompactRobot.py | 1,038 | 4.34375 | 4 | import math
from functools import reduce
'''
Q1. A Robot moves in a Plane starting from the origin point (0,0). The robot can move
toward UP, DOWN, LEFT, RIGHT. The trace of Robot movement is as given
following: UP 5, DOWN 3, LEFT 3, RIGHT 2
The numbers after directions are steps. Write a program to compute the
distance current position after sequence of movements.
'''
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Robot:
def __init__(self, x, y):
self.origin = Point(x, y)
self.move = Point(x, y)
def go(self, up, down, left, right):
self.move.y += up
self.move.y -= down
self.move.x += left
self.move.x -= right
def show_dist(self):
diff_array = [(self.origin.x - self.move.x), (self.origin.y - self.move.y)]
dist = math.sqrt(reduce(lambda x, y: x ** 2 + y ** 2, diff_array))
print("The distance covered from origin is: ", dist)
p1 = Robot(0, 0)
p1.go(up=5, down=3, left=3, right=2)
p1.show_dist()
| true |
beee7adf77fca1ddfc925ffdc7b8fbc93f86d248 | SaiPhani-Erlu/pyScript | /2_Seq_FileOps/seqInput.py | 1,758 | 4.1875 | 4 | '''
A website requires a user to input username and password to register.
Write a program to check the validity of password given by user.
Following are the criteria for checking password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12
'''
def isValid(pwd):
if 6 <= len(pwd) <= 12:
digit = 0
upper = 0
lower = 0
special = 0
for i in pwd:
if i.isupper():
upper += 1
elif i.islower():
lower += 1
elif i.isdigit():
digit += 1
else:
special += 1
if 0 in (digit, upper, lower, special):
return 'Password is NOT Valid'
else:
return 'Password is Valid'
return 'Password is NOT Valid'
print(isValid(input('Enter password:')))
# 5.Please write a program which accepts a string from console and print the characters that have even indexes
string = input('Q5= Enter Alphanumeric String:')
inList = list(string)
outList = []
for i in inList:
if inList.index(i) % 2 != 0:
outList.append(i)
print(''.join(outList))
# 6. Please write a program which accepts a string from console and print it in reverse order
string = input('Q6= Enter string to reverse:')
print(string[::-1])
# 7. Please write a program which count and print the numbers of each character in a string input by console
string = input('Q7= Enter string to count each character:')
dict = {}
for i in string:
if i in dict.keys():
dict[i] += 1
else:
dict[i] = 1
print(dict.items()) | true |
48d1d8d121393dd646ca1cf801afb34bcaab8fac | radam9/CPB-Selfmade-Code | /02 Keywords and Statements/L4E7_ListComprehensions.py | 1,294 | 4.46875 | 4 | #List comprehensions
#first lets check the beginners way
mys = 'hello'
myl =list() #we can use a shorter way as follows "myl = []"
for l in mys:
myl.append(l)
print(myl)
#now lets apply list comprehensions
mys = 'Hello'
myl = [l for l in mys]
print(myl)
#example
myl = [x for x in 'word']
print(myl)
#example 2
myl = [num for num in range(0,11)]
print(myl)
#we can perform operation on the first variable name
#getting square numbers
myl = [num**2 for num in range(0,11)]
print(myl)
#adding an if to the statement
myl = [num for num in range(0,11) if num%2==0]
print(myl)
#example - convertin temp from celcius to fahrenheit
c = [0,10,20,34.5]
f = [((9/5)*temp + 32) for temp in c]
print(f)
#the above example is a shorter way to the following
c = [0,10,20,34.5]
f = []
for temp in c:
f.append(((9/5)*temp + 32))
print(f)
#using a if and else in a List
myl = [x if x%2==0 else 'odd' for x in range(0,11)]
print(myl)
#the above example represents the following
myl = []
for x in range(0,10):
if x % 2==0:
myl.append(x)
else:
myl.append('odd')
print(myl)
#nested loops
myl = []
for x in [1,2,3]:
for y in [1,10,100]:
myl.append(x*y)
print(myl)
#adding the nested loop in a list comprehension
myl = [x*y for x in [1,2,3] for y in [1,10,100]]
print(myl)
| false |
ab9f452e8e1c711da3e27f8fdc101d274a860061 | radam9/CPB-Selfmade-Code | /07_Decorators.py | 1,990 | 4.3125 | 4 | #Decorators
#Mainly used for web developement (Flask and Django)
def func():
return 1
def hello():
return 'Hello!'
hello
greet = hello
greet
print(greet())
#
def hello(name='Adam'):
print('The hello() function has been executed!')
def greet():
return '\t This is the greet() function inside hello!'
def welcome():
return '\t This is welcome() inside hello'
print(greet())
print(welcome())
print('This is the end of the hello function!')
hello()
#greet and welcome's scope is the hello() function
#if you try to call them outside of that function you will get
#an undefined error
welcome()
#assigning a function to a variable using a return statement
def hello(name='Adam'):
print('The hello() function has been executed!')
def greet():
return '\t This is the greet() function inside hello!'
def welcome():
return '\t This is welcome() inside hello'
print('I am going to return a function!')
if name == 'Adam':
return greet
else:
return welcome
newfunc = hello()
print(newfunc())
# example
def cool():
def supercool():
return 'I am very cool!'
return supercool
func = cool()
print(func)
#example 2
def hello():
return 'Hi Adam!'
def other(deffunc):
print('Other code runs here!')
print(deffunc())
other(hello)
#Decorators (Manual way)
def new_decorator(original_func):
def wrap_func():
print('Some extra code, before the original function')
original_func()
print('Some extra code, after the original function')
return wrap_func
def func_needs_decorator():
print('I want to be decorated!!')
decorated_func = new_decorator(func_needs_decorator)
decorated_func()
# Decorators automatic way
#@new_decorator passes the funtion below it into new_decorator() and returns the
#result, while keeping the function name as is.
@new_decorator
def func_needs_decorator():
print('I want to be decorated!!')
func_needs_decorator()
| true |
0f82666397eba43041ecc911652e22d28d6876e8 | sravyapara/python | /icp3/vowels.py | 408 | 4.375 | 4 | str=input("enter the string")
def vowel_count(str):
# Intializing count to 0
count = 0
# Creating a set of vowels
vowel = {"a","e","i","o","u"}
# to find the number of vowels
for alphabet in str:
# If alphabet is present then count is incremented
if alphabet in vowel:
count = count + 1
print("No. of vowels :", count)
# Function Call
vowel_count(str) | true |
dc661840ce903a643db2dd851329fb1bbce006ac | MrRa1n/Python-Learning | /Tuple.py | 388 | 4.53125 | 5 | # Tuples are used to store a group of data
# Empty tuple
tuple = ()
# One item
tuple = (3,)
# Multiple items
personInfo = ("Diana", 32, "New York")
# Data access
print(personInfo[0])
print(personInfo[1])
# Assign multiple variables at once
name,age,country,career = ("Diana", 32, "United States", "CompSci")
print(country)
# Append to a tuple
x = (3,4,5,6)
x = x + (1,2,3)
print(x)
| true |
043f54f44d0fa3f3c3448940cf7ff7decd6fc148 | wpy-111/python | /month01/day03/exercise03.py | 490 | 4.15625 | 4 | # 练习 录入数字/运算符/数字
# 如果运算是+ - * / 打印结果,
number_one = float(input("请输入第一个数字:"))
operate = input("请输入运算符:")
number_two = float(input("请输入第二个数字:"))
if operate == "+":
print(number_one + number_two)
elif operate == "-":
print(number_one - number_two)
elif operate == "*":
print(number_one * number_two)
elif operate == "/":
print(number_one / number_two)
else:
print("运算错误")
| false |
1af3ff323ec577e65b93ad38a88979a105ef21e4 | wpy-111/python | /DataStructure/day03/03_queue.py | 771 | 4.3125 | 4 | """
python实现队列模型 - 顺序存储
思路:
1.先进先出
2.设计:列表的头部最为队头pop(0),列表尾部最为队尾,进行入队操作append
"""
class Queue:
def __init__(self):
self.queue = []
def is_empty(self):
return self.queue == []
def enqueue(self,value):
return self.queue.append(value)
def dequeue(self):
if self.is_empty():
raise Exception('dequeue from empty queue')
return self.queue.pop(0)
def size(self):
return len(self.queue)
if __name__ == '__main__':
q = Queue()
q.enqueue(100)
q.enqueue(200)
q.enqueue(300)
print(q.size())
print(q.dequeue())
print(q.dequeue())
print(q.size())
| false |
6e806db5f739d0f27684809d85b179261b6968d7 | wpy-111/python | /month01/day07/exercise07.py | 350 | 4.125 | 4 | """
一个筛子(1-6)
打印出三个筛子所有数字
"""
list_result=[]
for i in range(1,7):
for a in range(1,7):
for c in range(1,7):
list_result.append((a, i, c))
print(list_result)
print(len(list_result))
list_result=[(a, i, c) for i in range(1, 7) for a in range(1, 7) for c in range(1, 7)]
print(list_result) | false |
2ac6e2ccbbb8b1c16136932f1b89cca9bb62da3c | wpy-111/python | /month01/day08/homework.py | 607 | 4.3125 | 4 | """
字符串的函数
"""
name="清华 的 校训:持之 以 恒 . "
print(name.center(5,"-"))
# print(name.replace("清华","我的",1))
print(name.find("校训"))
print(name.isspace())#空白
print(name.count(" "))
name01=name.lstrip()#删除开头空白
print(name01)
name02=name.rstrip()#删除末尾空白
print(name02)
name03=name.strip()#删除开头和末尾空白
print(name03)
letter="我的sasfsdfasASADsaFDGAdfbi"
print(letter.lower())#将字符串变为小写
print(letter.upper())#将字符串变为大写
print(letter.swapcase())#将字符串小写变为大写,将大写变为小写 | false |
c5495793730e501b12c5f91dd60edd0a8a3adc41 | wpy-111/python | /month01/day16/exercise03.py | 543 | 4.15625 | 4 | #练习1.使用迭代思想,获取元祖中所有元素(“a","b","C")
#练习2.使用迭代思想,获取字典中所有记录(“a":1,"b":2,"C":3)
tuple=("a","b","C")
iteration=tuple.__iter__()
# while True:
while True:
try:
item=iteration.__next__()
print(item)
except StopIteration:
break
dict={"a":1,"b":2,"c":3}
iterations=dict.__iter__()
while True:
try:
qtx=iterations.__next__()
value=dict[qtx]
print("%s:%s"%(qtx,value))
except StopIteration:
break | false |
0e51d3c7ebe267947f9142ad7c38f1581e87a7f8 | GuilhermRodovalho/Algoritmos-e-estruturas-de-dados | /programaçao-dinamica/03-ola_universo.py | 1,564 | 4.1875 | 4 | """
Estamos no ano 3210 e há muitos e muitos anos atrás descobrimos que não
estamos sozinhos no Universo. Porém, em 2021 isso ainda era questionado.
Muitas civilizações em planetas da nossa galáxia, a Via-Láctea, já
entraram em contato com a Terra. Alguns até mantêm diálogos em busca de
nossos avançados algoritmos de busca de padrões em strings.
Felipe tem muito interesse pelo assunto e quer descobrir qual foi a
civilização mais antiga que enviou um Hello Galaxy para toda a galáxia.
Hello Galaxy é o primeiro comando do Protocolo de Ingresso (IP, em inglês)
no Protocolo de Transmissão e Comunicação (TCP) da Via-Láctea, garantindo
o contato entre civilizações.
A mensagem Hello Galaxy traz consigo duas informações básicas: o texto
“Hello World”, uma tradição muito antiga de origem desconhecida, e o
nome do planeta da civilização remetente. O CCVL, Centro de Comunicação
da Via-Láctea, instalado na Terra, recebe essas mensagens e registra o
ano em que foi recebida a mensagem e o número de anos que a mensagem
levou para chegar.
Felipe deve descobrir qual foi a primeira civilização a enviar o
"Hello World".
"""
casos = int(input())
while casos:
planetamaisvelho = ""
maisvelho = 0
for i in range(casos):
planeta, ano, tempo = input().split()
ano = int(ano)
tempo = int(tempo)
if ano - tempo < maisvelho or i == 0:
maisvelho = ano - tempo
planetamaisvelho = planeta
print(planetamaisvelho)
casos = int(input())
| false |
88c45d54bcf39138644d20b592b17ed02083c45e | courtneyng/GWC-18-PY | /gwc_py/programs/lists/liststuff.py | 739 | 4.28125 | 4 | friends = ["Camille", "Sarah", "Jade", "Aadiba", "Aishe"]
onepiece = ["Luffy", "Zoro", "Nami", "Usopp", "Sanji", "Chopper", "Robin", "Frankie", "Brook"]
friend = "RajabButt"
two = [friends, onepiece]
print(*friends) #list w/o brackets and commas
print(friends) #list with brackets and commas but also quotes
for name in friends: #print vertically (all names)
print(name)
print(len(friends))
print("Camille" in friends) #checks
print(friends[0])
for i in range(len(friends)):
#print(friends[i]) #this just prints names vertically
print(i)
for letter in friend: #print single letters down
print(letter)
print(len(friend))
for group in two:
for name in group:
print(name)
| true |
0ad9fd99507f9d1e1a14e43ce9b4f11b0850a80e | 3deep0019/python | /Input And Output Statements/Command_Line_Arguments.py | 947 | 4.1875 | 4 | # ------> argv is not Array it is a List. It is available sys Module.
# -----> The Argument which are passing at the time of execution are called Command Line
# Arguments.
# Note: ---------->argv[0] represents Name of Program. But not first Command Line Argument.
# argv[1] represent First Command Line Argument.
#Program: To check type of argv from sys
# import argv
# print(type(argv))
# q Write a Program to display Command Line Arguments
# ------ Ans
# from sys import argv
# print('The Number of Command Line Arguments:', len(argv))
# print('The List of Command Line Arguments:', argv)
# print('Command Line Arguments one by one:')
# for x in argv:
# print(x)
# from sys import argv
# sum=0
# args=argv[1:]
# for x in args :
# n=int(x)
# sum=sum+n
# print("The Sum:",sum)
from sys import argv
print(argv[1]+argv[1])
print(int(argv[1]+int(argv[2]))) | true |
a6e01da933653dca7493296ad2c255bcb6ab2609 | 3deep0019/python | /basic01/ListDataType.py | 414 | 4.15625 | 4 | # if we want to represent a group of values as a single entity where insertion order required
# to preserve and duplicates are allowed are allowwed then we should go for list data type .
list=[10,20,30,40]
print(list[0])
print(list[-1])
print(list[1:3])
list[0]=100
for i in list:print(i)
# --- **** list is growable in nature . Besed on our requirement we can increase or decrease the size.
| true |
97e513a0f616d804bf623dba4456b663da277b8a | 3deep0019/python | /Input And Output Statements/Input.py | 2,548 | 4.40625 | 4 | # 2)input():
# input() function can be used to read data directly in our required format.We are not
# required to perform type casting.
# x = input("Enter Value)
# type(x)
# 10 int
# "durga" str
# 10.5 float
# True bool
# ***Note:
# -------> But in Python 3 we have only input() method and raw_input() method is not available.
# ----->Python3 input() function behaviour exactly same as raw_input() method of Python2.
# Example
# every input value is treated as str type only.
# ---------> raw_input() function of Python 2 is renamed as input() function in Python 3.
# type(input("Enter value:"))
# Enter value:10
# <class 'str'>
# Enter value:10.5
# <class 'str'>
#Q) Write a program to read 2 numbers from the keyboard and print sum
# x=input("Enter First Number:")
# y=input("Enter Second Number:")
# i = int(x)
# j = int(y)
# print("The Sum:",i+j)
# Q) Write a Program to read Employee Data from the Keyboard and
# print that Data
# eno=int(input("Enter Employee No:"))
# ename=input("Enter Employee Name:")
# esal=float(input("Enter Employee Salary:"))
# eaddr=input("Enter Employee Address:")
# married=bool(input("Employee Married ?[True|False]:"))
# print("Please Confirm Information")
# print("Employee No :",eno)
# print("Employee Name :",ename)
# print("Employee Salary :",esal)
# print("Employee Address :",eaddr)
# print("Employee Married ? :",married)
# Write a Program to read Employee Data from the Keyboard and
# print that Data
# eno=int(input("Enter Employee No:"))
# ename=input("Enter Employee Name:")
# esal=float(input("Enter Employee Salary:"))
# eaddr=input("Enter Employee Address:")
# married=bool(input("Employee Married ?[True|False]:"))
# print("Please Confirm Information")
# print("Employee No :",eno)
# print("Employee Name :",ename)
# print("Employee Salary :",esal)
# print("Employee Address :",eaddr)
# print("Employee Married ? :",married)
# How to read multiple values from the keyboard in a
# single line:
a,b= [int(x) for x in input("Enter 2 numbers :").split()]
print("Product is :", a*b)
# Note: split() function can take space as seperator by default .But we can pass
# anything as seperator.
# Q) Write a program to read 3 float numbers from the keyboard
# with, seperator and print their sum
a,b,c= [float(x) for x in input("Enter 3 float numbers :").split(',')]
print("The Sum is :", a+b+c)
| true |
bfb02ba9318aeeceb7f7888063ba57036e965e7f | 3deep0019/python | /basic01/RelationalOperator.py | 700 | 4.1875 | 4 | # > , <= , < , <=
a=10
b=20
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
a > b is False
a >= b is False
a < b is True
a <= b is True
# *** We can apply relational operators for str types also.
#
a="durga"
b="durga"
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
a > b is False
a >= b is True
a < b is False
a <= b is True
# Note: Chaining of relational operators is possible. In the chaining, if all comparisons
# returns True then only result is True. If atleast one comparison returns False then the
# result is False | true |
9ffbab16675a9972956979ae653b3c2d283c860e | 3deep0019/python | /basic01/AssignmentOperators.py | 616 | 4.28125 | 4 | # Assignment operators
# -----------> We can use assignment operator to assign value to the variable.
# Eg:
# x = 10
# ****** We can combine asignment operator with some other operator to form compound
# assignment operator.
# Eg:
# x += 10 x = x+10
# -----> The following is the list of all possible compound assignment operators in Python.
# +=
# -=
# *=
# %=
# //=
# **=
# &=
# |=
# ^=
# >>=
# <<=
#
a = 10
b = a+20
print(b)
| true |
68025058491424f25b1b8ff2054283b6c50c8729 | 3deep0019/python | /STRING DATA TYPE/Replacing a String with another String.py | 1,227 | 4.5 | 4 | # Replacing a String with another String
# --------------------->>>>>>>>>> s.replace(oldstring, newstring)
# inside s, every occurrence of old String will be replaced with new String.
# Eg 1:
s = "Learning Python is very difficult"
s1 = s.replace("difficult","easy")
print(s1)
# Eg 2: All occurrences will be replaced
s = "ababababababab"
s1 = s.replace("a","b")
print(s1)
# Q) String Objects are Immutable then how we can change the
# Content by using replace() Method
# ANS -----> Once we creates string object, we cannot change the content.This non changeable
# behaviour is nothing but immutability. If we are trying to change the content by using
# any method, then with those changes a new object will be created and changes won't
# be happend in existing object.
# *** Hence with replace() method also a new object got created but existing object won't
# be changed.
# Eg:
s = "abab"
s1 = s.replace("a","b")
print(s,"is available at :",id(s))
print(s1,"is available at :",id(s1))
# In the above example, original object is available and we can see new object which was
# created because of replace() method. | true |
519e9ba48d09ed3d68f2cf1e552d4d2fbe689a7c | andremenezees/CursoPython | /Aulas/4_Orientada_a_objetos/7_Heranca_Multipla.py | 1,990 | 4.625 | 5 | """
Heraca Multipla
Como nome ja diz é a habilidade de uma classe herdar atributos e metodos de
outras multiplas classes.
"""
# Exemplo 1 - Multiderivacao direta
class Base1:
pass
class Base2:
pass
class MultiDerivada(Base1, Base2):
pass
# Exemplo 2 - Multiderivacao indireta
class Base1:
pass
class Base2(Base1):
pass
class Base3(Base2):
pass
class MultiDerivada(Base3): # E possveil perceber que herdando a base 3 a classe esta herdando todas as outras tbm.
pass
# Exemplo
class Animal:
def __init__(self, nome):
self.__nome = nome
def cumprimentar(self):
return f'Eu sou {self.__nome}'
class Aquatico(Animal):
def __init__(self, nome):
super().__init__(nome)
def nadar(self):
return f"{self._Animal__nome} está nadando"
def cumprimentar(self):
return f"Eu sou {self._Animal__nome} do mar"
class Terrestre(Animal):
def __init__(self, nome):
super().__init__(nome)
def andar(self):
return f'{self._Animal__nome} esta andando'
def cumprimentar(self):
return f"Eu sou {self._Animal__nome} da terra"
class Pinguim(Aquatico, Terrestre):
def __init__(self, nome):
super().__init__(nome)
# Testando
print('\n')
baleia = Aquatico("Wally")
print(baleia.nadar())
print(baleia.cumprimentar())
print('\n')
tatu = Terrestre('Xim')
print(tatu.andar())
print(tatu.cumprimentar())
print('\n')
ping = Pinguim('Tux')
print(ping.andar())
print(ping.nadar())
print(ping.cumprimentar()) # Method resolution Order - MRO, executa a primeira super classe escrita na classe pinguim
"""
MRO = Method Resolution Order (Resolução de Ordem de Métodos)
Basicamente escolhe qm será executado primeiro.
É possivel conferir a ordem de execução através de alguns metodos:
Através de propriedade da classe __mro__
via mro()
via Help
"""
#from mro import Pinguim
print(Pinguim.__mro__) #É possivel ver qual execução sera antes. | false |
6e506dc51b848e1f400f80aeaff57635c6eccfb4 | andremenezees/CursoPython | /Aulas/2_Meio/Lambdas.py | 1,603 | 4.875 | 5 | """
Utilizando lambdas
Conhecidas por expressões Lambdas, ou simplesmente Lambdas, são funções sem nome,
ou seja, funçÕes anonimas.
"""
def funcao(x):
return 3 * x + 1
print(funcao(4))
#Expressão lambda
lambda x: 3 * x + 1
#E como utilizar a empressão lambda?
calc = lambda x: 3 * x + 1
print(calc(4))
#Podemos ter expressões lambdas com multiplas entradas
nome_completo = lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title()
#O strip serve para tirar os espaços do começo e do final
#O title serve para colocar em maisculo as iniciais das palavras e em minusculo o resto.
print(nome_completo('maicon', 'jordan'))
print(nome_completo(' maicon', 'jordan '))
print(nome_completo('maicon', 'JORDAN'))
#Em funções python podemos ter varias entradas ou nenhuma. Portanto em lambda tbm.
amar = lambda: 'Como não amar python?'
uma = lambda x: 3* x + 1
duas = lambda x, y: 3*x + 2*y
tres = lambda x, y, z: (3 + z) + 2*x + 4*y
print(amar())
print(uma(2))
print(duas(3, 1))
print(tres(4, 1, 2))
#Outro exemplo
nomes = ['Maicon Jordan', 'Mapache X. God', 'Cristiano Ronaldo', 'Lionel Messi',
'Neymar Jr', 'Gabriel Toledo']
print(nomes)
#Foi feito uma ordenação da lista pelo sobrenome
nomes.sort(key=lambda sobrenome: sobrenome.split(' ')[-1])
print(nomes)
#Função quadratica com lambda (ax2 + bx + c)
def gerador_funcao_quadratica(a, b, c):
return lambda x: a * x ** 2 + b * x + c
teste = gerador_funcao_quadratica(2, 3, 5)
print(teste(0))
print(teste(1))
print(teste(2))
#Outra forma de printar.
print(gerador_funcao_quadratica(2, 4, 5)(2))
| false |
f221ff27ef1580ef0bcda2c69a06931b88a55dd4 | oldmuster/Data_Structures_Practice | /sort/python/bubble_sort.py | 2,254 | 4.125 | 4 | #!/usr/bin/env python
#coding:utf-8
"""
冒泡排序:
1. 比较相邻的元素。交换逆序对
2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。 最后一趟可以确定最后一个为最大元素
3. 对[0, max-i] 的元素集重复上述操作
记忆口诀:
交换逆序对(if n[j]>n[j+1]:n[j],n[j+1]=n[j+1],n[j])
划分左未排序区间和右已排序区间(range(0,n-1)->range(0,n-i-1)), 第一次遍历需要空出最后一个元素,否则nums[j+1]就会溢出。
优化1:某一趟遍历如果没有数据交换,则说明已经排好序了,直接break退出排序,用一个标记记录这个状态即可。
优化2: 记录某次遍历时最后发生数据交换的位置,这个位置之后的数据显然已经有序了。 因此通过记录最后发生数据交换的位置就可以确定下次循环的范围了。
"""
def bubble_sort(nums):
"""冒泡排序"""
for i in range(len(nums)-1):
for j in range(len(nums)-i-1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
print nums
return nums
def bubble_sort1(nums):
"""冒泡排序优化1"""
for i in range(len(nums)-1):
swap_count = 0 # 记录每次冒泡交换的次数
for j in range(len(nums)-i-1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
swap_count += 1
print nums, swap_count
if swap_count == 0:
break
return nums
def bubble_sort2(nums):
"""冒泡排序优化1"""
k = len(nums) - 1 #k为每次冒泡循环的范围
for i in range(len(nums) - 1):
flag = True
for j in range(0,k): #只遍历到最后交换的位置即可
if nums[j] > nums[j+1] :
nums[j+1],nums[j] = nums[j],nums[j+1]
k = j #记录最后交换的位置
flag = False
print nums
if flag :
break
return nums
def test_bubble_sort():
nums = [4, 5, 6, 3, 2, 1]
assert bubble_sort(nums) == [1, 2, 3, 4, 5, 6]
print 'bubble sort optimize 1'
nums = [3, 5, 4, 1, 2, 6]
assert bubble_sort1(nums) == [1, 2, 3, 4, 5, 6]
print 'bubble sort optimize 2'
nums = [3, 5, 4, 1, 2, 6]
assert bubble_sort2(nums) == [1, 2, 3, 4, 5, 6]
if __name__ == '__main__':
test_bubble_sort() | false |
6d8097e4c80ab7ebebaca9900840cef7bf50f55e | oldmuster/Data_Structures_Practice | /stack/__init__.py | 2,052 | 4.1875 | 4 | #!/usr/bin/env python
#coding:utf-8
"""
Stack based upon linked list
基于链表实现的栈
Author: Wenru
"""
class Node(object):
def __init__(self, data, next=None):
self._data = data
self._next = next
class LinkedStack(object):
"""用链表实现的链式栈
"""
def __init__(self):
"""只需要一个栈顶指针即可"""
self._top = None
def push(self, value):
new_top = Node(value)
new_top._next = self._top # 新元素指向栈下面一个元素
self._top = new_top #就栈顶指针赋值给新的元素
def pop(self):
if self._top:
value = self._top._data
self._top = self._top._next # 栈往下移一位
return value
def __repr__(self):
current = self._top
nums = []
while current:
nums.append(current._data)
current = current._next
return " ".join("%s"% num for num in nums)
def test_linkedstack():
stack = LinkedStack()
for i in range(9):
stack.push(i)
print(stack)
for _ in range(3):
stack.pop()
print(stack)
class ListStack(object):
"""使用List数据结构实现的顺序栈"""
def __init__(self, ):
self._items = []
def push(self, value):
"""入栈"""
self._items.append(value)
def pop(self):
"""弹出栈顶元素"""
if len(self._items) >0:
return self._items.pop()
else:
return None
def peek(self):
"""返回栈顶元素"""
return self._items[-1]
def is_empty(self):
return len(self._items) == 0
def __repr__(self):
return " ".join("%s" % i for i in self._items)
def test_arraystack():
stack = ListStack()
for i in range(9):
stack.push(i)
print(stack)
for _ in range(10):
print stack.pop()
# print(stack)
# print(stack.peek())
if __name__ == '__main__':
#test_linkedstack()
test_arraystack()
| false |
d7bf9dfa2783e4797471551de7852fc9fc5f438b | alvas-education-foundation/CSE-K-Thrishul-4AL17CS038 | /Machine Learing Class/02-Sept/P3_02-Sept.py | 219 | 4.21875 | 4 | '''
3. Write a Python program to test whether a passed letter is a vowel or not
'''
def is_vowel(ch):
All_vowels = 'aeiou'
return ch in All_vowels
char = input("Enter a Character : ")
print(is_vowel(char))
| false |
aef7af59132217b8002b44d4083a951f89a37b4d | 1F659162/Palindrome | /Palindrome.py | 707 | 4.125 | 4 | # 6206021620159
# Kaittrakul Jaroenpong IT 1RA
# Python Chapter 5 Example 3
print(">> Program Palindrome Number <<")
number = input("Enter integer number : ")
count = -1
for i in range(len(number)//2):
if number[i] == number[count] :
print(f"Digit {number[i]} equal to Digit {number[count]}")
Palin = "is Palindrome Number."
else :
print(f"Digit {number[i]} not equal to Digit {number[count]}")
Palin = "isn't Palindrome Number."
break
count -= 1
if len(number)%2 == 1 and i == len(number)//2:
print(f"Digit {number[len(number)//2]} equal to Digit {number[len(number)//2]}")
print(f"Your enter number : {number} {Palin}")
print(f"Exit Program")
| false |
2a8d3f1ee39455d37885011c0e0aad5aa5173ecd | gum5000/The-Soap-Mystery | /Main.py | 1,821 | 4.25 | 4 | # Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+=1
k+=1
while j < len(R):
arr[k] = R[j]
j+=1
k+=1
#binary search for index of x
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -(mid + 2)
numSoap = int(input())
soapCost = []
inputCost = input().split(" ")
for i in range(numSoap):
soapCost.append(int(inputCost[i]))
mergeSort(soapCost)
q = int(input())
for Q in range(q):
cost = int(input()) - 1
if cost < soapCost[0]:
print(0)
elif cost > soapCost[numSoap - 1]:
print(numSoap)
else:
index = binary_search(soapCost, cost)
if index < 0:
index = index * -1
if index >= numSoap:
index = numSoap - 1
while cost < soapCost[index]:
index -= 1
else:
if index + 1 < numSoap:
while cost >= soapCost[index + 1]:
if index + 2 < numSoap:
index += 1
else:
break
print(index + 1)
| true |
4ea5fe095bb8b14c78421fd592e1198e92e2338f | anthonywww/CSIS-9 | /prime_numbers.py | 632 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: prime_numbers.py
# Anthony Waldsmith
# 07/12/2016
# Python Version 3.4
# Description: Print out prime numbers between 3 to 100.
# Optional import for versions of python <= 2
from __future__ import print_function
# Loop between 3(start) to 100(end)
for i in range(3,100):
# Nested loop, check every integer that can be divisible (n-1)
for j in range(2,i-1):
if (i % j == 0):
# Number is not prime, break out of this loop
break;
if (i % j != 0 and j == i-2):
# Number is prime
print(i)
"""
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
"""
| true |
3cc6d21d24190988ef9c970cbb4e808607cd8e1f | anthonywww/CSIS-9 | /is_triangle.py | 1,249 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: is_triangle.py
# Anthony Waldsmith
# 07/14/2016
# Python Version 3.4
# Description: A function that checks if a triangle can be formed with the following parameters (a, b, c)
import random
# isTriangle function
def isTriangle(a,b,c):
# Check if the lengths are less-than or equal to two other sides.
if (a <= (b+c)) and (b <= (a+c)) and (c <= (a+b)):
return True
else:
# Otherwise it's not a triangle
return False
# Main function
def main():
# Set side values to random nums
a = random.randint(0,256)
b = random.randint(0,256)
c = random.randint(0,256)
# Set default string value
s = "does NOT"
# Change string value if it's a triangle
if (isTriangle(a,b,c)):
s = "DOES"
# Print final values
print ("Side 1 = [%i], Side 2 = [%i], Side 3 = [%i]; this %s make a triangle" %(a,b,c,s))
main()
"""
Side 1 = [114], Side 2 = [10], Side 3 = [9]; this does NOT make a triangle
Side 1 = [4], Side 2 = [176], Side 3 = [225]; this does NOT make a triangle
Side 1 = [175], Side 2 = [53], Side 3 = [212]; this DOES make a triangle
Side 1 = [132], Side 2 = [187], Side 3 = [117]; this DOES make a triangle
Side 1 = [143], Side 2 = [124], Side 3 = [85]; this DOES make a triangle
"""
| true |
9b9305de824ee3d38dcc69da90a2f26ea150979e | anthonywww/CSIS-9 | /TEMPLATE.py | 636 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: <ENTER PROGRAM NAME>
# <ENTER NAME>
# <ENTER DATE>
# Python Version 3.4
# Description: <ENTER DESCRIPTION>
# Optional import for versions of python <= 2
from __future__ import print_function
# Do this until valid input is given
while True:
try:
# Text input
text = input("Prompt ")
except ValueError:
# If there is invalid input (casting exception)
# Show the user this text in console, then continue the loop
print("Sorry, I didn't understand that, try again.")
continue
else:
# The value was successfully parsed
# So break out of the loop
break
| true |
debec9fcf3c46ab975dd0d88c5bc822cc64cab11 | anthonywww/CSIS-9 | /mult_add.py | 472 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: mult_add.py
# Anthony Waldsmith
# 07/14/2016
# Python Version 3.4
# Description: A function that takes in 3 parameters (a,b,c) and does the following operation a*b+c
# multAdd function
def multAdd(a,b,c):
return ((a*b)+c)
# Main function
def main():
a = 6
b = 10
c = 4
print("Num 1 = %i, Num 2 = %i, Num 3 = %i; Answer: %i" %(a,b,c,multAdd(a,b,c)))
main()
"""
Num 1 = 6, Num 2 = 10, Num 3 = 4; Answer: 64
"""
| false |
1006690d7e272732f7c61093227966af0096e9cc | aymenbelhadjkacem/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 974 | 4.21875 | 4 | #!/usr/bin/python3
"""Module square empty"""
class Square:
"""Square class def"""
def __init__(self, size=0):
"""if size not integer test raise expectation"""
""" attribute size (int): Size of square"""
self.__size = size
"""are function defintion"""
def area(self):
"""return the area of square"""
return self.__size**2
"""getter of size"""
@property
def size(self):
return self.__size
"""setter of size"""
@size.setter
def size(self, newsize):
"""if size not integer test raise expectation"""
""" attribute size (int): Size of square"""
if type(newsize) != int:
raise TypeError("size must be an integer")
"""second test if size is negative it must be positive"""
elif newsize < 0:
raise ValueError("size must be >= 0")
"""if size is positive init it"""
else:
self.__size = newsize
| true |
c51065c4ecbe92b79f967e72a8953498bede8c7c | albertsuwandhi/Python-OOP | /abstract_class.py | 624 | 4.1875 | 4 | # ABC = abstract base class
from abc import ABC, abstractmethod
#inheritance form ABC
class Button(ABC):
@abstractmethod
def onClick(self):
pass
class pushButton(Button):
def onClick(self):
print("Push Button Clicked")
class radioButton(Button):
# pass
# onClick must be implemented, if not will raise an error
def onClick(self):
print("Radio Button Clicked")
#This will generate error : TypeError: Can't instantiate abstract class Button with abstract methods onClick
#button1 = Button()
button2 = pushButton()
button2.onClick()
button3 = radioButton()
button3.onClick()
| true |
b1398fa7502fa47412ba7986d3727b1c944ffc46 | J-sudo-2121/codecademy_projects | /players.py | 1,291 | 4.71875 | 5 | # Working with a specific group of items in a list is called a slice (slicing)
# in Python.
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
# You can generate any subset of a list.
print(players[1:4])
# If you omit the first index in a slice Python automatically starts your slice
# at the beginning of the list.
print(players[:4])
# Same goes for the last index.
print(players[1:])
print(players[-3:])
# Adding a third number to the index tells Python how many items to skip between
# items in the specified range.
print(players[::2])
# You can use slice in a for loop if you want to loop through parts of the
# elements in a list.
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
# Trying my own. Three different slices.
# Print the first 3 from the list.
print("The first three items on the list are:")
for first_three in players[:3]:
print(first_three.title())
# Print 3 items from the middle of the list
print(len(players))
print("Three items from the middle of the list are:")
for middle_three in players[1:4]:
print(middle_three.title())
# Print last 3 items on the list.
print("The last three items from the list are:")
for last_three in players[-3:]:
print(last_three.title())
| true |
cc0742449bd9a5353248bb4d2d33a597c030d505 | J-sudo-2121/codecademy_projects | /toppings.py | 2,570 | 4.5 | 4 | # When you want to determine whether two values are not equal use (!=). !
# represents not.
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
# Most of the conditional expressions you write will test for equality. /
# Sometimes you'll find it more efficient to test for inequlity.
# To find out wheter a particular value is already in a list, use keyword in.
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings
# Will return True
'pepperoni' in requested_toppings
# Will return False
# This is helpful by allowing you to create a list of esential values and then /
# easily check whether the value you're testing matches one of the values on /
# the list.
# Sometimes it's important to check all of the conditions of interest. If so, /
# use a series of simple if statments without elif or else blocks.
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("\nAdding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
# This code wouldn't work properly if an if-elif-else chain was used. If you /
# want only one block of code to run, use an if-elif-else chain. If more than /
# one block of code needs to run, use a series of independent if statements.
# Searching for special values that need to be treated differently than other /
# values in the list.
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("\nSorry, we are out of green peppers right now.")
else:
print(f"\nAdding {requested_topping}.")
print("\nFinished making your pizza!")
#Checking that a list is not empty.
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"\nAdding {requested_topping}")
print("\nFinished making your pizza!")
else:
print("\nAre you sure you want a plain pizza?")
# Using Multple Lists.
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni',
'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
print("\nCan I take your order?")
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!") | true |
1afdd366fccc022e4d4dd66ad7a881c79db8eb3b | J-sudo-2121/codecademy_projects | /cars2.py | 1,926 | 4.34375 | 4 | # Using an if statement.
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# Python uses the values of True and False to decide whether the code in an if /
# statement should be executed.
# Conditional Tests.
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False")
print(car == 'audi')
animal = 'dog'
print("\nIs animal == 'fish'? I predict False")
print(animal == 'fish')
print("\nIs animal == 'dog'? I predict True")
print(animal == 'dog')
color = 'brown'
print("\nIs color == 'brown'? I predict True")
print(color == 'brown')
print("\nIs color == 'yellow'? I predict False")
print(color == 'yellow')
computer = 'Asus'
print("\nIs computer == 'asus'? I predict False")
print(computer == 'Dell')
print("\nIs computer == 'asus'? I predict True")
print(computer.lower() == 'asus')
fruit = 'durian'
print("\nIs fruit == 'papaya'? I predict False")
print(fruit == 'papaya')
print("\nIs fruit == 'durian'? I predict True")
print(fruit == 'durian')
shoes = 'nike'
print("\nIs shoes != 'adidas'? I predict True")
print(shoes != 'adidas')
print("\nIs shoes != 'nike'? I predict False")
print(shoes != 'nike')
number = 37
print('\nIs number > 31? I predict True')
print(number > 31)
print("\nIs number <= 17? I predict False")
print(number <= 17)
print("\nIs number < 22 and 39? I predict False")
print((number < 22) and (number <39))
print("\nIs number > 56 or 22? I predict True")
print((number > 56) or (number > 22))
storage_items = ['pens', 'staples', 'paper', 'ink', 'pencils']
requested_items = ['pens', 'pencils', 'erasers', 'markers']
for requested_item in requested_items:
if requested_item in storage_items:
print(f"\n{requested_item.title()} can be found on the second shelf in \
the closet")
else:
print(f"\nSorry, we are out of {requested_item}.") | true |
102d1b647849efe444787a335e3aeb610e92447e | Yao-Ch/OctPyFun2ndDayPM | /Exercise4.py | 773 | 4.28125 | 4 | french=("Mer","Ville","Voiture","Ciel","Couleur")
english=("Sea","Town","Car","Sky","Color")
fr_en=dict(zip(french, english))
# or more directly:
# fr_en={"Mer":"Sea","Ville":"Town","Voiture":"Car",
# "Ciel":"Sky",
# "Couleur":"Color"}
while True:
answerOrg=input("Enter a french word (or 'Stop'): ")
answer=answerOrg.lower().capitalize()
if answer == "Stop":
print("Bye!")
break
if answer in fr_en:
print(f"Translation of {answerOrg} is {fr_en[answer]}")
else:
print(f"No entry for the word: {answerOrg} in my dict")
print("But I can translate:")
for fr in sorted(fr_en.keys()):
print(fr,end=" ")
print() # to print an empty line
| false |
a647288d4d031ffc705c807166d7c2332e1d9638 | vandyliu/small-python-stuff | /madLibs.py | 1,955 | 4.1875 | 4 | #! python3
# Takes a mad libs text file and finds where an ADJECTIVE, NOUN, ADVERB, VERB should be replaced
# and asks users for a suggestion then saves the suggestion to a text file in the same directory
# Idea from ATBS
# To run type python.exe madLibs.py <path of madlibs text>
# Eg. python.exe C:\Users\Vandy\PycharmProjects\ATBS\madLibs.py C:\Users\Vandy\Desktop\madlibs.txt
import sys, os
if len(sys.argv) == 1:
print("Please write a madlibs text file path location as the second argument")
elif len(sys.argv) == 2:
path = sys.argv[1].lower()
# path = 'C:\\Users\\Vandy\\Desktop\\madlibs.txt'
if os.path.exists(path):
madLibsFile = open(path)
textList = madLibsFile.read().split()
for word in textList:
if 'ADJECTIVE' in word.upper():
index = word.upper().find('ADJECTIVE')
adjWord = input('Enter an adjective: ')
textList[textList.index(word)] = word[:index] + adjWord + word[index+9:]
elif 'NOUN' in word.upper():
index = word.upper().find('NOUN')
nounWord = input('Enter a noun: ')
textList[textList.index(word)] = word[:index] + nounWord + word[index+4:]
elif 'ADVERB' in word.upper():
index = word.upper().find('ADVERB')
advWord = input('Enter an adverb: ')
textList[textList.index(word)] = word[:index] + advWord + word[index+6:]
elif 'VERB' in word.upper():
index = word.upper().find('VERB')
verbWord = input('Enter a verb: ')
textList[textList.index(word)] = word[:index] + verbWord + word[index+4:]
endText = " ".join(textList)
print(endText)
endFile = open('%s_filled.txt' % os.path.join(os.path.dirname(path), os.path.basename(path)[:-4]), 'w')
endFile.write(endText)
madLibsFile.close()
endFile.close()
| true |
5150d24094b79bea9df2d5a4faccca56210075b7 | JhonattanDev/Exercicios-Phyton-05-08 | /ex14.py | 691 | 4.46875 | 4 | # Explicando o programa
print("=================================================================")
print("|Digite o valor do salário para aplicar um aumento de 15% a ele!|")
print("=================================================================")
# Pedir ao Usuário inserir o valor do salário
salarioIncial = int(input("Digite o valor do salário: "))
# Cálculo
salarioComAcrescimo = salarioIncial * 1.15
# Imprimir, mostrar o resultado do programa
# {:.2f} para mostrar 2 número após o ponto
print("O valor original do salário era de R${:.2f}.".format(salarioIncial))
print("O valor do salário com acréscimo de 15% fica: R${:.2f}.".format(salarioComAcrescimo))
| false |
94c160e31517b75bfb75b43550ddc059762f7099 | fengluodb/a-simple-snake-game | /AutoMove.py | 1,628 | 4.125 | 4 | # 简单的自动寻路逻辑
def simple(snake_x, snake_y, food_x, food_y, direction):
if direction is None:
if snake_x < food_x:
direction = "right"
if snake_x > food_x:
direction = "left"
else:
if snake_y < food_y:
direction = "down"
elif snake_y > food_y:
direction = "up"
else:
if direction == "left":
if snake_x > food_x:
direction = "left"
elif snake_x == food_x:
if snake_y > food_y:
direction = "up"
elif snake_y < food_y:
direction = "down"
else:
direction = "up"
elif direction == "right":
if snake_x > food_x:
direction = "up"
elif snake_x < food_x:
direction = "right"
else:
if snake_y > food_y:
direction = "up"
elif snake_y < food_y:
direction = "down"
elif direction == "up":
if snake_x < food_x:
direction = "right"
elif snake_x > food_x:
direction = "left"
else:
if snake_y < food_y:
direction = "left"
elif direction == "down":
if snake_x < food_x:
direction = "right"
elif snake_x > food_x:
direction = "left"
else:
if snake_y > food_y:
direction = "left"
return direction
| false |
fcfd80443b1dc4eba5b25056252a465057362201 | gravityrahul/PythonCodes | /AttributeConcepts.py | 2,119 | 4.34375 | 4 | '''
Python attribute tutorial based on Sulabh Chaturvedi's online tutorial
www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html
#method-resolution-order
'''
class C(object):
'''
This example illustrates Attribute concepts
'''
classattribute="a class attribute"
def f(self):
return "function f"
cobj = C()
print cobj.f
# if Python finds an object with a __get__() method inside the
# class's __dict__,
# instead of returning the object, it calls the __get__() method and returns
# the result. Note that the __get__() method is called with the instance and the class as the
# first and second arguments respectively.
print C.__dict__['f'].__get__(cobj, C)
# It is only the presence of the __get__() method that transforms an ordinary function into a bound
# method. There is nothing really special about a function object. Anyone can put objects with a
# __get__() method inside the class __dict__ and get away with it.
# An example of descriptor
class Descriptor(object):
"A class demonstrating descriptor protocol"
def __get__(self, obj, cls=None): #cls is optional class argument
pass
def __set__(self, obj, val):
pass
def __delete_(self, obj):
pass
class C2(object):
'''
A class with single descriptor
'''
d = Descriptor()
cobj2=C2()
cobj2.d = "setting a value"
cobj2.__dict__['d']="Try to force a value"
x = cobj2.d
C2.d = "Setting a value on class"
print C2.d
d = Descriptor()
d.__set__(cobj, "setting a value")
print x
#Non-data descriptors
class NonDataDescriptor(object):
"A class demonstrating descriptor protocol"
def __get__(self, obj, cls=None): #cls is optional class argument
pass
class C3(object):
'''
A class with single descriptor
'''
d = NonDataDescriptor()
cobj3 = C3()
cobj3.d = "Setting a value for nondata"
print cobj3.d
print cobj3.__dict__
d = NonDataDescriptor()
d.__get__(cobj3, C3)
print d.__dict__ | true |
0dc3b3104f4470e167227184602631f12951dab3 | ImprovementMajor/New | /Task1.py | 250 | 4.1875 | 4 | temp = float(input("Welcome to the temperature converter! Please enter a temperature and its units: "))
if units == F :
print(temp_f)
else :
print(temp_c)
temp_f = (9/5) * temp_c + 32
print(temp_f)
temp_c = temp_f - 32 * 5/9
print(temp_c)
| true |
0863297aca2ecae6ce8b6dd76fc268fc4fa1de67 | kishanSindhi/python-mini-projects | /minipro8.py | 358 | 4.28125 | 4 | # Author - Kishan Sindhi
# date - 30-5-2021
# discription - this function take the year as input from the user
# and in return it tells that the entered tear us a leap yaer or not
year = int(input("Enter a year you want to check that is a leap year or not:\n"))
if year % 4 == 0:
print("Year is leap year")
else:
print("Year is not a leap year")
| true |
f2d20dbd5ccb633702e4ef6f07ade72bfe1b5b65 | 6hack9/python-workshop | /python-stucture/set.py | 664 | 4.28125 | 4 | s5 = {1,2,3,4}
s6 = {3,4,5,6}
""" Use the | operator or the union method for a union operation: """
print(s5 | s6, '\n')
print(s5.union(s6),'\n')
""" Now use the & operator or the intersection method for an intersection operation: """
print(s5 & s6, '\n')
print(s5.intersection(s6),'\n')
""" Use the – operator or the difference method to find the difference between two sets: """
print(s5 -s6, '\n')
print(s5.difference(s6),'\n')
""" Now enter the <= operator or the issubset method to check if one set is a subset of another: """
print((s5 <= s6))
print(s5.issubset(s6),'\n')
s7 = {1,2,3}
s8 = {1,2,3,4,5}
print(s7 <= s8)
print(s7.issubset(s8)) | false |
e5947d044940b0d42e446919219b6727211a5e6e | tusharsappal/GeneralInterViewquestions | /GeeksForGeeks Questions/LinkedListPrograms/SimpleOrderedLinkedList.py | 1,445 | 4.15625 | 4 |
class Node(object):
def __init__(self,initData):
self.data = initData
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newData):
self.data = newData
def setNext(self,nextNode):
self.next = nextNode
class OrderedList(object):
head = None
def __int__(self):
self.head = None
def isEmpty(self):
return self.head is None
def addElementToOrderedList(self, element):
node = Node(element)
node.next = None
if self.isEmpty():
self.head = node
else :
iterator = self.head
while iterator.getNext() is not None:
iterator = iterator.next
iterator.next = node
def printOrderedList(self):
iterator = self.head
while iterator is not None:
print iterator.getData()
iterator = iterator.getNext()
if __name__=="__main__":
print "Now Ordered List Operations Starts"
orderedList = OrderedList()
orderedList.addElementToOrderedList(10)
orderedList.addElementToOrderedList(20)
orderedList.addElementToOrderedList(30)
orderedList.addElementToOrderedList(40)
orderedList.addElementToOrderedList(50)
orderedList.addElementToOrderedList(60)
orderedList.addElementToOrderedList(70)
orderedList.printOrderedList()
| true |
f834cbb5c946259bf32c29c033c2603779f63579 | tusharsappal/GeneralInterViewquestions | /GeeksForGeeks Questions/ArrayPrograms/BinarySearch.py | 1,083 | 4.15625 | 4 | # A simple class demonstrating Binary Search
class BinarySearch(object):
def binarySearch(self):
print "Enter the Sorted Array \n"
string_input = raw_input()
input_list = string_input.split()
input_list = [int(a) for a in input_list]
print "Array to be searched", input_list
# Binary Search Logic starts here
num_to_be_searched = int(input("Enter number to be searched"))
lower_limit = 0
higher_limit = input_list.__len__()-1
middle = (lower_limit+higher_limit) / 2
while ( lower_limit <= higher_limit):
if num_to_be_searched == input_list[middle]:
print "Number found at %d" %(middle+1)
break
if input_list[middle] < num_to_be_searched:
lower_limit = middle +1
else :
higher_limit = middle -1
middle = (higher_limit+lower_limit)/2
if ( lower_limit > higher_limit):
print "Number not found"
if __name__ == '__main__':
BinarySearch().binarySearch()
| true |
b396c5e7c99690636400614be744a0bb83d21659 | tusharsappal/GeneralInterViewquestions | /GeeksForGeeks Questions/ArrayPrograms/LeadersInArray.py | 924 | 4.125 | 4 | # This program checks for the leader in the array
#An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader.
class FindLeaderInArray(object):
def findLeaderInArray(self):
print "Enter the Array "
string_input = raw_input()
input_list = string_input.split()
input_list = [int(a) for a in input_list]
if input_list.__len__() == 1:
print "Leader is %d " %(input_list[0])
else:
upper_limit = input_list.__len__()-1
max = input_list[upper_limit]
print max
while (upper_limit >= 0):
if input_list[upper_limit] > max:
print input_list[upper_limit]
max = input_list[upper_limit]
upper_limit = upper_limit-1
if __name__=="__main__":
FindLeaderInArray().findLeaderInArray()
| true |
f7b74aa32c21042a530ddac4df0655348dfcf8ce | tusharsappal/GeneralInterViewquestions | /GeeksForGeeks Questions/DynamicProgramming/SumOfAllSubStringRepresentingString.py | 1,370 | 4.125 | 4 | '''This program prints Sum of all substrings of a string representing a number
We will be using the Concept of Dynamic Programing
We can solve this problem using dynamic programming. We can write summation of all substrings on basis of digit at which they are ending in that case,
Sum of all substrings = sumofdigit[0] + sumofdigit[1] + sumofdigit[2] and so on + sumofdigit[n-1] where n is length of string.
Where sumofdigit[i] stores sum of all substring ending at ith index digit, in above example,
Example : num = "1234"
sumofdigit[0] = 1 = 1
sumofdigit[1] = 2 + 12 = 14
sumofdigit[2] = 3 + 23 + 123 = 149
sumofdigit[3] = 4 + 34 + 234 + 1234 = 1506
Result = 1670
General Logic = sum[i] = (i+1)*array[i]+ '''
class SumOfAllSubStringsRepresentingString(object):
def printSumOfSubString(self):
string_input = raw_input("Enter the String")
len_of_string = string_input.__len__()
sum_of_digit = [0]*len_of_string
sum_of_digit[0] = int(string_input[0])
res= sum_of_digit[0]
index = 0
for index in range(1 , len_of_string):
numi = int(string_input[index])
sum_of_digit[index] = (index+1)*numi+ 10* sum_of_digit[index-1]
res = res+ sum_of_digit[index]
print res
if __name__=="__main__":
SumOfAllSubStringsRepresentingString().printSumOfSubString() | true |
9fb575247b44fd6cb944b68f0d077285dd80797f | AlyonaKlekovkina/JetBrains-Academy-Multilingual-Online-Translator | /translator.py | 275 | 4.125 | 4 | inp = input('Type "en" if you want to translate from French into English, or "fr" if you want to translate from English into French: \n')
word = input('Type the word you want to translate: \n')
print('You chose "{}" as the language to translate "{}" to.'.format(inp, word))
| true |
99b5e59a7ea63f7900a144b9540f48c241c9094a | 15johare/mockexam.py | /mockexam.py | 1,226 | 4.1875 | 4 | while True:
mood=input("choose what mood you are feeling")
print("this is a program that shows you what music to listen to depending on your mood")
print("all you have to do is type what mood you are and a link to a song will come up")
if mood=="happy":
print("https://www.youtube.com/watch?v=ZbZSe6N_BXs")
elif mood=="sad":
print("https://www.youtube.com/watch?v=aWIE0PX1uXk")
elif mood=="angry":
print("https://www.youtube.com/watch?v=77tvDMkc9eE&list=PLclxqlStifc4RjX5KM3NlIyn3RyN3aydk")
elif mood=="scared":
print("https://www.youtube.com/watch?v=e2vBLd5Egnk")
elif mood=="love":
print("https://www.youtube.com/watch?v=2Vv-BfVoq4g")
elif mood=="confusion":
print("https://www.youtube.com/watch?v=g2R0V-TgBY4")
elif mood=="heart break":
print("https://www.youtube.com/watch?v=GSBFehvLJDc")
elif mood=="ecstatic":
print("https://www.youtube.com/watch?v=nbH7SHKoZYY")
elif mood=="hyper":
print("https://www.youtube.com/watch?v=XbGs_qK2PQA")
elif mood=="jealous":
print("https://www.youtube.com/watch?v=50VWOBi0VFs")
elif mood=="lonely":
print("https://www.youtube.com/watch?v=50VWOBi0VFs")
else :
print("that is not a mood")
| true |
90f715e0e18587b6bc42fdf46e99e3fae7124666 | wisitlongsida1999/Project-Battleship.py | /battleship.py | 1,743 | 4.1875 | 4 | from random import randint
def print_board(board):
for row in board:
print(row)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
def play():
board = []
for x in range(0, 5):
board.append(["O"] * 5)
print_board(board)
ship_row = random_row(board)
ship_col = random_col(board)
for turn in range(4):
print("Turn : ",turn+1)
guess_row = input("Guess Row: ")
guess_col = input("Guess Col: ")
if guess_row == ship_row and guess_col == ship_col:
print( "Congratulations! You sank my battleship!")
break
elif guess_row == "#" and guess_col == "#":
print( "---------------Easter Egg!!!-------------------")
board[ship_row][ship_col]="#"
print_board(board)
break
else:
guess_row = int(guess_row)
guess_col = int(guess_col)
if (guess_row not in range(5) or guess_col not in range(5)):
print( "Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print( "You guessed that one already." )
else:
print( "You missed my battleship!")
board[guess_row][guess_col] = "X"
if (turn == 3):
print( "------------Game Over--------------")
print("Answer>>>>> Row is",ship_row,"Column is",ship_col)
board[ship_row][ship_col]="#"
print_board(board)
def main():
play()
while input("Play again ? (Y/N_) ").upper()== "Y":
play()
if (__name__=="__main__"):
main()
| false |
fd88fd1e55b79c6ef5e64f749c8255d2872dbfe8 | Anshikaverma24/if-else-meraki-ques | /if else meraki ques/q7.py | 314 | 4.21875 | 4 |
# take a number as input from the user. Convert this input to integer. Check if it is equal to varx.
# If the number is equal to varx, print "Equal" else print "Not equal".varx = 300 - 123
varx = 300 - 123
answer=int(input("enter the answer : "))
if answer==varx:
print("equal")
else:
print("not equal") | true |
a0f65d7e301ffaa85add12475cd8859afc18b095 | Anshikaverma24/if-else-meraki-ques | /if else meraki ques/q16.py | 281 | 4.1875 | 4 | # meraki debugging questions in if else
# number = input("please enter a decimal number")
# print ("your number divided by 2 is equal to = " + number/2)
# ANSWER
number = int(input("please enter a decimal number"))
print ("your number divided by 2 is equal to = ", + number/2) | true |
18a3633fd7a091250cee523189a7943a8de516a3 | tbaraza/Bootcamp_7 | /Day-3/data_types.py | 770 | 4.1875 | 4 | def data_type(x):
"""
Takes in an argument x:
- For an integer , return x ** 2
- For a float, return x/2
- For a string, returns "Hello " + x
- For a boolean, return "boolean"
- For a long, return squaroot of x
"""
if isinstance(x, int):
return x ** 2
elif isinstance(x, float):
return x / 2
elif isinstance(x, str):
return "Hello {}".format(x)
elif isinstance(x, bool):
return "boolean"
elif isinstance(x, long):
return "long"
else:
return "That'a not a primitive data type"
print data_type(24)
print data_type(25.67)
print data_type("Tonida")
print data_type(True)
print data_type(456 ** 456)
print data_type([2, 3])
| true |
9f4d6ae9ee32c1a152c1dca4a0ae343390637983 | shenbomo/LintCode | /Implement Queue by Stacks.py | 1,024 | 4.125 | 4 | """
As the title described, you should only use two stacks to implement a queue's actions.
The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
Example
For push(1), pop(), push(2), push(3), top(), pop(), you should return 1, 2 and 2
Challenge
implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.
"""
__author__ = 'Danyang'
class Queue:
def __init__(self):
self.stack1 = [] # for in
self.stack2 = [] # for out
def push(self, element):
self.stack1.append(element)
def top(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2[-1]
def pop(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
| true |
e25987866fe6ef5041487014192e412e58144749 | genrobaksel/Home_Work_2 | /Lesson3_part1/01_days_in_month.py | 938 | 4.40625 | 4 | # -*- coding: utf-8 -*-
# (if/elif/else)
# По номеру месяца вывести кол-во дней в нем (без указания названия месяца, в феврале 28 дней)
# Результат проверки вывести на консоль
# Если номер месяца некорректен - сообщить об этом
# Номер месяца получать от пользователя следующим образом
user_input = input("Введите, пожалуйста, номер месяца: ")
month = int(user_input)
full_days = 31
nofull_days = 30
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
print (full_days)
elif month == 4 or month == 6 or month == 9 or month == 11:
print (nofull_days)
elif month == 2:
print (28)
else:
print ('Вы ввели неизвестный месяц')
| false |
e317fdcd87ccf6f8fb70b3255b99862d615ca219 | Alexanra/graphs- | /Guess_my_number_working.py | 1,309 | 4.125 | 4 | print ("Please think of a number between 0 and 100!")
minimum = 0
maximum = 100
guess = minimum + (maximum-minimum)//2
print ("Is your secret number " + str(int(guess)) + "?")
ans = str (input("Enter 'h' to indicate the guess is too high. "+\
"Enter 'l' to indicate the guess is too low. "+\
"Enter 'c' to indicate I guessed correctly. "))
while guess > 0 and guess < 100:
if ans == "l":
minimum = guess
guess = minimum + (maximum-minimum)//2
print ("Is your secret number " + str(int(guess)) + "?")
ans = str (input("Enter 'h' to indicate the guess is too high. "+\
"Enter 'l' to indicate the guess is too low. "+\
"Enter 'c' to indicate I guessed correctly. "))
#print (ans)
elif ans == "h":
maximum = guess
guess = minimum + (maximum-minimum)//2
print ("Is your secret number " + str(int(guess)) + "?")
ans = str (input("Enter 'h' to indicate the guess is too high. "+\
"Enter 'l' to indicate the guess is too low. "+\
"Enter 'c' to indicate I guessed correctly. "))
#print (ans)
elif ans == "c":
print("Thanks for fun! Dzieki za zabawe!")
break
| true |
e17ad79242ce3fba5a259fa68d49436d210f2a41 | malarc01/Data-Structures | /binary_search_tree/Data Structures in Python- Singly Linked Lists -- Insertion .py | 1,353 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.data)
curr_node = curr_node.next
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
# if node already exist
print('SELF.HEAD', self.head)
last_node = self.head
print('last_node', last_node)
print('SELF.HEAD', self.head)
while last_node.next:
print('XLSOSO')
last_node = last_node.next
print('last_node.next', last_node.next)
last_node.next = new_node
print('last_node.next==>', last_node.next)
def prepend(self, data):
new_node = Node(data)
print(new_node)
print('self.head', self.head)
new_node.next = self.head
print('before self.head ==>', self.head)
self.head = new_node
print('after self.head ==>', self.head)
linked_list = LinkedList()
linked_list.append('Human')
linked_list.append('Pineapple')
# linked_list.append('Apple')
# linked_list.append('Banana')
# linked_list.prepend('Dog')
linked_list.print_list()
| true |
4ac0c78234417136cc65611724eb635eeb072b57 | ThakurSarveshGit/CrackingTheCodingInterview | /Chapter 1 Arrays and Strings/1_5.py | 779 | 4.21875 | 4 | # -*- coding: cp1252 -*- // What is this?
# Problem 1.5
# Write a method to replace all spaces in a string with %20.
# I doubt if any interviewer would give this question to be solved in python
# Pythonic Way
def replace(string):
modified_string = string.replace(" ", "%20")
print modified_string
return modified_string
replace("Afzal is Salman's big fan")
# Non-Pythonic Way
def replace_np(string):
to_find = " "
indices = [i for i, a in enumerate(string) if a == to_find]
count = 0
for ind in indices:
buf_str = string[:ind + count] + "%20" + string[ind + count + 1:]
count += 2
string = buf_str
print buf_str
return indices
replace_np("Afzal is Salman's big fan")
| true |
7dc54efd48efa8bd557e3171322479ce3e0bd98a | ThakurSarveshGit/CrackingTheCodingInterview | /Chapter 1 Arrays and Strings/1_2.py | 708 | 4.28125 | 4 | # -*- coding: cp1252 -*- # No clue why this came up :/
# Problem 1.2
# Write code to reverse a C-Style String.
#(C-String means that abcd is represented as five characters, including the null character.)
def reverse_in_c(string):
# Python Style of Reversing a string
Reverse_String_Python = string[::-1] # This contains the Null Character in the beggining
# Removing Null character from beginning and adding Null character at end
Reverse_String_C = Reverse_String_Python[1:] + '\0'
print Reverse_String_C
return Reverse_String_C
C_String1 = 'Afzal weighs 100 Kilos\0'
C_String2 = 'aBcD\0'
reverse_in_c(C_String1)
reverse_in_c(C_String2)
| true |
0ad19a3410b0ebd0a981474cc79da9305402b3b4 | rcisternas/PyhonEjercicios | /Factorial.py | 331 | 4.1875 | 4 | Numero = int(input("Ingrese Numero: "))
def Factorial(Number):
Numero_salida = 0
contador = 1
Numero_actual = 1
while (contador<=Number):
Numero_salida = contador*Numero_actual
contador+=1
Numero_actual = Numero_salida
return Numero_salida
print("El factorial es: ", Factorial(Numero)) | false |
1c6c4044f85036d9b81550ab031283a070c3e205 | Damishok/PP2 | /TSIS1/9.py | 573 | 4.25 | 4 | #1
fruits = ["apple", "banana", "cherry"]
print(fruits[1])
#2
fruits = ["apple", "banana", "cherry"]
fruits[0] = "kiwi"
#3
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
#4
fruits = ["apple", "banana", "cherry"]
fruits.insert(1,"lemon")
#5
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
#6
fruits = ["apple", "banana", "cherry"]
print(fruits[-1])
#7
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[2:5])
#8
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) | false |
c02cc82c080c24f7b9441c9fd7b4ea35a1f7c464 | Saptarshidas131/Python | /p4e/exercises/ex7_1.py | 470 | 4.40625 | 4 | """
Exercise 1: Write a program to read through a file and print the contents
of the file (line by line) all in upper case. Executing the program will
look as follows:
"""
filename = input("Enter filename: ")
# try opening file
try:
fileh = open(filename)
except:
print("Invalid filename ",filename)
exit()
# reading filedata
#data = fileh.read()
# reading data line by line and printing in uppercase
for line in fileh:
print(line.strip().upper())
| true |
ac308ee29c9e87118d51cb92273aa4fd0d2616f4 | Saptarshidas131/Python | /p4e/exercises/ex3_2.py | 663 | 4.125 | 4 | """
Exercise 2: Rewrite your pay program using try and except so that your
program handles non-numeric input gracefully by printing a message
and exiting the program. The following shows two executions of the
program
"""
# prompt for hours and rate per hour
try:
hours = float(input("Enter Hours: "))
rate = float(input("Enter Rate: "))
# check for overtime, if hours more than 40 add extra 1.5 times the hours
if hours > 40:
pay = (hours * rate) + (hours - 40)*1.5
# otherwise regular pay
else:
pay = hours * rate
print("Pay: " + str(pay))
except:
print("Error, please enter numeric input")
| true |
3c77543a0ab17cadcee5e91695ead226115b1f6e | rohitj205/Python-Basics-Code | /LOOPS.py | 2,096 | 4.34375 | 4 | #Loops
"for loop:"
#If we want to execute some action for every element present in some sequence
# (it may be string or collection)then we should go for for loop.
#Eg
#To Print Character represented in String
s = "Sachin Tendulkar"
for x in s:
print(x)
#For loop
exp = [2310,5000,2500,4500,4500]
total = 0
for item in exp:
total = total + item
print(total)
#Range Function
for i in range(1,101):
print(i*i)
#print the total using range function
exp = [1000,2000,3000,4000,5000]
total = 0
for i in range(len(exp)):
print("Month:",(i + 1),"Expense:",exp[i])
total = total + exp[i]
print("Total Expenses of all Month is ",total)
#Find the Key
key_location = "Car"
location = ["Garage","Key Stand","Chair","Closet","Car"]
for i in location:
if i==key_location:
print("Key is found in:",i)
break
else:
print("Key is not found in",i)
#print the sum of square of all numbers except even numbers
for i in range(1,6):
if i%2==0:
continue
print(i*i)
#while loop
i = 1
while i<=5:
print(i)
i=i+1
#Using for loop figure out count for “heads”.
result = ["heads","tails","tails","heads","tails","heads","heads","tails","tails","tails"]
count = 0
for item in result:
if item == "heads":
count += 1
print("Heads count: ", count)
#Your monthly expense list (from Jan to May)
#Write a program that asks you to enter an expense amount and program should tell youin which month that expense occurred.
# If expense is not found, then convey that as well
exp_list=[2340,2500,2100,3100,2980]
mon_list=["Jan","Feb","March","April","May"]
a=int(input("Enter the expense amount "))
for i in range(len(exp_list)):
if a!=exp_list[i]:
continue
else:
print("Expense of ",a,"occured in ",mon_list[i])
break
#Write a program that prints following shape, (Hint: Use for loop inside another for loop)
#*
#**
#***
#****
#*****
for i in range(1,6):
s = ' '
for j in range(i):
s += '*'
print(s) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.