blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
594e93c9222421af290b4bcb656d3be15e1bd40c | EmmanuelHePe/Notas_Python | /python Files/TdV.py | 615 | 4.3125 | 4 | #Siguiendo el tutorial de python
### Numeros ##############################################3
#Numeros inmaginarios
n = 7 + 6j
print(n.real)
print(n.imag)
print(abs(n))
#Quitar decimales
### CADENA DE CARACTERES ############################################3
Hola = "Que pedo morro \n como imprime esto"
print(Hola)
palabra = "Ayuda" + "B"
print(palabra*2)
print(palabra[2:5])a
x = len(palabra)
print("Hola")
### listas ############################################3
# Variable para guardar datos compuestos
a = ["pan","huevos", 100, 1024] #Diferentes tipos de datos
print(a)
| false |
f16880f9be84304c2c863b5f54ffa61657e5fa8c | hmtmcse-exp/python | /python/helper/klass_method/AClass.py | 843 | 4.375 | 4 |
class AClass(object):
"""In Python, a class may have several types of methods:
instance methods, class methods, and static methods
"""
def an_instance_method(self, x, y, z=None):
"""this is a function of the instance of the object
self is the object's instance
"""
return self.a_class_method(x, y)
@classmethod
def a_class_method(cls, x, y, z=None):
"""this is a function of the class of the object
cls is the object's class
"""
return cls.a_static_method(x, y, z=z)
@staticmethod
def a_static_method(x, y, z=None):
"""this is neither a function of the instance or class to
which it is attached
"""
return x, y, z
if __name__ == '__main__':
instance = AClass()
instance.an_instance_method('x', 'y')
| true |
4d25ffb468e2d40bd43c0fabffe5e172c0cd0a65 | KareliaConsolidated/Regular-Expressions | /06_Character_Ranges.py | 448 | 4.28125 | 4 | # Character Ranges
# We use metacharacter(-) which represents "Range of Characters"
# Includes all character between two characters
# Only a metacharacter inside a character set; a literal dash otherwise.
# [0-9]
# [A-Za-z]
### CAUTION ###
# [50-99] is not all numbers from 50 to 99, it targets one number at one time.
import re
pattern = '[0-9]'
word = re.findall(pattern, 'Call 911')
print([word[i] for i in range(len(word))]) # ['9', '1', '1'] | true |
62f4dbaf8e41b888046d75ed482f3fa90f5cf71f | jdemarc/100-days-of-code | /py-basics/challenges/arithmetic_ops.py | 719 | 4.28125 | 4 | '''
The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.
'''
def math_ops(a, b):
print(a + b)
print(a - b)
print(a * b)
'''
Print division and floor division.
'''
def division_func(a, b):
print(a // b)
print(a / b)
'''
The provided code stub reads and integer n from STDIN. For all non-negative integers i < n print i^2.
'''
def loops_func(n):
x = range(0, n-1)
for n in x:
print (n**2)
'''
Function calls
'''
math_ops(5, 9)
division_func(3, 5)
loops_func(6) | true |
e76a8e856e8d13b664d476f4c3ca3faf26883523 | mattbellis/Siena_College_Physics_2012_2013_Dark_matter_detection | /python_examples/conditionals_with_arrays.py | 824 | 4.21875 | 4 | import numpy as np
# Let me create an array with 20 random numbers between 0 and 10
x = 10*np.random.random(20)
print "Original x-array"
print x
# Suppose I want to create a new array where I find all the numbers in this
# x array that are below 5. Normally, you would loop over all the numbers
# and check their value. But with numpy arrays, there is an easier way.
# You can actually use that conditional as indexing!
xsubset = x[x<5]
print "\nOriginal x-array, but only the values < 5"
print xsubset
# But what if you want a slice of the numbers? Say, between 4 and 6?
# You can create an index for each conditional statement and then
# multiply them!
index0 = x>4
index1 = x<6
index = index0*index1
xslice = x[index]
print "\nOriginal x-array, but only the values where x>4 and x<6"
print xslice
print "\n"
| true |
7dfd6f5bbdf6760bacb276fc8d6256fe1ec6af84 | xuaijingwendy/sendmail | /xuaijing-29/python/f3.py | 266 | 4.25 | 4 | num=9
if num>=0 or num<=10:
print('hello')
else:
print('undefine')
num=10
if num<0 or num>10:
print('hello')
else:
print('undefine')
num=8
if (num>=0 and num<=5) or (num>=10 and num<=15):
print('hello')
else:
print('undefine') | false |
63c179c7d4dd7d6d35481d7fcb0c0ea2c43d7af9 | amygurski/python-learn-marathon | /Session 1/strings.py | 1,823 | 4.34375 | 4 | """
In this module we are going to be covering strings, string formatting and string manipulation.
This comment is a multiline string.
"""
# Single line string literal
first_string = "This is a simple string."
second_string = 'This is another string'
first_string = "This isn't important"
second_string = 'This contains "double" options'
third_string = "Double quotes can be escaped \" like this"
print(third_string)
fourth_string = "We have new lines here\nCheck us out"
print(fourth_string)
# Multiline string literal
multiline = """
This is a multiline string.
See it keeps going
La di da
"""
print(multiline)
# f-string and f-string formatting
number_of_ways = 4
print("f-string formatting. This is {} way.. But there are {} others. Like {}".format("one", "few", number_of_ways))
first_name = "this"
last_name = "person"
age = 20
print(f"We are looking at {first_name} {last_name} of {age} age")
print(f"They are {'young' if age < 30 else 'old'}")
# splitting a string
input = "Let's test this string with a bunch of words"
result = input.split(" ")
print(result[::2])
chat_command = "!alarm this is outrageous!!!"
tokens = chat_command.split(" ")
command = tokens[0]
print(command)
# joining a string
phrase = " ".join(tokens[1:]) #threw out index 0, joined the rest
print(phrase)
# stripping leading and trainling spaces
sample_str = " There are some spaces here before and after "
print(sample_str.strip())
# case manipulation
print(f"Is command !ALARM {tokens[0].upper() == '!ALARM'}")
print("!HALP".lower())
# let's build a random IP address
# goal eg. "127.234.20.129"
import random
#print(str(random.randint(100,255)) + "." + str(random.randint(100,255)) + "." + str(random.randint(0,99)) + "." + str(random.randint(100,255)))
print(".".join([str(random.randint(0,255)) for _ in range(4)]))
| true |
40e04abb985f1db3398d2603065af13e66f20f6d | LiuTianen/python_requrstDemo | /Csdn/XClock.py | 1,365 | 4.25 | 4 | # -*- encoding:utf-8 -*-
"""
3.1 线程锁 Lock
前几天,我想在一个几百人的微信群里统计喜欢吃苹果的人数。
有人说,大家从1开始报数吧,并敲了起始数字1,立马有人敲了数字2,3
。但是统计很快就进行不下去了,因为大家发现,有好几个人敲4,有更多的人敲5。
这就是典型的资源竞争冲突:统计用的计数器就是唯一的资源,很多人(子线程)都想取得写计数器的资格。
怎么办呢?Lock(互斥锁)就是一个很好的解决方案。
Lock只能有一个线程获取,获取该锁的线程才能执行,否则阻塞;执行完任务后,必须释放锁。
"""
import time
import threading
lock = threading.Lock() #创建互斥锁
counter = 0 #计数器
def hello():
"""线程函数"""
global counter
if lock.acquire(): #请求互斥锁,如果被占用,则阻塞,直至获取到锁
time.sleep(0.2)
counter += 1
print('我是第%d个'%counter)
lock.release() #释放互斥锁
def demo():
threads = list()
for i in range(30): #假设群里有30人,都喜欢吃苹果
threads.append(threading.Thread(target=hello))
threads[-1].start()
for t in threads:
t.join()
print('统计完毕,共有%d人'%counter)
if __name__ == '__main__':
demo() | false |
525396705756d4bcf6d30b576dd5df80b3fc07a3 | Farkyster/PythonClass | /movies.py | 433 | 4.28125 | 4 | ##Write a program that adds the movies above to a list names movies using a
#for loop and the new "movies" list, print the name and rating of the movie
movie_1 = ('Iron Man 3', 78)
movie_2 = ('The Great Gatsby', 48)
movie_3 = ('Star Trek Into Darkness', 90)
movie_4 = ('Oblivion', 56)
movies =[movie_1,movie_2,movie_3_,movie_4]
i =1
for movie in movies:
print movies[i][1] + " is rated " + movies[i][2] + "out of 100"
i++
| true |
6351aab6233438cf848001d348b3e19565fae2ff | artifex4847/Intro2Program | /lpthw/ex21.py | 992 | 4.40625 | 4 | # -*- coding: utf-8 -*-
'''
ex21.py
Functions Can Return Something
'''
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
'''
Key points:
1. A function can return an object, like number, string, and even function.
2. Treat a function like an expression, 1 + 1 gives 2, just like add(1, 1) here.
3. Do NOT move on until you fully understand this!
''' | true |
4e27992389716456cdb7c71cf3656c1b14f25025 | artifex4847/Intro2Program | /lpthw/ex20.py | 730 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
ex20.py
Functions and Files
'''
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
'''
Key points:
1. Function gives a name to a block of code.
2. You can reuse the block anytime.
''' | true |
54d43cf48438bd99ba536a37b7e7d63120f3a12c | lagerfeuer/AdventOfCode2019 | /day02/main.py | 2,234 | 4.125 | 4 | #!/usr/bin/env python3
from enum import Enum
from os.path import dirname
from os.path import join
class OpCodes(Enum):
ADD = 1
MUL = 2
HLT = 99
def read_input(file_name='input.txt'):
"""
Read input from file_name
"""
# always open relative to current file
file_name = join(dirname(__file__), file_name)
with open(file_name, 'r') as f_in:
input_list = f_in.read().split(',')
return list(map(int, input_list))
def run(program_in):
"""
An Intcode program is a list of integers separated
by commas (like 1,0,0,3,99).
To run one, start by looking at the first integer (called position 0).
Here, you will find an opcode - either 1, 2, or 99.
The opcode indicates what to do; for example,
99 means that the program is finished and should immediately halt.
Encountering an unknown opcode means something went wrong.
"""
program = program_in.copy()
pc = 0
while pc < len(program):
opcode = OpCodes(program[pc])
if opcode == OpCodes.HLT:
return program
op1 = program[program[pc + 1]]
op2 = program[program[pc + 2]]
dst = program[pc + 3]
func = None
if opcode == OpCodes.ADD:
func = lambda x, y: x + y
if opcode == OpCodes.MUL:
func = lambda x, y: x * y
program[dst] = func(op1, op2)
pc += 4
raise RuntimeError("Invalid opcode")
def part1():
"""
Solve the puzzle (part 1), given the input in input.txt
...before running the program,
replace position 1 with the value 12 and
replace position 2 with the value 2.
"""
program = read_input('input.txt')
program[1] = 12
program[2] = 2
return run(program)[0]
def part2():
"""
Solve the puzzle (part 2), given the input in input.txt
"""
program_in = read_input('input.txt')
OUTPUT = 19690720
for i in range(100):
for j in range(100):
program = program_in.copy()
program[1] = i
program[2] = j
if run(program)[0] == OUTPUT:
return 100 * i + j
if __name__ == '__main__':
print("Part 1:", part1())
print("Part 2:", part2())
| true |
a35407ca3287a702bf9ff03e0b5f9eb6f19a107e | gokulnippani/DataStructures | /Project_3/problem_2.py | 1,415 | 4.1875 | 4 | def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
return search(input_list,0,len(input_list)-1,number)
pass
def search(arr, l, h, key):
if l > h:
return -1
mid = (l + h) // 2
if arr[mid] == key:
return mid
if arr[l] <= arr[mid]:
if key >= arr[l] and key <= arr[mid]:
return search(arr, l, mid - 1, key)
return search(arr, mid + 1, h, key)
if key >= arr[mid] and key <= arr[h]:
return search(a, mid + 1, h, key)
return search(arr, l, mid - 1, key)
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
test_function([[-6, -7, -8, -1, -2, -3, -4], -1])
test_function([[], -1]) | true |
09003b1d3c99328ac225d6d9001b73fab2d52014 | BelangerAlexander/RandomProjects | /python/Random/Lab01AlexanderBelanger.py | 1,052 | 4.3125 | 4 | import random
def avgCounter(number, rangeBottom, rangeTop):
value = 0;
print("For ",number ,"numbers between ", rangeBottom, "and ", rangeTop, ":")
for i in range(0,number):
num = 0
num = random.randrange(rangeBottom, rangeTop +1)
if number < 10: # If the amount of numbers that needs to be generated exceeds 10, then skip listing them.
print("Number ", i+1, "is", num)
value+=num
print("The total is", value)
return value/number
def main():
print(avgCounter(5, 1, 20),"\n") # Average of 5 Random Numbers between 0 and 20
print(avgCounter(5, 50, 70),"\n")# Average of 5 Random Numbers between 50 and 70
print("Answering Question 3: The method I use now could be used to\ndo so, however it would be more efficient if I skipped printing\neach random number generated to the Shell. I did this as you can\nsee in the comments in the code. Below you see the 100 Number Generation Output.\n")
print(avgCounter(100, 1, 100),"\n")
if __name__ == '__main__':
main() | true |
ea85fccb37356164eab740868607ce9ea2a1f74d | subratcall/problem-solving-nov | /problems/28-FindingMajorityElement/solution.py | 624 | 4.15625 | 4 |
def find_major_element(array):
# below block of code finds a majority element
major_element = array[0]
count = 0
for i in range(len(array)):
if array[i] == major_element:
count += 1
else:
count -= 1
if count <=0:
major_element = array[i]
count = 1
# below block of verifies if majority element occures more than or equal n/2 times
if array.count(major_element)>=(len(array)/2):
return major_element
return -1
print(find_major_element([ 3, 10, 3, 2, 3, 5, 3, 1, 3, 4, 3, 10, 5, 3])) | true |
772c5930f86bba3cc5784fc3a8cdbfe6dcb476ec | DForshner/PythonExperiments | /summultipleof3or5.py | 607 | 4.4375 | 4 | #Multiples of 3 and 5
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
#The sum of these multiples is 23.
#
#Find the sum of all the multiples of 3 or 5 below 1000.
def multiple3or5(num):
if num % 3 == 0:
return True
elif num % 5 == 0:
return True
else:
return False
def sum_multiples_of_3or5(max_num):
total = 0
for i in range(1, max_num + 1):
if multiple3or5(i):
print("multiple: ", i)
total += i
print("Sum: ", total)
sum_multiples_of_3or5(9)
sum_multiples_of_3or5(999)
| true |
467105b3dd9b9d24b88fea9daa429ce994657c1f | ipbrennan90/machine-learning-udemy | /simple-linear-regression/simple_linear_regression.py | 1,285 | 4.125 | 4 | # Simple Linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LinearRegression
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3.0, random_state = 0)
#Fitting regressor object to training set
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#predicting test set results
#create a vector of predictions of test set salary values
#vectors of predictions of dependent variables (salary for this example)
y_pred = regressor.predict(X_test)
#visualizing the training set results
plt.scatter(X_train, y_train, color = "red")
plt.plot(X_train, regressor.predict(X_train), color="blue")
plt.title('Salary vs. Experience (training)')
plt.xlabel('years of experience')
plt.ylabel('salary')
plt.show()
plt.scatter(X_test, y_test, color = "red")
plt.plot(X_test, regressor.predict(X_test), color="blue")
plt.title('Salary vs. Experience (training)')
plt.xlabel('years of experience')
plt.ylabel('salary')
plt.show()
| true |
75cf40b59db7d0c4504e12b00798be6f55ed8c07 | dshmc/python | /OLD/Stepik/calc.py | 630 | 4.25 | 4 | num1 = float(input())
num2 = float(input())
action = input()
if action == '+':
print(num1+num2)
elif action == '-':
print(num1+num2)
elif action == '/' and num2 == 0:
print("Деление на 0!")
elif action == '/' and num2 !=0:
print(num1 / num2)
elif action == '*':
print(num1 * num2)
elif action == 'mod' and num2 ==0:
print("Деление на 0!")
elif action == 'mod' and num2 !=0:
print(num1 % num2)
elif action == 'pow':
print(num1 ** num2)
elif action == 'div' and num2 == 0:
print("Деление на 0!")
elif action == 'div' and num2 != 0:
print(num1 // num2)
| false |
b38b4b99a1c6be3c919542f518fe4190ceab320e | krishnasharma5547/Dictionary_python | /venv/Question_3.py | 376 | 4.28125 | 4 | states={"Rajasthan":101,"Haryana":102}
# Adding element to predefined dictionary =>>
states["Assam"] = 103
# Printing dictionary
print(states)
# printing non existing states code
print(states.get("UP"))
# adding another element
states["Goa"] = 104
# printing the dic....
print(states)
# use of setDefault to dictionary =>>
x = states.setdefault("Goa","104")
print(x)
| true |
ae0af2e999ea8c217b187efc4034fff0eb204cee | doctoryeo-code/python_practice | /dict.py | 311 | 4.21875 | 4 | thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x , "==>", thisdict[x])
thisdict["year"] = 1971
print(thisdict["year"])
if "model" in thisdict:
print("Yes, model is a key in thisdict")
if "smodel" in thisdict:
print("Yes, smodel is a key in thisdict")
| true |
87f418c6fef20843b880dd15a6217fdf8e31f617 | beckysx/python_basic | /数据类型转换&运算符/数据类型转换.py | 272 | 4.125 | 4 | """
int(x) x-> int
eval(str) 计算字符串中有效python表达式,并返回一个对象
tuple(s)
list(s)
float(x)
str(x)
"""
# eval()
str1 = '1'
str2 = '1.1'
str3 = '(1,2,3)'
str4 = '[1,2,3]'
str5 = str(["3","4","5"])
x =eval(str5)
print(type(x[2])) | false |
86ecb876cce967417ee4d0ae9320e466389d30b8 | beckysx/python_basic | /tuple&list/list修改.py | 327 | 4.4375 | 4 | """
1. 修改指定index数据
2. revers()
3. sort() reverse= Ture 降序 false 升序(默认)
"""
name_list = ['TOM', 'Lily', 'ROSE']
# 1
name_list[1] = 'LILY'
print(name_list)
# 2
list1 = [1, 3, 2, 5, 4, 9, 7]
list1.reverse()
print(list1)
# 3 sort()
list1.sort(key=None, reverse=True) # key用于dictionary
print(list1)
| false |
3edb1682493ba55b2aad19c900fc1dc444474566 | jkrsn98/cisc3160 | /l3/python-sorts/main.py | 1,080 | 4.34375 | 4 | def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr) - 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def insertion_sort(arr):
for i in range(len(arr)):
key = arr[i]
pos = i
while pos > 0 and arr[pos - 1] > key:
arr[pos] = arr[pos - 1]
pos = pos - 1
arr[pos] = key
return arr
def selection_sort(arr):
for i in range(len(arr)):
minimum = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[minimum]:
minimum = j
arr[minimum], arr[i] = arr[i], arr[minimum]
return arr
arr1 = [5,6,2,4,8,1]
arr2 = [6,2,6,4,5,5,1,2]
arr3 = [9,8,7,6,5,4,3,2,1]
print("arr before calling bubble_sort(arr):%s" %(arr1))
print("arr after calling bubble_sort(arr): %s" %(bubble_sort(arr1)))
print("arr before calling insertion_sort(arr):%s" %(arr2))
print("arr after calling insertion_sort(arr): %s" %(insertion_sort(arr2)))
print("arr before calling selection_sort(arr):%s" %(arr3))
print("arr after calling selection_sort(arr): %s" %(selection_sort(arr3)))
| false |
b54d8195a4c2ed429ec7369c59d670a5c1c88efd | DaijaStokes/JUMP-DaijaStokes | /D2 - 3 Functions - Exercises.py | 932 | 4.4375 | 4 | # -*- coding: utf-8 -*-
# 1
#Create a function to calculate the absolute value of a number without using the abs() function to calculate the absolute value for -9 and 7.2
# 2
# for the given data (20,30,40,50,100), create a function to calcuate the total/3
#note that all the calcualtions have to be done within the function
# 3
#create a function to work in range(43,60) such that if the number is <50, it prints out "LT_50" else it should print out (number+3)
#4
# create a functio which takes 2 inputs as num and x and do the following
#if num>=0 then calcuate num*x else num*x/2
#5 create a function to create a new list with only the nos which can be divided by 3 from the following list
li = [5, 7, 21, 99, 51, 62, 77, 27, 73, 61]
# 6
#create a function using lambda function to overwrite the following list with all the elements squared
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
| true |
1e181e7c2e57244e14390eb190e0fd5a7b7288c3 | joanga/python_fundamentals | /problem_set/week_1/day_2/ex_2_comparing_numbers.py | 564 | 4.28125 | 4 | #Write a script that takes two user inputted numbers and prints
#"The first number is larger" or "The second number is larger"
#depending on which is larger. (**Hint**: you'll need to use `input()` twice.)
user_number_1 = float(input('Enter a number to evaluate: '))
user_number_2 = float(input('Enter a second number to evaluate: '))
if user_number_1 > user_number_2:
print ('The first number is larger')
elif user_number_1 < user_number_2:
print ('The second number is larger')
elif user_number_1 == user_number_2:
print ('The numbers are equal')
| true |
e14a2eb93aff240e557df466cea722bd65e2e088 | joanga/python_fundamentals | /problem_set/week_1/day_2/ex_8_prime_number.py | 392 | 4.28125 | 4 |
my_num= int(input('Enter the a number to determine if it is prime: '))
if my_num == 1:
print ('The number is not prime')
elif my_num == 2 or my_num == 3:
print ('The number is prime')
else:
current = 2
while current < (my_num / 2) :
if my_num % current == 0:
print ('not prime')
quit()
current += 1
print ('The number is prime')
| true |
424fa9134cb9ac56c629318be37669c544ea1c81 | lyenliang/QuickbidScraper | /dataTypes/Date.py | 865 | 4.21875 | 4 | class Date(object):
year = '0'
month = '0'
day = '0'
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def display(self):
return self.year + '-' + self.month + '-' + self.day
# called when Date is printed
def __str__(self):
return self.display()
def __repr__(self):
return self.display()
def __eq__(self, other):
if type(other) != Date:
return self.display() == other
elif self.display() == other.display():
return True
else:
return False
def __cmp__ (self, other):
if self.year > other.year:
return 1
elif self.year < other.year:
return -1
else:
if self.month > other.month:
return 1
elif self.month < other.month:
return -1
else:
if self.day > other.day:
return 1
elif self.day < other.day:
return -1
else:
return 0
| false |
db33a8d32ccd065782595a17919f1c41da28da05 | baibuz/mult_table | /mult_table.py | 634 | 4.1875 | 4 | # The program reads in an integer number from command line,
# creates a multiplication table,
# and prints it
# Requires pandas and numpy modules installed
# by E. baibuz
import sys,os
sys.path.append(os.getcwd())
import module
from module import *
#Reading command line arguments
N = readin_integer(sys.argv)
print("Multiplication table for N = %i"%N)
# main program starts here
table = generate_mult_table(N)
#Uncomment next line if pandas is unavailable
#print(table)
#printing the table with pandas module
from pandas import DataFrame
df = DataFrame(table)
# print to a terminal
print(df.to_string(index = False, header=False))
| true |
00966e09d419ba3794b8072f27544dbad989f63e | kavishsanghvi/SSW567-WS-Triangle | /Triangle.py | 1,326 | 4.3125 | 4 | """
@author: kavishsanghvi
@purpose: to demonstrate a simple python program to classify triangles
"""
def classifyTriangle(a,b,c):
""" classify different types of triangle
:param a: The side of a triangle
:type a: float
:param b: The side of a triangle
:type b: float
:param c: The side of a triangle
:type c: float
:rtype: str
:return: str
"""
# require that the input values be >= 0 and <= 200
if a > 200 or b > 200 or c > 200:
return 'InvalidInput'
if a <= 0 or b <= 0 or c <= 0:
return 'InvalidInput'
# verify that all 3 inputs are integers
if not(isinstance(a,int) and isinstance(b,int) and isinstance(c,int)):
return 'InvalidInput'
# the sum of any two sides must be strictly less than the third side
# of the specified shape is not a triangle
if ((b + c) < a) or ((a + c) < b) or ((a + b) < c):
return 'NotATriangle'
# now we know that we have a valid triangle
if (a * a) + (b * b) == (c * c) or (b * b) + (c * c) == (a * a) or (c * c) + (b * b) == (a * a):
return 'Right'
if a == b and b == c and a == c:
return 'Equilateral'
elif a == b or b == c or a == c:
return 'Isosceles'
else:
return 'Scalene' | true |
eb2f653af97cdc67539bed13618079856081bffe | KnightChan/LeetCode-Python | /Sort List.py | 2,545 | 4.1875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
"""Sort a linked list in O(n log n) time using constant space complexity."""
#print(head)
return self.mergeList(head)
def mergeList(self, node):
#print('merge start', node)
snode = node
size = 0
lh = None
rh = None
while node is not None:
size += 1
tmp = node
node = node.next
if size % 2:
tmp.next = lh
lh = tmp
else:
tmp.next = rh
rh = tmp
#print('size = ', size)
#print("return: " + str(snode))
if size <= 1:
return snode
#print("lh : " + str(lh))
#print("rh : " + str(rh))
lres = self.mergeList(lh)
rres = self.mergeList(rh)
#print("lres : " + str(lres))
#print("rres : " + str(rres))
res = self.mergeSortedList(lres, rres)
#print('merge end', res)
return res
def mergeSortedList(self, lh, rh):
tlh = lh
#print('sorted list start')
while rh is not None:
if lh.val > rh.val:
tmpnode = rh
rh = rh.next
tmpnode.next = lh
lh = tmpnode
tlh = lh
continue
while lh.next is not None and lh.next.val < rh.val:
lh = lh.next
if lh.next is None and lh.val < rh.val:
lh.next = rh
break
tmpnode = rh
rh = rh.next
tmpnode.next = lh.next
lh.next = tmpnode
#print('sorted list end')
return tlh
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
#print("in str")
tmp = self
strs = []
while tmp.next is not None:
strs.append(str(tmp.val) + "->")
tmp = tmp.next
else:
strs.append(str(tmp.val) + ";")
return "".join(strs)
in0 = [1, 2, 4, 3, 2]
ins = [in0]
for tin in ins:
head = ListNode(0)
tail = head
for val in tin:
tail.next = ListNode(val)
tail = tail.next
ss = Solution()
print(len(tin), tin)
#print(head)
print(ss.sortList(head.next))
print() | true |
a97f2cd0bbbc7ccf70cb283284bda6d7eac27d96 | KnightChan/LeetCode-Python | /Partition List.py | 2,661 | 4.1875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
'''
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
'''
def two_list(head, x):
smallHead = ListNode(0)
smallTail = smallHead
largeHead = ListNode(0)
largeTail = largeHead
while head:
if head.val < x:
smallTail.next = head
smallTail = smallTail.next
head = head.next
smallTail.next = None
else:
largeTail.next = head
largeTail = largeTail.next
head = head.next
largeTail.next = None
smallTail.next = largeHead.next
return smallHead.next
def two_pointer(head, x):
dummyHead = ListNode(0)
dummyHead.next = head
small = dummyHead
while small.next and small.next.val < x:
small = small.next
nextsmall = small
while nextsmall.next:
while nextsmall.next and nextsmall.next.val >= x:
nextsmall = nextsmall.next
if not nextsmall.next:
break
t = nextsmall.next
nextsmall.next = nextsmall.next.next
t.next = small.next
small.next = t
small = t
return dummyHead.next
return two_pointer(head, x)
#return two_list(head, x)
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
# print("in str")
tmp = self
strs = []
while tmp.next is not None:
strs.append(str(tmp.val) + "->")
tmp = tmp.next
else:
strs.append(str(tmp.val) + ";")
return "".join(strs)
in0 = [1, 4, 3, 5, 2]
ins = [in0]
for tin in ins:
head = ListNode(0)
tail = head
for val in tin:
tail.next = ListNode(val)
tail = tail.next
ss = Solution()
print(len(tin), tin)
# print(head)
print(ss.partition(head.next, 3))
print() | true |
096b3d1f528aa92a3c4ab2722aaf8030c32cefac | BhumikaReddy/3GRM | /Academics/Sem1/bhumi pdfs/python/remaining_notes/_files/1_file.py | 797 | 4.5 | 4 | # filename : 1_file.py
# we specify the physical filename - the name by which the operating system
# know the file - in a function called open.
# we open file in different modes
# reading(r), writing(w), appending(a) ...
# we get a file handle as the result of opening.
# we use the file handle from that point onwards
"""
# gives a runtime error if the file does not exist and we try to open the file for reading
f = open("junk.txt", "r")
# FileNotFoundError: [Errno 2] No such file or directory: 'junk.txt'
"""
""""
# Let us an existing file for opening.
# An open file uses the resources of the operating system.
# We return the resources by calling a function called close on the open file handle.
f = open("t.txt", "r")
print(f, type(f)) # do not worry about this output!
f.close()
"""
| true |
e773f2fec1e56e098ff2e4a698ea2c3f1627b6e6 | BhumikaReddy/3GRM | /Academics/Sem1/bhumi pdfs/python/ cbt2/list_comp.py | 1,101 | 4.21875 | 4 | # file name: 1_list_comprehension.py
# list comprehension
# uses the set builder method to create a list
# [ <expr> for <variable> in <iterable> ]
l1 = [ 'hello' for x in range(5)]
print(l1) # [ 'hello', 'hello', 'hello', 'hello', 'hello' ]
# expr may depend on the variable
# squares of numbers from 1 to 5
l2 = [ x * x for x in range(5)]
print(l2)
# list of tuples having a number and its square
l3 = [ (x, x * x) for x in range(5)]
print(l3)
# list of strings and its length
a=['bangalore', 'mysore', 'hubballi', 'shivamogga']
l4 = [ (x, len(x)) for x in a]
print(l4)
# cartesian product
l5 = [ (x, y) for x in range(4) for y in range(4)]
print(l5)
# relation: partial order
l6 = [ (x, y) for x in range(4) for y in range(4) if x < y]
print(l6)
# convert all words to uppercase
# map
a = ['bangalore', 'mysore', 'hubballi', 'shivamogga' ]
b = [ x.upper() for x in a ]
print(b)
# filter
# find all words whose len exceeds 7
b = [ x for x in a if len(x) > 7]
print(b)
# convert all words to uppercase if len exceeds 7
# combine
b = [ x.upper() for x in a if len(x) > 7]
print(b)
| true |
ddbb54f7fe9402675045a564221ebc450eb9f3c6 | BhumikaReddy/3GRM | /Academics/Sem1/bhumi pdfs/python/remaining_notes/OO/1_inher.py | 1,286 | 4.46875 | 4 | # filename : 1_inher.py
# inheritance
# we have a class called the base class.
# We require another class which exhibits every behaviour of the base class
# and may have other behaviours or the behaviours could be different.
# such a class is called a derived class.
# We create the derived class to use the base class - called inheritance
# point in 2 dimension is a point in 3 dimension
class P2D:
def __init__(self, x, y):
self.x = x
self.y = y
def disp(self):
print ("x : ", self.x)
print ("y : ", self.y)
p2 = P2D(3, 4)
p2.disp()
"""
# P3D inherits from P2D
# an object of P3D gets everything P2D has
class P3D(P2D) :
def __init__(self, x, y, z):
P2D.__init__(self, x, y)
self.z = z
p3 = P3D(11, 12, 13)
p3.disp() # no function in the derived class; calls the base class function by default
print(isinstance(p3, P2D)) #True
"""
# P3D inherits from P2D
# an object of P3D gets everything P2D has
class P3D(P2D) :
def __init__(self, x, y, z):
P2D.__init__(self, x, y)
self.z = z
#overriding the base class function
def disp(self):
P2D.disp(self) # delegate work to the base class
print("z : ", self.z)
p3 = P3D(11, 12, 13)
p3.disp() # no function in the derived class; calls the base class function by default
print(isinstance(p3, P2D)) #True
| true |
233b9bb78a5c7f402b4771680cb367b33160376d | ammarshahin/LearningPython | /src/giraffeAcademy/BasicCalculator.py | 1,681 | 4.34375 | 4 |
# ************* Basic Calculator Program **************
# ******************* Factorial function ****************
def factorial(num):
if num > 0:
return factorial(num - 1) * num
return 1
def calc():
try:
operand1 = float(input("1st operand: "))
operation = input("Enter the operation needed ex(+,-,*,/,^,!): ")
except ValueError:
print("invalid Input")
return
if operation == "+":
operand2 = float(input("2nd operand: "))
result = operand1 + operand2
elif operation == "-":
operand2 = float(input("2nd operand: "))
result = operand1 - operand2
elif operation == "*":
operand2 = float(input("2nd operand: "))
result = operand1 * operand2
elif operation == "/":
operand2 = float(input("2nd operand: "))
try:
result = operand1 / operand2
except ZeroDivisionError as err: # save the error message in a string variable "err"
print(err)
result = False
elif operation == "^":
operand2 = float(input("2nd operand: "))
result = pow(operand1, operand2)
elif operation == "!":
result = int(factorial(operand1))
else:
result = False
if result == False:
print("invalid Input")
else:
print("result =", result)
calc()
#! notes : "pass" >> is used to The pass statement is used as a placeholder for future code.
#! When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed.
#! Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
| true |
1225d8e858e0c761c6d201305a1c321ac4c93b55 | ammarshahin/LearningPython | /src/giraffeAcademy/12thLesson.py | 317 | 4.25 | 4 | # ************* Lesson 12 **************
# ***** 2D Lists and Nested loops ******
number_grid = [ # 2D list
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10]
]
'''
print(number_grid[0][2]) # access the element
'''
for row in number_grid: # row is now a list of columns
for col in row:
print(col)
| false |
0e989c1cd4e959ff0f470f33ff27b17e07f35426 | olutoye1/CompSci201-Minor-Codes | /DistanceBetweenTwoPoints.py | 1,266 | 4.28125 | 4 | # File: hw5_part1.py
# Author: olutoye sekiteri
# Date: 4/7/17
# Section: 23
# E-mail: olutoye1@umbc.edu
# Description:
# this code solves for the distance of two points
###################################################
# getTupl() get all point values from user
# Input: none
# Output: tupl1; the first point user entered
# tupl2; the second point user entered
def getTupl():
x1=int(input("Please enter a value for x1: "))
y1=int(input("Please enter a value for y1: "))
x2=int(input("Please enter a value for x2: "))
y2=int(input("Please enter a value for y2: "))
tupl1=(x1,y1)
tupl2=(x2,y2)
return tupl1, tupl2
####################################################
# distance() calculate the distance between points
# Input: tupl1; the first point user entered
# tupl2; the second point user entered
# Output: total; the total distance
def distance(tupl1,tupl2):
total=(((tupl2[0]-tupl1[0])**2+(tupl2[1]-tupl1[1])**2))**.5
return total
def main():
print("This program will ask for two points, and")
print("will compute the distance between the two.")
tupl1,tupl2=getTupl()
total=distance(tupl1,tupl2)
print("the distance between",tupl1,"and",tupl2,"is",total)
main()
| true |
af6bead7f98784c0d3fffd7b1f1eda7bbe73cebe | zsalieva/Python-codes | /CharCount.py | 249 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
import os, sys
# Write a Python program which calculates number of characters
# in a given user input.
Characters ="Enter a character to count "
print(len(Characters))
print("Char Count completed!")
| true |
70bf209cb463e446d890ab383e4e95fd9af6d255 | zsalieva/Python-codes | /CalculateVolumes.py | 293 | 4.21875 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
import os, sys
# Write a program that calculates volume of a cylinder.
# V=πr2h 5
pi=3.14
radius=input("Enter the Radius")
height=input("Enter the height")
r=int(radius)
h=int(height)
V= pi*r*2*h
print('The Volume of given Cylinder equals ', V)
| true |
eae8ea4a0d9933c038057cc0d1a22d93e63d3c15 | royels/BeyondHelloWorld | /pythonsnippets/reverse.py | 297 | 4.25 | 4 |
def reversing(string):
ram = string[::-1]
return ram
def reverse2(string):
ram = ''
for char in reversed(string):
ram += char
return ram
if __name__ == "__main__":
param = raw_input("Enter some text : ")
print reversing(param)
print reverse2(param)
| true |
0d967b8aa2f9f5979a711912294c45d02e68650a | adityasharan01/coding-interview-patterns | /Data Structures in python/enumerate-in-python.py | 1,378 | 4.375 | 4 | The syntax of enumerate() is:
enumerate(iterable, start=0)
enumerate() Parameters
enumerate() method takes two parameters:
iterable - a sequence, an iterator, or objects that supports iteration
start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.
Return Value from enumerate()
enumerate() method adds counter to an iterable and returns it. The returned object is a enumerate object.
You can convert enumerate objects to list and tuple using list() and tuple() method respectively.
Example 1: How enumerate() works in Python?
grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)
print(type(enumerateGrocery))
# converting to list
print(list(enumerateGrocery))
# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))
Output
<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]
Example 2: Looping Over an Enumerate object
grocery = ['bread', 'milk', 'butter']
for item in enumerate(grocery):
print(item)
print('\n')
for count, item in enumerate(grocery):
print(count, item)
print('\n')
# changing default start value
for count, item in enumerate(grocery, 100):
print(count, item)
Output
(0, 'bread')
(1, 'milk')
(2, 'butter')
0 bread
1 milk
2 butter
100 bread
101 milk
102 butter
| true |
30e27c7e9b141e873322fa9a12ca9bdc1a176e0a | jaxin007/Study | /Python_OOP/6.py | 681 | 4.4375 | 4 | # Даны катеты прямоугольного треугольника. Найти его гипотенузу и площадь.
import math
num = int (input("Введите первый катет треугольника: "))
num_2 = int (input("Введите второй катет треугольника: "))
gypotenusa = math.sqrt(num**2 + num_2**2) #Вычисляем длину гипотенузы по формуле
print ("Длина гипеотенузы равна ", gypotenusa)
square = (num * num_2)/2 #Вычисляем площадь треугольника по формуле
print ("Площадь треугольника равна ", square) | false |
dfb4e41227b745a3f5dd63e8231cd23323a7b43a | jaxin007/Study | /Python_OOP/30.py | 687 | 4.21875 | 4 | # Дано действительное число х. Не пользуясь никакими другими арифметическими операциями, кроме умножения, сложения и вычитания, вычислить
# Разрешается использовать не более восьми операций.
def first():
x = int(input('Choose your x: '))
_2 = 2 * x
_3 = 3 * x**2
_4 = 4 * x**3
result = 1 - _2 + _3 - _4
return(result)
print(first())
def second():
x = int(input('Choose your x: '))
_2 = 2 * x
_3 = 3 * x**2
_4 = 4 * x**3
result = 1 + _2 + _3 + _4
return(result)
print(second()) | false |
d1004408bb1dcb69668ecd63a7cab834c0eca43b | lauracondon/pands-problem-sheet | /secondstring.py | 715 | 4.3125 | 4 | # secondstring.py
# This programs asks a user to input a string
# and then returns every second letter of it in reverse order
# Author: Laura Condon
# requests input from user
# and stores it as a variable
sentence = input("Please enter a sentence: ")
# slice the string, with a step value of -1 to reverse it [1]
backwardsSentence = (sentence[::-1])
# slice it again with a step value of 2
# to output every 2nd letter in the string [2]
print(backwardsSentence [::2])
# References
# [1] https://www.w3schools.com/python/python_howto_reverse_string.asp (accessed 03/02/2021)
# [2] https://stackoverflow.com/questions/20847205/program-to-extract-every-alternate-letters-from-a-string-in-python (accessed 03/02/2021)
| true |
293cb38c02964bfb458cbea2bc4b43f0f418ccbd | LynnDC/trigrams | /src/trigrams.py | 1,705 | 4.375 | 4 | """Makes a set of trigrams to create a new body of text
provided text file.
"""
import io
import random
import sys
def main(doc, x): # pragma: no cover
"""Open file, splits it, grabs the desired chunk
and makes a dictionary out of the words.
"""
with io.open(doc, encoding='utf-8') as open_file:
text = open_file.read().split()
text_dict = parse_words(text)
if x == 0:
return None
if x == 1:
print(random.choice(text))
return None
else:
generated_article = generate_article(text_dict, x)
print(' '.join(generated_article))
def parse_words(words):
"""Parse the text list into a dictionary.
"""
text_dict = {}
for i in range(len(words) - 2):
two_words = (' ').join(words[i: i + 2])
third_word = words[i + 2]
if two_words in text_dict.keys():
if not isinstance(text_dict[two_words], list):
text_dict[two_words] = [text_dict[two_words]]
text_dict[two_words].append(third_word)
else:
text_dict.setdefault(two_words, third_word)
return text_dict
def generate_article(dicty, x):
"""Generate a paragraph from startings words
and our dictionary from parse_words.
"""
paragraph = []
text_key = random.choice(list(dicty.keys()))
paragraph.extend(text_key.split())
for _ in range(0, x-2):
text_key = ' '.join(paragraph[-2:])
if isinstance(dicty[text_key], list):
paragraph.append(random.choice(dicty[text_key]))
else:
paragraph.append(dicty[text_key])
return paragraph
if __name__ == '__main__':
main(str(sys.argv[1]), int(sys.argv[2]))
| true |
ba2c8b4bd4d05598f5b6e338a5228f3107e9d4b2 | xme1ez/python | /basic/celsius_fahrenheit_converter.py | 433 | 4.5625 | 5 |
# function will convert temperature from celsius to fahrenheit or
# fahrenheit to celsius
# input:
# - temperature (int)
# - flag shows in which form the temperature is entered:
# - c - celsius
# - f - fahrenheit
def celsius_fahrenheit_converter(temperature, flag):
if flag == "c":
return (temperature * (9 / 5)) + 32
elif flag == "f":
return (temperature - 32) * (5 / 9)
else:
return -1
| true |
7d48fae4edcce96574acb7d9f7f19b608d5a3b51 | xme1ez/python | /basic/check_on_the_simplicity_of_the_number.py | 635 | 4.1875 | 4 | # Function for define if the number is a simple or not.
# This is the simplest method of define.
# First stage is to find square root of input number
# Second stage is through the loop calculate modulo of input number and
# each number from range(2, square_root+1)
# Input is a (int) number
# Output is boolean:
# True if input number is a simplest number
# False if not.
import math
def check_on_the_simplicity_of_the_number(number):
simplicity = True
square_root = math.ceil(math.sqrt(number))
for divider in range(2, square_root+1):
if number % divider == 0:
simplicity = False
break
return simplicity
| true |
5a88a03db42c490456ec31ceb18038b1adfd8bc0 | donaldrossberg/BSA---Programming-MB | /Python/temperature.py | 728 | 4.15625 | 4 | #...initialize looping variable, assume 'yes' as the first answer
continueYN = "y"
while continueYN == "y":
#...get temp from user
sDegreeF = input("Enter next temperature in degrees Farenheight (F):")
#...convert the users input to an int for math operations
nDegreeF = int(sDegreeF)
#...convert from Farenheight to Celcius
nDegreeC = (nDegreeF - 32) * 5 / 9
print("Temperature in degrees C is :", nDegreeC)
#...check for temp below freezing
if nDegreeC < 0:
print ("Pack long underwear!")
#...check for a hot day
if nDegreeF > 100:
print ("Don't forget lots of water!")
continueYN = input("Input another?")
# Exit the program | true |
a67d19e66efaa51db8888ed87588baba3c4013a3 | samarthsaxena/Python3-Practices | /Practices/linkedInLeraning/power_n_factorial.py | 760 | 4.375 | 4 | #!/usr/bin/env python3
def power(num,pwr):
"""
calculate the power of a number. If power is 0 then return 1
"""
if pwr is 0:
return 1
if pwr < 0 :
return "not supported by this function."
if num != 0 and pwr >= 0:
return num * power(num,pwr-1)
def factorial(num):
"""
calculate factorial of a +ve number
"""
if num <= 1:
return 1
if num > 1:
return num * factorial(num-1)
def main():
a = int(input('Value of a : '))
a_pow = int(input('Value of a_pow : '))
d = int(input('Value of d : '))
print('{} to the power {} is {}'.format(a,a_pow,power(a,a_pow)))
print('Factorial of {} is {}'.format(d,factorial(d)))
if __name__ == '__main__':
main()
| true |
c5187c4e4b2c755d9bfafc1929777d375239b1ec | samarthsaxena/Python3-Practices | /Practices/Dictionary - a key value pair- mutible/Dic_loop_through_keys_values.py | 552 | 4.46875 | 4 | student = {'name' : 'Samarth','age' : 25,'courses': ['Math','CompSci']}
#to know how many keys are there, simply use len method
print(len(student))
#to know all the keys
print(student.keys())
#to know all the values
print(student.values())
#to know keys and values together
print(student.items())
#looping through keys
for a in student:
print(a)
for a in student.keys():
print(a)
for b in student.values():
print(b)
#to loop through keys and corresponding values
for key, value in student.items():
print(key, value)
| true |
68eb0c9d3753992887630aa043328695a298adb8 | Uluturk0/Python_Week5 | /Uluturk_w5/Society.py | 1,430 | 4.59375 | 5 | '''
Developer: Ömer Ulutürk
Date: 04.03.2021
Purpose of Software: Reinforcement of learned Python Code and Self-improvement
---PROJECT---
Create the class Society with following information:
society_name,house_no_of_mem, flat, income
Methods :
- An __init__ method to assign initial values of society_name,house_no_of_mem, flat, income
- input_data() To read information from members
- allocate_flat() To allocate flat according to income using the below table.
- show_data() to display the details of the entire class.
Income Flat
>=25000 A Type
>=20000 and <25000 B Type
>=15000 and <20000 C Type
<15000 D Type
'''
class Society():
def __init__(self):
pass
def input_data(self):
self.society_name = input("Please enter society name:")
self.house_no_of_mem = input("Please enter member's house number:")
self.income = int(input("Please enter income:"))
def allocate_flat(self):
if self.income >=2500:
self.flat="A Type"
elif self.income >=2000:
self.flat ="B Type"
elif self.income >=1500:
self.flat ="C Type"
else:
self.flat ="D Type"
def show_data(self):
print(f"Society name is:{self.society_name}\nHouse no:{self.house_no_of_mem}\nIncome:{self.income}\nFlat:{self.flat}")
s1=Society()
s1.input_data()
s1.allocate_flat()
s1.show_data()
| true |
bb6f14e6d04b377f533dcbf9e2a4d42af50b6b7f | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter9-Objects-and-Classes/P9_26.py | 1,129 | 4.15625 | 4 | # Design a Customer class to handle a customer loyalty marketing campaign. After
# accumulating $100 in purchases, the customer receives a $10 discount on the next
# purchase. Provide methods
# • def makePurchase(self, amount)
# • def discountReached(self)
# Provide a test program and test a scenario in which a customer has earned a discount
# and then made over $90, but less than $100 in purchases. This should not result in a
# second discount. Then add another purchase that results in the second discount.
class Customer():
def __init__(self):
self._purchase = 0
self._total_purchases = 0
def get_purchase(self):
return self._purchase
def get_total_purchases(self):
return self._total_purchases
def make_purchase(self, amount):
if self.is_discount_reached() is True:
self._total_purchases += amount - 10
self._purchase = 0
else:
self._total_purchases += amount
self._purchase = 0
def is_discount_reached(self):
if self._purchase >= 100:
return True
return False
| true |
07fc6205efa53be927d1202a23963a9b57fe3991 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter6-Lists/P6.9.py | 490 | 4.4375 | 4 | # Write a function that reverses the sequence of elements in a list. For example, if you
# call the function with the list
# 1 4 9 16 9 7 4 9 11
# then the list is changed to
# 11 9 4 7 9 16 9 4 1
# FUNCTIONS
def reverse(list):
# http://stackoverflow.com/a/3705676
return list[::-1]
# main
def main():
exampleList = [ 1, 4, 9, 16, 9, 7, 4, 9, 11 ]
print("List", exampleList)
print("Reversed", reverse(exampleList))
# PROGRAM RUN
main() | true |
f35ba27e3cbd7ec46ba05eb22e780ce7bc3111c7 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter4-Loops/P4.14.py | 891 | 4.15625 | 4 | # Mean and standard deviation. Write a program that reads a set of floating-point data
# values. Choose an appropriate mechanism for prompting for the end of the data set.
# When all values have been read, print out the count of the values, the aver age, and
# the standard deviation.
# imports
from sys import exit
from math import sqrt
count = 0
sum = 0
sumSquares = 0
stop = False
while not stop:
try:
inputN = float(input("Value: "))
except ValueError:
stop = True
break
count += 1
sum += inputN
sumSquares += inputN * inputN
if count <= 2:
exit()
# calculate average
average = sum / count
# second term in the numerator
stdDevAvg = (sum * sum) / count
standDev = sqrt((sumSquares - stdDevAvg) / (count - 1))
print("There are %d value" % count )
print("The average is %f and the standard deviation is %f" % (average, standDev)) | true |
e6e3d5165a8fcf934e31eb22830a2be21ae0200c | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter3-Decisions/WorkedExample3.1.py | 559 | 4.34375 | 4 | # Your task is to extract a string containing the middle character from
# a given string. For example, if the string is "crate" , the result is the string "a" . However, if the
# string has an even number of letters, extract the middle two characters. If the string is "crates" ,
# the result is "at"
userInput = str(input("Enter a string: "))
position = len(userInput) // 2
if len(userInput) % 2 == 1 :
result = userInput[position]
else:
result = userInput[position - 1 ] + userInput[position]
print("The middle character(s) is/are:", result) | true |
d8efdfea7e4a8ee7d2029c733999b7ec1d79d423 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter6-Lists/P6.3.py | 1,062 | 4.1875 | 4 | # Write a program that adds all numbers from 2 to 10,000 to a list.
# Then remove the multiples of 2 (but not 2), multiples of 3 (but not 3),
# and so on, up to the multiples of 100. Print the remaining values.
# FUNCTIONS
def fillList(list):
for i in range(2, 10001):
list.append(i)
return list
def removeMultiples(list):
# for i in range(len(list) - 1, -1, -1):
# number = list[i]
# pop = False
# for j in range(100, 1, -1):
# if number != j:
# pop = True
# break
#
# if pop == True:
# list.remove(number)
for i in range(10000, 1, -1):
remove = False
for j in range(100, 1, -1):
if i != j and i % j == 0:
remove = True
if remove == True:
list.remove(i)
return list
# main
def main():
exampleList = []
exampleList = fillList(exampleList)
print("Before")
print(exampleList)
print("After")
print(removeMultiples(exampleList))
# PROGRAM RUN
main() | true |
a00582af6d26adc0749be64e93f2fce8a32436da | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter4-Loops/P4.12.py | 437 | 4.15625 | 4 | # Write a program that reads a word and prints all substrings, sorted by length. For
# example, if the user provides the input "rum" , the program prints
# r
# u
# m
# ru
# um
# rum
word = str(input("Enter a word: "))
wordLen = len(word)
subLen = 1
start = 0
for i in range(wordLen):
start = 0
while start + subLen <= wordLen:
print(word[start:start+subLen])
start += 1
subLen += 1 | true |
ee0d967a295d4da0958937b495213c758bae1fdb | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter5-Functions/P5.5.py | 647 | 4.34375 | 4 | # Write a function
# def repeat(string, n, delim)
# that returns the string string repeated n times, separated by the string delim . For
# example, repeat("ho", 3, ", ") returns "ho, ho, ho"
# FUNCTIONS
def repeat(string, n, delim):
result = ""
for i in range(n):
result += string + delim
# doesn't add a delimiter after the last string repetition
lenDelim = len(delim)
return result[:-lenDelim]
def main():
string = str(input("Enter a string: "))
n = int(input("How many times to repeat the string: "))
delim = str(input("Delimiter: "))
print(repeat(string, n, delim))
# PROGRAM RUN
main() | true |
3ce27e50fcefcc623d49f34ea8e47e11932fc7ce | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter6-Lists/P6.4A.py | 537 | 4.3125 | 4 | # Write list functions that carry out the following tasks for a list of integers. For each
# function, provide a test program.
# a. Swap the first and last elements in the list.
# FUNCTIONS
def swapFirst_and_Last(list):
# bubble sort
temp = list[0]
list[0] = list[-1]
list[-1] = temp
return temp
# main
def main():
exampleList = [ 5, 6, 7, 4]
print("Before the swap")
print(exampleList)
swapFirst_and_Last(exampleList)
print("After the swap")
print(exampleList)
# PROGRAM RUN
main() | true |
699223a1bdf9b662b901724e3fd6cebb6c105394 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter7-Files-and-Exceptions/P7.8.py | 642 | 4.53125 | 5 | # Write a program that replaces each line of a file with its reverse.
# For example, if you run
# python reverse.py hello.py
# then the contents of hello.py are changed to
# .margorp nohtyP tsrif yM #
# )"!dlroW ,olleH"(tnirp
# Of course, if you run Reverse twice on the same file, you get back the original file
# IMPORTS
from sys import argv
# FUNCTIONS
# main
def main():
filename = argv[1]
file = open(filename, "r")
reversedFile = ""
for line in file:
reversedFile += line[::-1]
file.close()
file = open(filename, "w")
file.write(reversedFile)
file.close()
# PROGRAM RUN
if __name__ == "__main__":
main()
| true |
4e34592068e487bd5c929dbc765584d328eb93ab | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter5-Functions/P5.23.py | 1,092 | 4.3125 | 4 | # Write a program that prints instructions to get coffee, asking the user for input
# whenever a decision needs to be made. Decompose each task into a function, for
# example:
# def brewCoffee() :
# print("Add water to the coffee maker.")
# print("Put a filter in the coffee maker.")
# grindCoffee()
# print("Put the coffee in the filter.")
# . . .
# FUNCTIONS
def grindCoffee():
choice = str(input("Grind the coffee?(Y/N) "))
if choice == "y" or choice == "Y":
print("Add beans to grinder")
print("Grind up coffee beans for 2 minutes")
def brewCoffee():
print("Switch the coffee maker on")
print("Wait for the water to run through")
def pourCoffee():
print("Get a mug")
print("Pour coffee in a mug")
def drinkCoffee():
print("Drink the coffee you just made")
# main
def main():
print("Add water to the coffee maker")
print("Put a filter in the coffee maker")
grindCoffee()
print("Put coffee in the filter")
brewCoffee()
pourCoffee()
drinkCoffee()
# PROGRAM RUN
main() | true |
f716956f99359f0ba43e26f7b6a832783570fdc7 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter4-Loops/P4.11.py | 1,289 | 4.125 | 4 | # Write a program that reads a word and prints the number of syllables in the word.
# For this exercise, assume that syllables are determined as follows: Each sequence of
# adjacent vowels a e i o u y , except for the last e in a word, is a syllable. However, if
# that algorithm yields a count of 0, change it to 1. For example,
# Word Syllables
# Harry 2
# hairy 2
# hare 1
# the 1
inputWord = str(input("Enter a word: "))
vowels = ('a','e','i','o','u','y','A','E','I','O','U','Y')
lastVowel = False
lastCons = False
currVowel = False
currCons = False
syllablesCount = 0
for i in range(len(inputWord)):
letter = inputWord[i]
if letter in vowels:
currVowel = True
currCons = False
else:
currVowel = False
currCons = True
if currCons == True and lastVowel == True:
syllablesCount += 1
lastVowel = currVowel
lastCons = currCons
lastStart = len(inputWord) - 1
lastEnd = len(inputWord)
last = inputWord[lastStart:lastEnd]
if last == "a" or last == "i" or last == "o" or last == "u" or last == "y" or last == "A" or last == "I" or last == "O" or last == "U" or last == "Y":
syllablesCount += 1
if syllablesCount == 0:
syllablesCount = 1
print("There are %d syllables" % syllablesCount) | true |
6486ee92be4556605acfc2d00201afeb492aa0c8 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter7-Files-and-Exceptions/P7.6.py | 800 | 4.28125 | 4 | # Write a program find.py that searches all files specified on
# the command line and prints out all lines containing a specified word.
# For example, if you call
# python find.py ring report.txt address.txt homework.py
# then the program might print
# report.txt: has broken up an international ring of DVD bootleggers that
# address.txt: Kris Kringle, North Pole
# address.txt: Homer Simpson, Springfield
# homework.py: string = "text"
# The specified word is always the first command line argument
# IMPORTS
from sys import argv
# FUNCTIONS
# main
def main():
wordToFind = argv[1]
for i in range(2, len(argv)):
filename = argv[i]
file = open(filename, "r")
for line in file:
if wordToFind in line:
print("%s: %s" % (filename, line))
# PROGRAM RUN
if __name__ == '__main__':
main() | true |
bb73b4a34e621e2271d23e7a1444436ad73a5123 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter4-Loops/P4.5.py | 845 | 4.375 | 4 | # Write a program that reads a set of floating-point values. Ask the user to enter the
# values, then print
# • the average of the values.
# • the smallest of the values.
# • the largest of the values.
# • the range, that is the difference between the smallest and largest.
inputN = float(input("Enter a number(0 to stop): "))
total = 0
count = 0
min = inputN
max = inputN
while inputN != 0.0:
total += inputN
count += 1
if inputN < min:
min = inputN
if inputN > max:
max = inputN
inputN = float(input("Enter a number(0 to stop): "))
if count == 0:
print("No numbers entered")
else:
average = total / count
print("Average", average)
print("Smallest:", min)
print("Biggest:", max)
range = max - min
print("Range between smallest and biggest:", range) | true |
7247889e3422c48446ceaee18b81f2618ada17a6 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter3-Decisions/P3.7.py | 668 | 4.53125 | 5 | # Write a program that reads in three integers and prints “in order” if they are sorted in
# ascending or descending order, or “not in order” otherwise. For example,
# 1 2 5 in order
# 1 5 2 not in order
# 5 2 1 in order
# 1 2 2 in order
number1 = float(input("Enter number one: "))
number2 = float(input("Enter number two: "))
number3 = float(input("Enter number three: "))
if (number1 < number2 < number3) or (number1 > number2 > number3)\
or (number1 <= number2 < number3) or (number1 < number2 <= number3)\
or (number1 >= number2 > number3) or (number1 > number2 >= number3):
print("In order")
else:
print("Not in order") | true |
468d1b989de401eeb7a67d50fd47e1f87c0612fc | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter5-Functions/P5.4.py | 599 | 4.34375 | 4 | # Write a function
# def middle(string)
# that returns a string containing the middle character in string if the length of string is
# odd, or the two middle characters if the length is even. For example, middle("middle")
# returns "dd"
# FUNCTIONS
def middle(string):
result = ""
posMiddle = int(len(string) / 2)
if len(string) % 2 == 0:
result = string[posMiddle - 1] + string[posMiddle]
else:
result = string[posMiddle]
return result
def main():
string = str(input("Enter a string: "))
print("Middle:", middle(string))
# PROGRAM RUN
main() | true |
a8f096723561bf101bab815cfbb258b81b7af43c | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter9-Objects-and-Classes/P9_14.py | 1,653 | 4.34375 | 4 | # Write functions
# • def sphereVolume(r)
# • def sphereSurface(r)
# • def cylinderVolume(r, h)
# • def cylinderSurface(r, h)
# • def coneVolume(r, h)
# • def coneSurface(r, h)
# that compute the volume and surface area of a sphere with a radius r , a cylinder with
# a circular base with radius r and height h , and a cone with a circular base with radius r
# and height h . Place them into a geometry module. Then write a program that prompts
# the user for the values of r and h , calls the six functions, and prints the results.
# IMPORTS
from math import sqrt
from math import pi
# FUNCTIONS
def sphere_volume(radius):
return 4/3 * pi * radius ** 3
def sphere_surface(radius):
return 4 * pi * radius ** 2
def cylinder_volume(radius, height):
return pi * radius ** 2
def cylinder_surface(radius, height):
return pi * radius ** 2 * 2 * pi * radius * height
def cone_volume(radius, height):
return 1/3 * pi * radius ** 2 * height
def cone_surface(radius, height):
return pi * radius ** 2 + pi * radius * sqrt(height ** 2 + radius ** 2)
# main
def main():
radius = input("Radius>")
height = input("Height>")
print("Sphere volume: {}".format(sphere_volume(radius)))
print("Sphere surface: {}".format(sphere_surface(radius)))
print("Cylinder volume: {}".format(cylinder_volume(radius, height)))
print("Cylinder surface area: {}".format(cylinder_surface(radius, height)))
print("Cone volume: {}".format(cone_volume(radius, height)))
print("Cone surface: {}".format(cone_surface(radius, height)))
# PROGRAM RUN
if __name__ == "__main__":
main()
| true |
3083793a1732d97620aae1a831f8fcfb339dfa67 | akrizma12/pythonProjects | /H1/htt2_6.py | 818 | 4.25 | 4 | print("Trying to divide 5 by 2", 5 % 2)
print("Trying to divide 5 by 2", 9 % 5)
print("Trying to divide 5 by 2", 15 % 12)
print("Trying to divide 5 by 2", 12 % 15)
print("Trying to divide 5 by 2", 6 % 6)
print("Trying to divide 5 by 2", 0 % 7)
try:
print("Trying to divide 5 by 2", 7 % 0)
except:
print("Attempt to 0 any number gives ZeroDivisionError. Please try to put any other number other than 0")
'''
/usr/bin/python2.7 /Users/a6003261/Documents/class/pythonProjects/H1/htt2_6.py
('Trying to divide 5 by 2', 1)
('Trying to divide 5 by 2', 4)
('Trying to divide 5 by 2', 3)
('Trying to divide 5 by 2', 12)
('Trying to divide 5 by 2', 0)
('Trying to divide 5 by 2', 0)
Attempt to 0 any number gives ZeroDivisionError. Please try to put any other number other than 0
Process finished with exit code 0
''' | true |
eadb61f486c8c8bd6bb818192078e14faf2369d1 | ArianaAhmadi/Algorithm-Assignment-1 | /main.py | 2,365 | 4.4375 | 4 | #P1
#print('Input a temperature in Fahrenheit')
#a=int(input())
#b=(a-32)*5/9
#print(b,"°C")
#I've printed a sentence that would ask the user to input a number in Fahrenheit. Then the number that they input would be (a-32)*5/9 which is the formula used to convert it into Celsius. Finally, the printed output would be the answer with °C symbol at the end to indicate the unit of the temperature.
#P2
#print("Print F to convert input into Fahrenheit or C to convert input into Celcius")
#a=input()
#if a=='C':
#print("Input temperature in Fahrenheit")
#a=int(input())
#print(round((a-32)*5/9,"°C"))
#else:
#print("Input temperature in Celcius")
#a=int(input())
#print(round((a* 9/5) + 32,"°F"))
#I've made an "IF" statement that asks the user to press C or F depending if they want their number to be converted into Celcius or Fahrenheit.Then the "IF" statement converts the input into Celcius if C is inputted or Fahrenheit in F is inputted.
#P3
#result=1
#a=input("Input words. Once done, press x to count the amount of words listed.")
#while True:
#a=input()
#if a=="x":
#b="You've typed "+ str(result) +" words"
#print(b)
#break
#elif a!="x":
#result+=1
#else:
#print()
#Since this question includes counting and adding things together, I used result=1 to initiate a starting point. A while loop was used inorder to create a loop when x is pressed the loop stops due to the break and if x isn't pressed, the user can keep on adding words.
#P4
#print("A numeric password is set, guess the password.")
#i= False
#while i==False:
#a=input()
#if a=="3458":
#i= True
#print('Correct')
#else:
#print('Try again')
#I used a "While loop" inorder for the loop to keep on going for the statement to be false until the loop ends and the answer is true. So, while the answer is false, the user can keep on trying until the statment is true, where the loop ends.
#P5
#print("Enter 10 numbers")
#a=int(input())
#b=int(input())
#c=int(input())
#d=int(input())
#e=int(input())
#f=int(input())
#g=int(input())
#h=int(input())
#i=int(input())
#j=int(input())
#l= a,b,c,d,e,f,g,h,i,j
#print(l, sep=',', end=' ')
#Once the user inputs 10 numbers from a-l, the numbers will then be put next to eachother by the veriable l that is assigned to keep everything next to each other and printed with a sep and an end.
| true |
2f3c0925357d7d1869d7315b1c70f655cbaeb51d | bvermeulen/Django | /howdimain/utils/plogger.py | 2,460 | 4.125 | 4 | from functools import wraps
import logging
import time
''' plogger is a module with logging tools which can be either called directly
or to be used as decorators
timed - logs the time duration of a decorated function
func_args - logs the arguments (*args, **kwargs) and results of a
decorated function
'''
class Logger:
@classmethod
def set_logger(cls, log_file, logformat, level):
''' set the logger parameters
'''
cls.logger = logging.getLogger(__name__)
formatter = logging.Formatter(logformat)
cls.logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(level)
file_handler.setFormatter(formatter)
cls.logger.addHandler(file_handler)
return cls.logger
@classmethod
def getlogger(cls):
return cls.logger
# def timed(logger):
# ''' decorator object to log time of a function
# '''
# def _timed(func):
# """This decorator prints the execution time for the decorated function."""
# @wraps(func)
# def wrapper(*args, **kwargs):
# start = time.time()
# result = func(*args, **kwargs)
# end = time.time()
# logger.info("{} ran in {}s".format(func.__name__,
# round(end - start, 3)))
# return result
# return wrapper
# return _timed
def parameterized(decorator_func):
def layer(*args, **kwargs):
def replace_func(func):
return decorator_func(func, *args, **kwargs)
return replace_func
return layer
@parameterized
def timed(func, logger):
"""This decorator logs the execution time for the decorated function."""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
logger.info(f'==> {func.__name__} ran in {round(end - start, 3)} s')
return result
return wrapper
@parameterized
def func_args(func, logger):
"""This decorator logs the arguments for the decorated function."""
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
logger.info('\n==>{0}: arguments: {1}, key arguments: {2}\n'
'==>{0}: result: {3}'.
format(func.__name__, args, kwargs, result))
return result
return wrapper
| true |
24600ba4d31477a375979241ed0d9d28bf4de1f7 | k3ll3x/python-scripts | /advance_calculator.py | 1,334 | 4.3125 | 4 | # Script of Advance Calculator using Python using regexp module
# importing the regexp module
import re
# salutation and providing termination condition.
print("Welcome! I am your Advance Calculator.")
print("Type 'quit' to terminate.\n")
#declaring global variables
previous_value = 0
flag = True
# Defining non parametrized function to perform all the operations.
def calculate():
global flag
global previous_value
equation = ""
# Taking input from the user.
if previous_value == 0:
equation = input("Give me something to calculate:")
else:
equation = input(str(previous_value))
# Termination step.
if equation == 'quit':
print("You exit.")
print("See you next time.")
flag = False
else:
equation = re.sub('[a-zA-z,.:()" "]', '', equation)
# For security point of view here we eliminate all the letters and keep only numerical characters, if entered by the user.
# Calculating the results.
if previous_value == 0:
previous_value = eval(equation)
else:
previous_value = eval(str(previous_value) + equation)
# Calling the function within the infinite loop.
# On execution will continue to calculate until the user enters 'quit' .
while flag:
calculate()
#end of the script
| true |
d4f7734f82788efedeb733a68e3875f985c06c6a | mehrotra-prateek/exercism-python | /yacht/yacht.py | 1,528 | 4.125 | 4 | """
This exercise stub and the test suite contain several enumerated constants.
Since Python 2 does not have the enum module, the idiomatic way to write
enumerated constants has traditionally been a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a common practice to export both constants and functions that work with
those constants (ex. the constants in the os, subprocess and re modules).
You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type
"""
from collections import Counter
# Score categories.
# Change the values as you see fit.
YACHT = (lambda dice: 50 if len(Counter(dice).values()) == 1 else 0)
ONES = (lambda dice: 1*Counter(dice)[1])
TWOS = (lambda dice: 2*Counter(dice)[2])
THREES = (lambda dice: 3*Counter(dice)[3])
FOURS = (lambda dice: 4*Counter(dice)[4])
FIVES = (lambda dice: 5*Counter(dice)[5])
SIXES = (lambda dice: 6*Counter(dice)[6])
FULL_HOUSE = (
lambda dice: sum(dice)
if sorted(Counter(dice).values()) == [2, 3] else 0)
FOUR_OF_A_KIND = (
lambda dice: 4*Counter(dice).most_common(1)[0][0]
if Counter(dice).most_common(1)[0][1] >= 4 else 0)
LITTLE_STRAIGHT = (lambda dice: 30 if sorted(dice) == [1, 2, 3, 4, 5] else 0)
BIG_STRAIGHT = (lambda dice: 30 if sorted(dice) == [2, 3, 4, 5, 6] else 0)
CHOICE = (lambda dice: sum(dice))
def score(dice, category):
try:
return category(dice)
except Exception:
print("Invalid dice input. It must be a list with 5 integers")
| true |
1a1a04342cbeb6f1d93bfbe3ceed5970a5af42a7 | ritesh-deshmukh/Algorithms-and-Data-Structures | /TTech/factorial.py | 329 | 4.21875 | 4 | def fact_recursion(n):
if n == 1 or n == 0:
return 1
return n*fact_recursion(n-1)
print(f"Factorial using Recursive approach: {fact_recursion(4)}")
def fact_iterative(n):
res = 1
for i in range(1,n+1):
res *= i
return res
print(f"Factorial using Iterative approach: {fact_iterative(4)}")
| false |
97909fcde200ab7d70148fe8d70ffa94da008473 | ritesh-deshmukh/Algorithms-and-Data-Structures | /Daily Coding Problem/Problem #6.py | 1,156 | 4.1875 | 4 | # An XOR linked list is a more memory efficient doubly linked list.
# Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node.
# Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index.
#
# If using a language that has no pointers (such as Python),
# you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses.
#
# class Node(object):
# def __init__(self, data):
# self.data = data
# self.next = None
# self.previous = None
# self.xor = None
#
# class DLL(object):
# def __init__(self):
# self.head = None
#
# def insert(self, data):
# new_node = Node(data)
# new_node.next = self.head
#
# self.head = new_node
#
# def traverse(self):
# temp = self.head
# while temp:
# print(temp.data)
# temp = temp.next
#
# dll = DLL()
# dll.insert(1)
# dll.insert(2)
# dll.insert(3)
# dll.insert(4)
#
# dll.traverse()
| true |
70c0e9dd62f19d0f43ab900c22a155a17a568890 | ritesh-deshmukh/Algorithms-and-Data-Structures | /180Geeks/Arrays/Sorting Elements of an Array by Frequency.py | 718 | 4.21875 | 4 | # Given an array of integers, sort the array according to frequency of elements.
# For example, if the input array is {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}, then modify the array to {3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}.
# If frequencies of two elements are same, print them in increasing order.
arr = [2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12]
size = len(arr)
def freq(size, arr):
freq_dict = {}
for i in range(size):
if arr[i] not in freq_dict:
freq_dict[arr[i]] = arr.count(arr[i])
# print(freq_dict)
sorted_freq_dict = sorted(freq_dict.items(), key=lambda x: x[1])[::-1]
for key, value in sorted_freq_dict:
print([key]*value, end=" ")
# print(freq_dict)
freq(size,arr) | true |
74de2b82f7fc6ad9c2ce9a29409a20ba6bafc6f1 | ritesh-deshmukh/Algorithms-and-Data-Structures | /180Geeks/Strings/Implement strstr.py | 499 | 4.21875 | 4 | # Your task is to implement the function strstr.
# The function takes two strings as arguments(s,x) and locates the occurrence of the string x in the string s.
# The function returns and integer denoting the first occurrence of the string x .
str1 = "dtrfyguhjiokp"
str2 = "rfy"
def strstr(str1, str2):
if str2 in str1:
print(f"Found '{str2}' in '{str1}' at position: {str1.find(str2)+1}")
else:
print("Not found")
print(f"Find '{str2}' in '{str1}'")
strstr(str1,str2) | true |
a1a9aabdef46c1da971212cc26ab4c760f4a3a4e | ritesh-deshmukh/Algorithms-and-Data-Structures | /180Geeks/Arrays/Relative Sorting.py | 1,235 | 4.28125 | 4 | # Given two array A1[] and A2[],
# sort A1 in such a way that the relative order among the elements will be same as those in A2.
# For the elements not present in A2. Append them at last in sorted order.
# It is also given that the number of elements in A2[] are smaller than or equal to number of elements in A1[] and A2[] has all distinct elements.
# Input: A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
# A2[] = {2, 1, 8, 3}
# Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}
arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]
arr2 = [2, 1, 8, 3]
print(f"Given array 1: {arr1}")
print(f"Given array 2: {arr2}")
def relative_sorting(arr1,arr2):
# answer = [] * len(arr1)
temp = []
for i in range(len(arr1)):
if arr1[i] in arr2 and arr2.count(arr1[i]) < 2:
arr2.insert(arr2.index(arr1[i]),arr1[i])
# del arr1[i]
for i in range(len(arr1)):
if arr1[i] not in arr2:
temp.append(arr1[i])
# print(f"Temp array: {temp}")
temp.sort()
# print(f"Sorted temp: {temp}")
# print(f"Original first array: {arr1}")
# print(f"Second array after insertion: {arr2}")
print(f"Relative sorting of Array 1 and Array 2: {arr2 + temp}")
relative_sorting(arr1,arr2) | true |
fed3a395a10ee52c787a457c5d81e683f2370e9c | ritesh-deshmukh/Algorithms-and-Data-Structures | /180Geeks/Strings/Longest Distinct characters in string.py | 485 | 4.3125 | 4 | # Given a string, find length of the longest substring with all distinct characters.
# For example, for input "abca", the output is 3 as "abc" is the longest substring with all distinct characters.
word = "abcavnmx"
def longest_distinct(word):
count = 0
distinct = []
word = list(word)
for i in range(len(word)):
if word[i] not in distinct:
distinct += word[i]
else:
distinct += " "
print(distinct)
longest_distinct(word) | true |
3b1f2c05e929cf913b911aeb386b26ab18cf78c1 | ritesh-deshmukh/Algorithms-and-Data-Structures | /180Geeks/Arrays/temp.py | 2,421 | 4.25 | 4 | # Problem Statement
# You and your friends are visiting an amusement park. Everyone wants to ride the most famous attraction, the world's slowest roller coaster. There is a minimum height and a maximum height to be allowed on the ride. Your task is to count the number of people who will be able to go on the roller coaster.
#
# Implement the method countRiders. The method has three parameters: heights, minHeight, and maxHeight. heights is an array of integers containing the heights of the people who want to go on the ride. minHeight is the minimum height allowed on the ride, inclusive. maxHeight is the maximum height allowed on the ride, inclusive. The method should return the number of people able to go on the ride.
#
#
# Constraints
# heights contains between 0 and 100 elements
# minHeight ≤ maxHeight
# Examples
# heights = {32, 10, 91, 40}
# minHeight = 10
# maxHeight = 50
# Output: 3
# heights = [32, 10, 91, 40]
# minHeight = 10
# maxHeight = 50
def count_riders(heights, minHeight, maxHeight):
# Implement this function
count = 0
for i in range(len(heights)):
if heights[i] <= maxHeight and heights[i] >= minHeight:
count += 1
return count
# print(count_riders(heights,minHeight,maxHeight))
if __name__ == '__main__':
heights = [32, 10, 91, 40]
minHeight = 10
maxHeight = 50
answer = count_riders(heights, minHeight, maxHeight)
print("My answer: %s" % answer)
print("Expected answer: %s" % 3)
# from __future__ import print_function
#
# def g_a(n):
# return n * (n-1) // 2
#
#
# def g_b(n):
# return (n-1) * n // 2
#
# def f(n):
# return (g_a if n % 2 else g_b)(n)
#
# if __name__ == '__main__':
# print(f(4))
# def add_args(one,two):
# x1 = [two/one]
#
# def closure():
# three = 15
# four = three * 2
#
# x1[0] = 5 + four
#
# print(x1[0], " ", end='')
#
# closure()
# print(x1[0])
#
# def main():
# add_args(10,20)
# main()
#
import sys
# def main():
# sysPrinters = {}
# for i in range(1,4):
# sysPrinters[i] = "printer" + str(i)
#
# for keys in sysPrinters:
# print(sysPrinters[keys]),
#
# return 0
#
# main()
def main():
tampa = "tampa"
florida = "florida"
tampa = tampa[3: 5] + tampa[2]
co = florida.find(tampa[1])
florida = tampa + florida[co: co + 1]
print(florida)
main() | true |
3453d80e97e4dbea5ca5d388c95557e3c492375e | ritesh-deshmukh/Algorithms-and-Data-Structures | /180Geeks/Strings/Check if string is rotated by two places.py | 828 | 4.15625 | 4 | # Given two strings, the task is to find if a string ('a') can be obtained by rotating another string ('b') by two places.
# Input : a = "amazon"
# b = "azonam" // rotated anti-clockwise
# Output : 1
#
# Input : a = "amazon"
# b = "onamaz" // rotated clockwise
# Output : 1
a_str = "amazon"
b_str = "zonama"
a = list(a_str)
b = list(b_str)
count = 0
def check(a,b, count):
len_a = len(a)
len_b = len(b)
for i in range(len_a):
if a == b:
if len_b-count == 2:
print(f"Rotated by {len_b-count} places in clockwise pattern")
else:
print(f"Rotated by {len_b-count} places in clockwise pattern")
else:
b.insert(len_b+1, b.pop(i))
count += 1
check(a,b,count)
return
check(a,b,count)
| true |
fc8a61113ad4eb6aa291f88b44402e065aef1a6a | iharnoor/PythonicPrograms | /addArray.py | 792 | 4.1875 | 4 | """
Problem: To add one to the last element of the array just like addition of whole numbers
for example: [1,3,4,5] +1 changes to [1,3,4,6]
"""
# Case 1: [1,3,4]->[1,3,4]
# Case 2: [1,9,9]->[2,0,0]
# Case 3: [9,9,9]->[1,0,0,0]
# Assumptions: that any element in an array ranges from 0 to 9
def addArray(array):
carry = 1
sum = 0
for i in range(len(array) - 1, -1, -1):
sum = array[i] + carry
if sum == 10:
carry = 1
else:
carry = 0
array[i] = sum % 10
if carry == 1:
newArray = array
newArray.append(0)
newArray[0] = carry
array = newArray
return array
print('Array1: ', addArray([1, 9, 9, 9]))
print('Array2: ', addArray([9, 9, 9, 9]))
print('Array3: ', addArray([1, 3, 4]))
| true |
f938aa6fe99540405e97792ba4b8e04057a6487e | jaywonhan0111/wave-3 | /wave 3-4 python file.py | 355 | 4.125 | 4 | def shipping_calculator(num_items):
if num_items > 0:
return 10.95 +(num_items - 1) * 2.95
else:
return 0
def main():
num_items = int(input("Enter the number of items for shipping"))
fee = shipping_calculator(num_items)
print("Shipping charge: " + str(fee))
if __name__ == "__main__":
main()
| true |
64cf24375672a98d22db4fbc7e60e05a78f5f590 | sninala/Python-Programming | /Programs/general_examples/StringOperations.py | 777 | 4.125 | 4 | S = 'SPAM'
print S.find('pa') # returns -a
print S.find('PA') # returns index of matched character_size
print S.rstrip()
print S.replace('PA', 'XX')
print S ## immutable
print S.split(',')
print S.isdigit()
print S.lower()
print S.endswith('AM')
print S.endswith('am')
print S.encode('latin-1')
## iterate through string
for char in S:
print char
print [c*2 for c in S] ## list comprehension
### indexing and slicing
###X[I:J:K] --> extract all the items in X, from offset I through J-1, by K.
S = 'abcdefghijklmnop'
print S[1:10:2]
S = 'hello'
print S[::-1] ## String reversal
print S[5:1:-1]
print ord('s') ## convert a single character to its underlying ASCII integer
print chr(115) ## an ASCII integer code and converting it to the corresponding character | true |
0d3b73b1e63fb54c6f0584f96d5b93d8c7ad35bc | sninala/Python-Programming | /Programs/data_structures/searching_sorting/MergeSort.py | 1,197 | 4.15625 | 4 | def mergeSort(items):
'''
--divide and conquer strategy
recursive algorithm that continually splits a list into half
If the list is empty or has one item, it is sorted by definition
If the list has more than one item, we split the list and recursively invoke a merge sort on both halves.
Once the two halves are sorted, the fundamental operation, called a merge, is performed.
'''
totalElements = len(items)
if(totalElements > 1):
mid = totalElements//2
lefthalf = items[:mid]
righthalf = items[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i,j,k = 0, 0, 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
items[k] = lefthalf[i]
i += 1
else:
items[k] = righthalf[j]
j += 1
k += 1
while i < len(lefthalf):
items[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
items[k]=righthalf[j]
j=j+1
k=k+1
return items
items = [15, 70, 23, 44, 16, 99, 66, 32]
print mergeSort(items) | true |
6b7b30edcae98799e30dc389762ad007a0e2e3fb | galoscar07/college2k16-2k19 | /1st Semester/Fundamentals of Programming /Lecture/Code/14-ExistingDataTypes.py | 433 | 4.25 | 4 | '''
Created on Nov 1, 2016
@author: Arthur
'''
'''
We define two list objects!
- list is a predefined data type in Python
- list is implemented as a class!
'''
list_one = [1,2,3]
list_two = [4,5,6]
'''
The 'append()' method is called on the 'list_one' object
- list has a __init__ method
- list has an 'append' method (and many more!)
'''
list_one.append(5)
print(list_one)
print(list_two)
| true |
05d4262e9daaf2e41c722866efdd0031014e3944 | galoscar07/college2k16-2k19 | /1st Semester/Fundamentals of Programming /Lecture/Code/ex31_search.py | 2,910 | 4.21875 | 4 | '''
Created on Dec 16, 2016
@author: Arthur
'''
'''
1. Example of a class that overloads '==' operator.
This allows using Python's inbuilt 'in' syntax
'''
class IDObject:
'''
Base class that we use to demonstrate overloading '=='
'''
def __init__(self, objectId):
self._id = objectId
def getID(self):
return self._id
def __eq__(self, o):
return type(o) == type(self) and o._id == self._id
'''
2. We have a few derived classes
'''
class Car(IDObject):
def __init__(self, carId, make, model):
IDObject.__init__(self, carId)
self._make = make
self._model = model
def __str__(self):
return str(self._id) + " " + str(self._make) + " " + str(self._model)
def __repr__(self):
return str(self)
class Student(IDObject):
def __init__(self, studentId, name):
IDObject.__init__(self, studentId)
self._name = name
def __str__(self):
return str(self._id) + " " + self._name
def __repr__(self):
return str(self)
'''
3. Let's test how the '==' operator works
'''
def testEquals():
c1 = Car(1, "Dacia", "Sandero")
c2 = Car(1, "Dacia", "Logan")
c3 = Car(2, "Dacia", "Lodgy")
s1 = Student(1, "Anna")
s2 = Student(1, "John")
s3 = Student(2, "Maria")
print(c1 == c1)
print(s1 == s1)
print(c1 == c2)
print(c1 == c3)
print(s1 == s2)
print(s1 == s3)
print(c1 == s1)
print(c1 == s3)
'''
4. Let's test how the 'in' operation works
'''
def testIn():
c1 = Car(1, "Dacia", "Sandero")
c2 = Car(1, "Dacia", "Logan")
c3 = Car(2, "Dacia", "Lodgy")
s1 = Student(1, "Anna")
s2 = Student(1, "John")
s3 = Student(2, "Maria")
cars = [c1, c2, c3, s1]
print(c1 in cars)
print(s2 in cars)
print(s3 in cars)
'''
5. An example of an iterable collection that wraps a list
'''
class MyCollection:
def __init__(self):
self._data = []
def add(self, o):
self._data.append(o)
def __iter__(self):
'''
Return an iterator
'''
self._iterPoz = 0
return self
def __next__(self):
'''
Returns the next element of the iteration
'''
if self._iterPoz >= len(self._data):
raise StopIteration()
rez = self._data[self._iterPoz]
self._iterPoz = self._iterPoz + 1
return rez
def testInCollection():
c1 = Car(1, "Dacia", "Sandero")
c2 = Car(2, "Dacia", "Logan")
c3 = Car(3, "Dacia", "Lodgy")
c4 = Car(4, "Dacia", "Duster")
collection = MyCollection()
collection.add(c1)
collection.add(c2)
collection.add(c3)
'''
This calls the __next__ method until StopIteration() is raised
'''
for c in collection:
print (c)
print(c3 in collection)
print(c4 in collection)
testInCollection()
| true |
66c844c12575be6b358f96f4214ff2461f73570d | dhananjaymehta/Algo-DS | /Solutions/binarytree.py | 1,650 | 4.1875 | 4 | # Implementing a simple Binary Tree
# Insert between existing node and root.
class Tree():
def __init__(self,nums):
self.val=nums
self.left=None
self.right=None
def getleft(self):
return self.left
def getright(self):
return self.right
def insert_left(self,val):
if self.left == None:
self.left=Tree(val)
else:
tree=Tree(val)
tree.left = self.left
self.left = tree
def insert_right(self,val):
if self.right == None:
self.right=Tree(val)
else:
tree=Tree(val)
tree.left=self.right
self.right = tree
def inorder(self,root,res):
if root != None:
self.inorder(root.left,res)
res.append(root.val)
#print(root.val)
self.inorder(root.right,res)
return res
def preorder(self,root,res):
if root!= None:
res.append(root.val)
self.preorder(root.left, res)
self.preorder(root.right, res)
return res
def postorder(self, root, res):
if root != None:
self.postorder(root.left, res)
self.postorder(root.right, res)
res.append(root.val)
return res
def testTree():
myTree = Tree(1)
myTree.insert_left(2)
myTree.insert_right(3)
myTree.insert_right(4)
myTree.insert_left(5)
myTree.insert_left(6)
myTree.insert_right(9)
print(myTree.inorder(myTree,[]))
print(myTree.preorder(myTree, []))
print(myTree.postorder(myTree, []))
# call the function
testTree() | true |
1429852e7cb7fefd4fd92a7fdcac21885ae196cf | Jrive204/cs-sprint-challenge-hash-tables | /hashtables/ex4/ex4.py | 805 | 4.1875 | 4 | def has_negatives(a):
# dict to hold all numbers in `a`
storage = {}
# arr to return matches
result = []
# loop through each num in arr
for num in a:
# if the num has a corresponding number in the dict
if storage.get(
abs(num)): # The abs() function is used to return the absolute value of a number.get method returns the value for the given key
# check if they add to 0
if (storage.get(abs(num)) + num) == 0:
# if it does, add to match list
result.append(abs(num))
else:
# if no value is found, pass num as new key along with it's value
storage[abs(num)] = num
return result
if __name__ == "__main__":
print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
| true |
c0299790a5c37a4dbd589543ed51d243c0f0ac5f | SanjogitaMishra/leetcode-challenges | /Flatten a Multilevel Doubly Linked List.py | 1,595 | 4.28125 | 4 | """
QUESTION:
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer,
which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own,
and so on, to produce a multilevel data structure, as shown in the example below.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
Example 1:
Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
"""
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
"""
:type head: Node
:rtype: Node
"""
pointer = head
while pointer and not pointer.child:
pointer = pointer.next
if pointer:
# find child tail and connect with rest head if it exists
child_tail = pointer.child
while child_tail.next:
child_tail = child_tail.next
rest_head = self.flatten(pointer.next)
if rest_head:
child_tail.next = rest_head
rest_head.prev = child_tail
child_head = self.flatten(pointer.child)
pointer.next = child_head
child_head.prev = pointer
pointer.child = None
return head
| true |
eb983be20281d9c297a992159178ccba589a5e09 | pdhhiep/Computation_using_Python | /r8lib/r8_pythag.py | 802 | 4.15625 | 4 | #!/usr/bin/env python
def r8_pythag ( a, b ):
#*****************************************************************************80
#
## R8_PYTHAG computes sqrt ( A^2 + B^2 ), avoiding overflow and underflow.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 25 July 2014
#
# Author:
#
# John Burkardt
#
# Reference:
#
# The SLATEC library
#
# Parameters:
#
# Input, real A, B, the values for which sqrt ( A**2 + B**2 )
# is desired.
#
# Output, real VALUE, the value of sqrt ( A**2 + B**2 ).
#
from math import sqrt
a = abs ( a )
b = abs ( b )
if ( b < a )
value = a * sqrt ( 1.0 + ( b / a ) * ( b / a ) )
elif ( b == 0.0 )
value = 0.0
elif ( a <= b )
value = b * sqrt ( 1.0 + ( a / b ) * ( a / b ) )
return value
| true |
ad784b38987933d939bc780a9bd28701fc66a9d7 | ThomasTourrette/PythonCrashCourse | /classeTest.py | 1,017 | 4.125 | 4 | #!/usr/bin/env
# A class
class Dog():
""" Class representing a dog """
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
""" Simulating a dog sitting in response to a command """
print(self.name + " is now sitting.")
def roll_over(self):
""" Simulating rolling over in response to a command """
print(self.name + " rolled over !")
my_dog = Dog("joe", 10)
my_dog.sit()
my_dog.roll_over()
# Inheritance
class YellowDog(Dog):
def __init__(self, name, age, master, color="yellow"):
super().__init__(name, age)
self.color = color
self.master = master
def print_infos(self):
print(self.name.title() + " appartient à " + master.name.title())
class Master():
def __init__(self, name, age):
self.name = name
self.age = age
master = Master("john", 30)
yellow_dog = YellowDog("Yellow", 20, master)
yellow_dog.sit()
yellow_dog.roll_over()
yellow_dog.print_infos()
| false |
d57ff303ec02cb2dd0417082f34064744c98dca9 | harry7potter/Python_Learning | /usingFunc.py | 256 | 4.21875 | 4 | def find(num):
# code logic here
numtype = "odd"
if num%2 == 0:
numtype="even"
return numtype
num = int(input('Enter the number: '))
numtype = find(num)
print('Given number is',numtype)
| true |
28f5e6ebe4aefb1af74c221ebad5f4978f87ebc3 | sophcarr/comp110-21f-workspace | /exercises/ex07/data_utils.py | 2,458 | 4.25 | 4 | """Utility functions."""
__author__ = "730320301"
from csv import DictReader
def read_csv_rows(filename: str) -> list[dict[str, str]]:
"""Read the rows of a csv into a 'table'."""
result: list[dict[str, str]] = []
file_handle = open(filename, "r", encoding="utf8")
csv_reader = DictReader(file_handle)
for row in csv_reader:
result.append(row)
file_handle.close()
return result
def column_values(table: list[dict[str, str]], column: str) -> list[str]:
"""Produce a list[str] of all values in a single column."""
result: list[str] = []
for row in table:
item: str = row[column]
result.append(item)
return result
def columnar(row_table: list[dict[str, str]]) -> dict[str, list[str]]:
"""Transform a row-oriented table to a column-oriented table."""
result: dict[str, list[str]] = {}
first_row: dict[str, str] = row_table[0]
for column in first_row:
result[column] = column_values(row_table, column)
return result
def head(table: dict[str, list[str]], N: int) -> dict[str, list[str]]:
"""Making a column-based table with only the first N rows of data for each column."""
result: dict[str, list[str]] = {}
i: int = 0
for column in table:
row: list[str] = []
if len(table) >= N:
while i < N:
row.append(table[column][i])
i += 1
result[column] = row
i = 0
else:
result = table
return result
def select(table: dict[str, list[str]], hello: list[str]) -> dict[str, list[str]]:
"""Selecting specific columns."""
result: dict[str, list[str]] = {}
for column in hello:
result[column] = table[column]
return result
def concat(a: dict[str, list[str]], b: dict[str, list[str]]) -> dict[str, list[str]]:
"""Combining two dictionarires."""
result: dict[str, list[str]] = {}
for column in a:
result[column] = a[column]
for column in b:
if column in result:
result[column] += b[column]
else:
result[column] = b[column]
return result
def count(hi: list[str]) -> dict[str, int]:
"""Number of times a value appeared in input list."""
result: dict[str, int] = {}
i: int = 0
while i < len(hi):
if hi[i] in result:
result[hi[i]] += 1
else:
result[hi[i]] = 1
i += 1
return result
| true |
e6558e194a42fe26c743a8af2578cc6b641b9eb3 | GruposTEC/TC1028.413 | /Examen/test1.py | 1,558 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 09:45:50 2020
@author: Cronoxz05
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 09:19:39 2020
@author: Cronoxz05
"""
def main():
"""
recibe Velocidad y lo convierte a entero
-------
lo manda a la funcion y al regresar imprime la multa
"""
velocidad=input()
velocidad=int(velocidad)
multa=calculo_multa(velocidad)
print(multa)
def calculo_multa(a):
"""
Parameters
----------
a : TLa velocidad
Regresa el numero 0, 1, 2 dependiendo su velocidad
-------
int
primero declaramos las fuinciones x y y, despues lo mandamos a ver si el cumpleaños es verdadero
si lo es se le agregan a los valores de x y y 5 para que asi este al mismo nivel del cumpleaños
despues de esto solo se calcula cual seria la mumlta
"""
x=60
y=80
if a== True:
if a<= x+5:
return 0
elif a>x+5 and a<=y+5:
return 1
else:
return 2
else:
if a<=x:
return 0
elif a>x and a<y:
return 1
else:
return 2
main()
#primero pones la velocidad, despues pones el condicional if para saber si es su cumpleaños
#despues si es su cumpleaños entonces hacer las deciciones con un rango de 5 km/h mayor
#sino hacer las deciciones con los valores originales
| false |
a4411ffa4b37195e9b1ac7eb0e01f9f7437f36b2 | brysonreece/pycaesar | /pycaesar/caesar.py | 1,993 | 4.4375 | 4 | # create a searchable array of a common 26-letter alphabet
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# define our encryption function with two arguements: the plain text and number of letters to shift by
def encrypt(plaText, shift):
# an empty variable to hold our encrypted text until completion
encryptedText = ""
# an empty variable to hold our encrypted characters which will be appended to our result
appendLetter = ""
# cycles through every character in our provided plain text
for character in plaText:
# checks if said character is a letter in the alphabet
if character in alphabet:
# makes the letter lowercase to ensure it stays within the alphabet array
character = character.lower()
# takes the current letter position and transforms it to the new encrpyted position
currentPosition = alphabet.index(character)
newPosition = (currentPosition + shift) % len(alphabet)
# holds the encrpyted letter that is going into our 'encryptedText' variable
appendLetter = alphabet[newPosition]
# if character is NOT a letter, don't encrpyt it (e.g !@#$%^&*())
else:
appendLetter = character
# appends the character to our result
encryptedText += appendLetter
# returns our encrypted text
return encryptedText
# the exact same as our above function except that we negatively transform
# our encrypted text along the alphabet array instead of positively, therefore
# decrypting the text. Essentially we're encrypting our text in the the reverse order.
def decrypt(encText, shift):
decryptedText = ""
appendLetter = ""
for character in encText:
character = character.lower()
if character in alphabet:
currentPosition = alphabet.index(character)
newPosition = (currentPosition - shift) % len(alphabet)
appendLetter = alphabet[newPosition]
else:
appendLetter = character
decryptedText += appendLetter
return decryptedText
| true |
b22ca34bd30a7ceaa678d572f40c67c5a8c55482 | dinabseiso/HW10 | /len_.py | 392 | 4.15625 | 4 | #! /usr/bin/env python
#
### Imports go here
### Body goes here:
"""The len_list() function works for counting
the length of a list, a string, a tuple, a dictionary!
"""
def len_list(l):
count = 0
for i in l:
count += 1
return count
## Define main() here:
def main():
print len_list(["s", "o", "n"])
print len_list("blah")
## Bootstrap here:
if __name__ == "__main__":
main() | true |
69f322f434fa4e6b0cb2d9a75d5999471d753ba3 | SageChang/Python-Learning | /Python-Exercises/demo0001.py | 735 | 4.34375 | 4 | # 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
import random
str = ''
list_1 = []
for i in range(97,123):
list_1.append(chr(i))
for j in range(48,57):
list_1.append(chr(j))
for k in range(65,90):
list_1.append(chr(k))
str = str.join(list_1)
series_set_final = []
def random_series(len = 10):
series = ''
series_set = []
for i in range(0, len):
series += random.choice(str)
if series not in series_set:
series_set.append(series)
series_set_final.append(series_set[-1])
for i in range(0,200):
random_series()
print(series_set_final)
| false |
12a09e466529dec49a12d72834079de67ff37249 | SrilekhaSundara-git/Srilekha | /learn-to-code-with-python-incomplete/07-Strings-Methods/vowel_count.py | 543 | 4.4375 | 4 | # Define a vowel_count function that accepts a string argument.
# The function should return the count of vowels in the string.
# The 5 vowels are "a", "e", "i", "o", and "u".
# You can assume the string will be in all lowercase.
def vowel_count(param):
vowels = "aeiou"
#for vowel in vowels:
# print(vowel, param.lower().count(vowel))
return sum([param.lower().count(vowel) for vowel in vowels])
#
# EXAMPLES:
print(vowel_count("estate")) #=> 3
# vowel_count("helicopter") => 4
# vowel_count("ssh") => 0 | true |
78412c1c93e7bbee36d05c6d9a61fd3f0cd888b7 | SrilekhaSundara-git/Srilekha | /learn-to-code-with-python-incomplete/07-Strings-Methods/find_my_letter.py | 462 | 4.5 | 4 | # Define a find_my_letter function that accepts two arguments: a string and a character
# The function should return the first index position of the character in the string
# The function should return a -1 if the character does not exist in the string
def find_my_letter(param1,param2):
return param1.find(param2)
#
# EXAMPLES:
find_my_letter("dangerous", "a") # => 1
# find_my_letter("bazooka", "z") => 2
# find_my_letter("lollipop", "z") => -1 | true |
a0a80fe08e5cda45491b7b94514b0b596e83002e | SrilekhaSundara-git/Srilekha | /Python_Challenges/Classic Problems/recurssion/fib_series.py | 291 | 4.28125 | 4 | def fib_series(n:int)->int:
"""This is a recursive function
to find the Fibonacci series of a number
n:int fib(n) = fib(n - 1) + fib(n - 2)"""
if n <2:
return n
else:
return fib_series(n - 2) + fib_series(n - 1)
help(fib_series)
print(fib_series(5)) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.