blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7a0a5f7926f661bdb3061cdad7f232473a5e2a47 | cyjhunnyboy/PythonTutorialProj | /pers/cyj/day07/04-异常处理/异常处理.py | 2,233 | 4.28125 | 4 | """
需求:当程序遇到问题时不让程序结束,而越过错误继续向下执行
try.....except.....else
格式:
try:
语句t
except 错误码 as e:
语句1
except 错误码 as e:
语句2
.....
except 错误码 as e:
语句n
else:
语句e
注意:else语句可有可无
作用:用来检测try语句块中的错误,从而让except语句捕获错误信息并处理
逻辑:当程序执行到try...except...else语句时
1、如果当try"语句t"执行出现错误或异常,会匹配第一个错误码,如果匹配上就执行对应的"语句"
2、如果当try"语句t"执行出现错误,没有匹配的异常,错误将会被提交到上一层的try语句,或者到程序的最上层
3、如果当try"语句t"执行没有出现错误,不会匹配任何异常,执行else下的"语句e"(你得有)
"""
try:
# print(3 / 0)
print(3 / 1)
# print(name)
print("程序出错,词句不会被打印到控制台输出!")
except NameError as e:
print("没有该变量")
except ZeroDivisionError as e:
print("除数为0了")
else:
print("代码没有问题!")
print("*******************")
# 使用except而不适用任何的错误类型
try:
# print(4 / 0)
print(name)
except:
print("程序出现了异常!")
print("*******************")
# 使用except带着多种异常
try:
print(4 / 0)
print(name)
except (NameError, ZeroDivisionError) as e:
print("出现了NameError或ZeroDivisionError")
print("*******************")
# 特殊
# 1、错误其实class(类),所有的错误都继承自BaseException,所以在捕获异常的时候,它捕获了该类型的错误,还把子类一网打尽
try:
print(5 / 0)
except BaseException as e:
print("异常1")
except ZeroDivisionError as e:
print("异常2")
print("*******************")
# 2、跨越多层调用,main调用了func2,func2调用func1,func1出现了错误
# 这时只要main捕获到了就能处理
def func1(num):
print(1 / num)
def func2(num):
func1(num)
def main():
func2(0)
try:
main()
except ZeroDivisionError as e:
print("除数为0了")
print("*******************")
| false |
e2428d1972b286b13755a7f534ddca4d2ac8459d | cyjhunnyboy/PythonTutorialProj | /pers/cyj/day04/02-list(列表)/list列表方法.py | 2,271 | 4.25 | 4 | # 列表方法
# append 在列表中的末尾添加新的元素
list1 = [1, 2, 3, 4, 5]
list1.append(6)
print(list1)
list1.append([7, 8, 9])
print(list1)
# extend 在末尾一次性追加另一个列表中的多个值
list2 = [1, 2, 3, 4, 5]
list2.extend([6, 7, 8])
# TypeError: 'int' object is not iterable
# list2.extend(9)
print(list2)
# insert 在下标处添加一个元素,不覆盖原数据,原数据向后顺延
list3 = [1, 2, 3, 4, 5]
list3.insert(1, 100)
print(list3)
list3.insert(2, [6, 7, 8])
print(list3)
# pop(x=list[-1]) 移除列表中指定下标处的元素(默认移除最后一个元素),并返回删除的数据
# 表示列表的最后一个下标
list4 = [1, 2, 3, 4, 5]
list4.pop()
print(list4)
list4.pop(2)
print(list4)
list4.pop(-1)
print(list4)
print(list4.pop(1))
# remove 移除列表中的某个元素第一个匹配的结果
list5 = [1, 2, 7, 3, 6, 4, 9, 4, 5, 6, 4]
list5.remove(4)
print(list5)
# clear 清除列表中所有的数据
list6 = [1, 2, 3, 4, 5]
list6.clear()
print(list6)
# index 从列表中找出某个值的第一个匹配的索引值
list7 = [1, 2, 3, 4, 5, 3, 6, 3]
index7_1 = list7.index(3)
print(index7_1)
# 圈定查找元素的范围(开始查找的位置、查找的结束位置)
index7_2 = list7.index(3, 3, 7)
print(index7_2)
# 列表中元素的个数
list8 = [1, 2, 3, 4, 5]
print(len(list8))
# 获取列表中的最大值
list9 = [1, 2, 3, 4, 5]
print(max(list9))
# 获取列表中的最小值
list10 = [1, 2, 3, 4, 5]
print(min(list10))
# 查看元素在列表中出现的次数
list11 = [1, 2, 3, 4, 5, 1, 3, 2, 3, 5, 6, 3, 3, 9]
print(list11.count(3))
num11 = 0
all = list11.count(3)
while num11 < all:
list11.remove(3)
num11 += 1
print(list11)
# reverse 倒叙
list12 = [1, 2, 3, 4, 5]
list12.reverse()
print(list12)
# 排序 升序
list13 = [1, 4, 3, 7, 9, 2, 5, 6, 8]
list13.sort()
print(list13)
# 拷贝
# 浅拷贝
list14 = [1, 2, 3, 4, 5]
list15 = list14
list14[1] = 200
print(list14)
print(list15)
print(id(list14))
print(id(list15))
# 深拷贝(内存的拷贝)
list16 = [1, 2, 3, 4, 5]
list17 = list16.copy()
list17[1] = 300
print(list16)
print(list17)
print(id(list16))
print(id(list17))
# 将元组转成列表
list18 = list((1, 2, 3, 4, 5))
print(list18)
| false |
0ab40b89d111ba1fdd7c3ebdd813b5d21ceb0272 | cyjhunnyboy/PythonTutorialProj | /pers/cyj/day06/01-set/set.py | 1,436 | 4.21875 | 4 | """
set: 类似dict,是一组key的集合,不存储value
本质:无序和无重复元素的集合
"""
# 创建
# 创建set需要一个list或者tuple或者dict作为输入集合
set1 = set([1, 2, 3, 4, 5])
print(set1)
# 重复元素在set中会自动被过滤
print(set([1, 2, 3, 3, 3, 4, 5]))
print(set([1, 2, 3, 3, 2, 1]))
set2 = set({1:"good", 2:"nice"})
print(set2)
# 添加
set3 = set([1, 2, 3, 4, 5])
set3.add(6)
print(set3)
# 可以添加重复的,但是不会有效果
set3.add(3)
print(set3)
# set的元素不能是列表,因为列表是可变的
# TypeError: unhashable type: 'list'
# set3.add([7, 8, 9])
# print(set3)
set3.add((7, 8, 9))
print(set3)
# set的元素不能是字典,因为字典是可变的
# TypeError: unhashable type: 'dict'
# set3.add({1:"a"})
# print(set3)
# 插入整个list、tuple、字符串,打碎插入
set4 = set([1, 2, 3, 4, 5])
set4.update([6, 7, 8])
print(set4)
set4.update((9, 10))
print(set4)
set4.update("sunny")
print(set4)
# 删除
set5 = set([1, 2, 3, 4, 5])
set5.remove(3)
print(set5)
# 遍历
set6 = set("sunny")
for i in set6:
print(i)
# set没有索引的
# TypeError: 'set' object is not subscriptable
# print(set6[3])
for index, data in enumerate(set6):
print(index, data)
set7 = set([1, 2, 3])
set8 = set([2, 3, 4])
# 交集 后生成一个新的集合
a1 = set7 & set8
print(a1)
print(type(a1))
# 并集
a2 = set7 | set8
print(a2)
print(type(a2))
| false |
ddea47ea7104526d791b3c123aaa13d1aaeb62d3 | cyjhunnyboy/PythonTutorialProj | /pers/cyj/day04/05-break与continue语句/continue语句.py | 395 | 4.1875 | 4 | """
continue语句
作用:跳过当前循环中的剩余语句,然后继续下一次循环
注意:跳过距离最近的循环
"""
for i in range(10):
print(i)
if i == 3:
continue
print("*")
print("&")
print("=================")
num = 0
while num < 10:
print(num)
if num == 3:
num += 1
continue
print("*")
print("&")
num += 1
| false |
786cf0d56d1b916df31862abe73be15d07e33a2a | cyjhunnyboy/PythonTutorialProj | /pers/cyj/day03/01-运算符和表达式的续集/逻辑运算符.py | 791 | 4.28125 | 4 | """
逻辑与:and
逻辑与运算表达式:表达式1 and 表达式2
值:如果表达式1的值为真,表达式2的值为真,整个逻辑与运算表达式的值为真,否则为假
"""
num1 = 10
num2 = 20
if num1 - 10 and num2:
print("***********")
"""
逻辑或:or
逻辑或运算表达式:表达式1 or 表达式2
值:如果表达式1和表达式2的值其中有一个为真正,整个逻辑或运算表达式的值为真,否则为假
"""
num3 = 0
num4 = 1
if num3 or num4:
print("逻辑或表达式结果为真")
"""
逻辑非:not
逻辑非运算表达式:not 表达式
值:如果“表达式”的值为真,则整个逻辑非运算表达式的值为假,否则为真
"""
num5 = False
if not num5:
print("逻辑非运算表达式结果为真")
| false |
8d3496826ca6dd7bd4aa40bf48a5563f873a86a3 | emelleby/in1000 | /3_oblig/testing.py | 928 | 4.5 | 4 | liste = [1, 2, 3]
l = len(liste)
""" Function to calculate the product of the numbers in the list
def produkt(liste):
produkt_liste = 1
for i in range(len(liste)):
produkt_liste *= liste[i]
return produkt_liste
def produkt(liste):
produkt = 1
for i in liste:
produkt *= i
return produkt
print(produkt(liste))
def multiplyList(l, i):
if i == 0:
print("ett tall")
return = l[i]
return l[i] * multiplyList(l[i - 1])
"""
# Recursive Python3 code
# to multiply array elements
# Function to calculate the product
# of array using recursion
def multiply( a , n ):
# Termination condition
if n == 0:
return(a[n])
else:
return (a[n] * multiply(a, n - 1))
# Driver Code
# array = [1, 2, 3, 4, 5, 6]
# n = len(array)
# Function call to
# calculate the product
print("product is:")
print(multiply(liste, len(liste) - 1))
| false |
8e001e5a0e936f366a6f09b7e3c8d0b76fd14c32 | leticiafelix/python-exercicios | /04 - Manipulando textos/desafio022.py | 621 | 4.125 | 4 | #faça um programa que leia o nome completo de uma pessoa e mostre:
#o nome com todas as letras maiusculas
#o nome com todas as letras minusculas
#quantas letras tem (sem considerar os espaços)
#quantas letras tem o primeiro nome
nome = str(input('Insira seu nome completo:'))
nome = nome.strip()
mai = nome.upper()
min = nome.lower()
letras = nome.split()
n = len(letras)
letras = len(nome)-(n-1) #subtraindo o número de espaços
prim = len(nome.split()[0])
print("""Nome: {}
Em maiúsculo: {}
Em minúsculo: {}
Quantidade de letras: {}
Quantidade de letras do primeiro nome: {}""".format(nome,mai,min,letras,prim))
| false |
4229b121411d36062db4f30122e745d7fd523e0e | WHJR-G8/G8_C15_For_Student_Reference | /Student_Project.py | 568 | 4.125 | 4 | import turtle
turtle.pensize(4)
turtle.pencolor("OliveDrab")
turtle.setpos(-50, 0)
def repeated_tasks(c,s,a):
turtle.fillcolor()
for i in [0, 1, 2]:
#This function call is to make the house shelter i.e upper part of the house
turtle.forward(25)
turtle.right(90)
#This function call is to make the lower part of the house
#The below steps till the end are for drawing a circle(window)
turtle.penup()
turtle.forward(62.5)
turtle.left(90)
turtle.forward(25)
turtle.right(90)
turtle.pendown()
turtle.hideturtle()
| true |
6c5244b15945d02c986258e76d9da2b1f3da289c | ichan266/Code-Challenges | /Leetcode/Past Code Challenges/05-27-21 shift2Dgrid.py | 1,421 | 4.21875 | 4 | # Leetcode # 1260
# https://leetcode.com/problems/shift-2d-grid/
# Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
# In one shift operation:
# Element at grid[i][j] moves to grid[i][j + 1].
# Element at grid[i][n - 1] moves to grid[i + 1][0].
# Element at grid[m - 1][n - 1] moves to grid[0][0].
# Return the 2D grid after applying shift operation k times.
# % This solution "flatten" the 2D array to a simple array with no nested arrays, create a new array by
# % using the k value, counting elements from the back, and move k amount of elements to the front.
# % Final step was to recreate the 2D array based on # of column in the original 2D array
def shiftGrid1(grid, k):
combined = [num for rows in grid for num in rows]
if k > len(combined):
k = k % len(combined)
newList = combined[-k:] + combined[:-k]
col = len(grid[0])
return [newList[i:i+col] for i in range(0, len(newList), col)]
# @ Pair programming with Ben. General strategy is to shift forward instead of backward (see line 35: rows*cols is the total amount of items in the entire 2D array. Subtracting k % (rows*cols) will shift it forward)
def shiftGrid2(grid, k):
rows = len(grid)
cols = len(grid[0])
k = (rows*cols) - (k % (rows*cols))
return [[grid[(idxR + (k+idxC)//cols) % rows][(idxC + k % cols) % cols] for idxC in range(cols)] for idxR in range(rows)]
| true |
e0ea787e176e1b2e4f868fdb8012ca792e2d9d6c | Sethrick/SelfTaughtP_CompletedExercises | /Python_Althoff_SelfTaughtProgrammer/SelfTaughtP_pp085_Ch05_Challenges.py | 1,797 | 4.46875 | 4 |
# 1) Create a list of your favorite musicians.
band_list = ["TSFH", "Evancho", "Thomas", "Piano Guys"]
print(band_list)
# 2) Create a list of tuples, with each tuple containing the longitude
# and latitude of somewhere you've lived or visited.
Ft_Riley = (39.1101, 96.8100)
Gimli_Peak = (49.7661, 117.6469)
Keystone_CO = (39.5792, 105.9347)
places = [Ft_Riley, Gimli_Peak, Keystone_CO]
print(places)
# 3) Create a dictionary that contains different attributes about you:
# height, favorite color, favorite author, etc.
my_dict = {"height": "6'1",
"favorite color": "yes",
"favorite author": "LordsFire"}
print(my_dict)
my_height = my_dict["height"]
print(my_height)
# 4) Write a program that lets the user ask your height, favorite color,
# or favorite author, and returns the result from the dictionary you
# created in the previous challenge.
user_ask = input("Query \"height\", \"favorite color\", or \"favorite author\": ")
result = my_dict[user_ask]
print(result)
# 5) Create a dictionary mapping your favorite musicians to a list of your
# favorite songs by them.
music_dir = {"TSFH": "El Dorado",
"Evancho": "Nella Fantasia",
"Thomas": "Illumination"}
print(music_dir["Evancho"])
# 6) Lists, tuples, and dictionaries are just a few of the containers
# built into Python. Research Python sets (a type of container).
# When would you use a set?
"""
Sets are lists without duplicate entries. They use brackets like lists, but
are instantiated by using the "set()" method. One example of how a set might
be used is on a sign-in roster at a gym. Many people might be regulars, and
enter their name frequently. A set would tell us how many different people
use the gym. For example:
"""
print(set("Jordan Josh Eric Adam Eric Seth Isaac Clara Seth".split()))
| true |
a18650703c788528552895a8a2192dc73d59f70c | Sethrick/SelfTaughtP_CompletedExercises | /Python_Althoff_SelfTaughtProgrammer/SelfTaughtP_pp151_Ch13_Encapsulation.py | 1,676 | 4.4375 | 4 |
# Encapsulation in object oriented programming means that both variables
# (state) and methods (for altering state or doing calculations) are grouped
# together in "objects".
class Rectangle():
def __init__(self, w, l):
self.width = w # Variables (state)
self.len = l
def area(self): # Method which makes a calculation based on state
return self.width * self.len
rec1 = Rectangle(4, 5)
print(rec1.area())
# Encapsulation also refers to hiding a class's internal data to prevent the
# code outside of the object (the "client") from reading it.
class Data():
def __init__(self):
self.nums = [1, 2, 3, 4, 5]
def change_data(self, index, n):
self.nums[index] = n
data0 = Data()
print(data0.nums) # Changing a variable by accessing it directly.
data0.nums[0] = 8
print(data0.nums)
data1 = Data()
print(data1.nums)
data1.change_data(1, 9) # Changing a variable via the "change_data" method.
print(data1.nums)
# Some programming languages have "private variables" that can only be accessed
# by objects of the class in which they are contained. Python does not, using
# naming conventions instead. A Python method that starts with an underscore
# ("_") is not supposed to be accessed by any code outside of its class
# (client code).
class PublicPrivateExample():
def __init__(self):
self.public = "safe"
self.private = "unsafe"
def public_method(self):
# clients can use this.
print(self.public)
def private_method(self):
# clients should not use this.
print(self.private)
ppe = PublicPrivateExample()
ppe.public_method()
ppe.private_method()
| true |
6442273820b2d9041861d6e999377d20be6462d0 | Sethrick/SelfTaughtP_CompletedExercises | /Python_Althoff_SelfTaughtProgrammer/SelfTaughtP_pp035_Ch03_ConditionalStatements.py | 1,071 | 4.4375 | 4 |
# Making decisions with control structures/conditional statements.
# Pseudocode:
# If (expression) Then
# (code_area1)
# Else
# (code_area2)
# Basic if/else control structure
home = "America"
if home == "America":
print("Hello America")
else:
print("Hello World")
# Multiple if statements
x = 2
if x == 2:
print("The number is 2.")
if x % 2 == 0:
print("The number is even.")
if x % 2 != 0:
print("The number is odd.")
# Nested if statements
x = 10
y = 11
if x == 10:
if y == 11:
print(x + y)
# Else-If statements
home = "Thailand"
if home == "Japan":
print("Hello, Japan")
elif home == "Thailand":
print("Hello, Thailand")
elif home == "India":
print("Hello, India")
elif home == "China":
print("Hello, China")
else:
print("Hello, World")
# Combining conditional statements
x = 100
if x == 10:
print("x = 10")
elif x == 20:
print("x = 20")
else:
print("I don't know")
if x == 100:
print("x = 100")
if x % 2 == 0:
print("x is even")
else:
print("x is odd")
| false |
702908e84864118b15aed1a4e935941cfe4c622a | lawrencetheabhorrence/Data-Analysis-2020 | /hy-data-analysis-with-python-2020/part02-e09_rational/src/rational.py | 1,179 | 4.21875 | 4 | class Rational(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __add__(self, r):
# a/b + c/d = (ad + bc) / bd
a = self.a * r.b + self.b * r.a
b = self.b * r.b
return(Rational(a, b))
def __sub__(self, r):
a = self.a * r.b - self.b * r.a
b = self.b * r.b
return(Rational(a, b))
def __mul__(self, r):
a = self.a * r.a
b = self.b * r.b
return(Rational(a, b))
def __truediv__(self, r):
a = self.a * r.b
b = self.b * r.a
return(Rational(a, b))
def __gt__(self, r):
return self.a * r.b > self.b * r.a
def __lt__(self, r):
return self.a * r.b < self.b * r.a
def __eq__(self, r):
return self.a * r.b == self.b * r.a
def __str__(self):
return f'{self.a} / {self.b}'
def main():
r1=Rational(1,4)
r2=Rational(2,3)
print(r1)
print(r2)
print(r1*r2)
print(r1/r2)
print(r1+r2)
print(r1-r2)
print(Rational(1,2) == Rational(2,4))
print(Rational(1,2) > Rational(2,4))
print(Rational(1,2) < Rational(2,4))
if __name__ == "__main__":
main()
| false |
9b96ad978ca5642f2db095845c2902b3dafe603c | RitikaAg/Hacktoberfest-2020-FizzBuzz | /Python/FizzBuzzP2.py | 397 | 4.15625 | 4 | // Another method for creating FizzBuzz
// MishManners
import sys
inputs = sys.argv
inputs.pop(0)
def fizzbuzz(n):
# for n in range(n, num, n + 1):
if n % 3 == 0 and n % 5 == 0:
print ('fizzbuzz')
elif n % 3 == 0:
print ('fizz')
elif n % 5 == 0:
print ('buzz')
else: print(n)
for arg in sys.argv:
fizzbuzz(int(arg))
| false |
5e9a5d8d18445d8a2ddc2f279947648bf30c99c2 | 4RG0S/2021-Summer-Jookgorithm | /안준혁/[21.07.13]3613.py | 840 | 4.15625 | 4 | word = input()
bigger = False
underscore = False
makeBigger = False
error = False
small = False
out = []
for alphabet in word:
if 'a' <= alphabet <= 'z':
small = True
if makeBigger:
out.append(alphabet.upper())
makeBigger = False
else:
out.append(alphabet)
elif 'A' <= alphabet <= 'Z':
if small:
bigger = True
out.append('_')
out.append(alphabet.lower())
else:
error = True
elif alphabet == '_':
if small:
small = False
makeBigger = True
underscore = True
else:
error = True
else:
error = True
if alphabet == '_':
print('Error!')
elif (underscore and bigger) or error:
print('Error!')
else:
print(''.join(out)) | true |
fade9fcc59fd25e22249fec0c309e759687a3db4 | JCharlieDev/Python | /Python Programs/TkinterTut/TkGrid.py | 375 | 4.34375 | 4 | from tkinter import *
# Mostly everything is a widget
# Main Window
root = Tk()
# Creating label widget
myLabel1 = Label(root, text = "Hello world")
myLabel2 = Label(root, text = "My name is Charlie")
# Putting it on the screen
myLabel1.grid(row = 0, column = 0)
myLabel2.grid(row = 1, column = 5)
# Event loop, loops the application to stay open
root.mainloop() | true |
3f0e54298456bd64e7c15f298faba0f3f0b7d93a | Code360In/21092020LVC | /day_01/labs/02_height_of_the_building.py | 438 | 4.28125 | 4 | # Program to calculate the height of the building
# given angle of sight and distance of the measurer from the building
import math
# input
a = float(input("Enter the angle of sight in deg: "))
d = float(input("Enter the distance in mts: "))
# process
h = d * math.tan(math.radians(a))
h = h * 3.281
# output
# print('The height of the building is ', h, ' ft')
print('The height of the building is %.2f ft' % h)
| true |
18e91eed6e9810bf6b24c6713f9a74984084c8cf | sofmorona/nucoroCurrency | /currencyRates/utils.py | 1,571 | 4.25 | 4 | import datetime
import decimal
from functools import reduce
def checkDateFormat(date_string, format):
"""
Function to check if the given date has the expected format
:param date_string: string to check if is a valid date format
:param format: the format expected by the date_string
:return: datetime with the date of the string given, False if the string couldn't be converted.
"""
try:
return datetime.datetime.strptime(date_string, format)
except ValueError:
return False
def checkDecimal(value):
"""
Function to check if the given value can be converted to decimal
:param value: a value compatible with decimal conversion
:return: the decimal in case it can be converted, false in other case
"""
try:
return decimal.Decimal(value)
except decimal.InvalidOperation:
return False
def calculate_twr(values):
"""
Function to calculate the time-weighted rate
Formula:
TWR=[(1+HP1)×(1+HP2)×...×(1+HPn)]−1
where:
TWR= Time-weighted return
n=Number of sub-periods
HP=(End Value − Initial Value + Cash Flow)/(Initial Value + Cash Flow)
HPn = Return for sub-period n
:param values: List of periods
:param amount: amount for which we want to calculate the TWR
:return: the TWR for the given amount
"""
# @todo implement this function
# What is exactly the cashFlow in the API request that we have
# What are the sub-period?
return {'twr': 0, 'rate_value': values[0].rate_value}
| true |
aeb99449371c2c2c9bea0311b55e7cc265e973bf | Ganesh-sundaram-82/DatastructuresAndAlgo | /DS/Linked-List/LinkedList.py | 1,069 | 4.15625 | 4 | import Node
# # head = Node.Node("1")
# # head.NextNode = Node.Node("2")
# # print(head.value)
# # print(head.NextNode.value)
#Single Linked-list
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node.Node(value)
return
# Move to the tail (the last node)
node = self.head
while node.NextNode:
node = node.NextNode
node.NextNode = Node.Node(value)
return
def print(self):
node = self.head
while node:
print(node.value)
node = node.NextNode
def to_list(self):
self.list = []
node = self.head
while node:
self.list.append(node.value)
node = node.NextNode
return self.list
#Single linked-list Operation
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(4)
#linked_list.print()
print(linked_list.to_list())
| true |
2f0caf50c2cd55dc92dc8bc98982da0a2cc1143d | Saberg118/Simple_Python_Programs | /password.py | 1,125 | 4.53125 | 5 | """
This is a password generator that prompts the user the day the were born,
favoriteFruit, and first name.
The new password will contain the the last two letters of their first name,
the last digit of the day they were born times 3, first three letter of their favorit fruit, and
the first letter of their name capitalized.
The program will then display the new password to the user
"""
#Get the information needed from user needed to generate the password
day = [input("What was the day and month you were born ")]
favFruit = input("What is your favorite fruit ")
firstName = [input("What is your first name ")]
# get the last two letter of their first name and the first letter of their name capitalized
for letters in firstName:
lasttwoLetters = letters[-2] + letters[-1]
firstLetter = letters[0].upper()
# multiply the the last digit of the day they were born by three
for num in day:
lastNum = int(num[1])
times3 = lastNum * 3
#get the firstthree letter of their favorite password
lastThree = (favFruit[0:3])
# Display new password
print(lasttwoLetters + str(times3) + lastThree + firstLetter)
| true |
9157fb6460d261a48f65e981febc73a2729032f3 | zmarrich/beginning-python | /pltlweek7ses1.py | 1,056 | 4.15625 | 4 |
###SLIDE ONE
print("She said, '"'I dont like to wear a helmet it messes up my hair'"',which is really silly")
print("Yes\\No?")
print("April\nMay\nJune\n")
#####SLide TWO
message= 'I like Python.'
print(message.lower())
print(message.upper())
print(message.replace('Python','Pasta',1))
#slide 3
##statement='I like to go shopping for clothes'
##print(statement.split(" "))
##
##list="pants, shirts, dresses, socks, skirt, tie"
##print(list.split(","))
###SLIDE 4
##statement="I like to go \nshopping for clothes"
##print(statement.strip())
##
##months="\t\t\njan\nfeb\nmar\napr\nmay\njun\njul\naug\nsep\noct\nnov\ndec\n\t\t"
##print(months.strip())
##print()
###slide5
##statement="I like to go shopping for new tech toys."
##print(statement[30:39])
##print(statement[-9:-1])
##
###slide 6
###word triangle
message=input('Please enter a message:')
count=1
for i in range(len(message)):
print(message[:count])
count+=1
#NEGITIVE INDEX
for i in range(len(message)):
print(message[:i+1])
for i in range(len(message)):
print(message[:-i-1])
| true |
99b2b3031898b7edfb6cf8bf45669075c5d17184 | KarlaXimena16/Tarea-04 | /NumerosRomanos.py | 867 | 4.1875 | 4 | #encoding: UTF-8
#Autor: Ángel Guillermo Ortiz González
#Matrícula: A01745998
#Descripción: Convierte números entre 1 y 10 a números romanos.
#convierte números arábigos entre el 1 y el 10 a su correspondiente número romano
def convertirNumeroARomano(numero):
if numero >= 1 and numero <= 3:
romano = numero * "I"
elif numero >= 4 and numero <=8:
romano = (5 - numero) * "I" + "V" + (numero - 5) * "I"
elif numero == 9 or numero == 10:
romano = (10 - numero) * "I" + "X"
else:
romano = 0
return romano
def main():
numero = int(input("Inserte un número del 1 al 10: "))
romano = convertirNumeroARomano(numero)
print("------------------------------------------")
if romano == 0:
print("ERROR. Inserte un número entre 1 y 10.")
else:
print("El número romano correspondiente es:",romano)
main() | false |
d46c23889ec6a85af6e38228d20c8a7215b6d072 | byuniqueman/pyproj | /bdate | 313 | 4.1875 | 4 | #!/usr/bin/env python3
# test test test
import datetime
currentdate = datetime.date.today()
userinput = input ("What is your birthday? (mm/dd/yy) ")
# format expected below 03/24/1964
birthday = datetime.datetime.strptime(userinput, "%m/%d/%Y").date()
print(birthday)
days = birthday - currentdate
print(days)
| true |
567c548fc3250b56aa461da9d3d5e9317fa96398 | itszrong/2020-Statistics-Tools | /Chi square using contingency table.py | 2,387 | 4.3125 | 4 | data = []
columns = int(input("How many columns are there?"))
rows = int(input("How many rows are there?"))
array_of_row_sum = []
array_of_column_sum =[]
grand_total = 0
#initialising array for column restraints
for n in range(columns):
array_of_column_sum.append(0)
#initialising the observed data and restraints
for i in range(rows):
row = []
row_sum = 0
for j in range(columns):
#generating data matrix
print("Input a the value with the place (", i+1 ,",", j+1 ,") in the data.")
value_at_place = int(input())
row.append(value_at_place)
#calculating restraints
row_sum += value_at_place
grand_total += value_at_place
array_of_column_sum[j] += value_at_place
array_of_row_sum.append(row_sum) #calculates restraints for each row
data.append(row)
#check
print (data)
print(array_of_row_sum)
print(array_of_column_sum)
print("Grand total is", grand_total)
print("The data given")
for r in data:
for c in r:
print(c,end = " ")
print()
#generating expected frequencies
expected_frequencies = []
for i in range(rows):
row = []
for j in range(columns):
row.append(array_of_row_sum[i]*array_of_column_sum[j]/grand_total)
expected_frequencies.append(row)
print("expected frequencies")
for r in expected_frequencies:
for c in r:
print(c,end = " ")
print()
#difference array
difference_array= []
for i in range(rows):
row = []
for j in range(columns):
row.append((data[i][j]-expected_frequencies[i][j]))
difference_array.append(row)
print("difference")
for r in difference_array:
for c in r:
print(c,end = " ")
print()
#chi_squared array
chi_squared_terms= []
for i in range(rows):
row = []
for j in range(columns):
row.append((data[i][j]-expected_frequencies[i][j])**2/expected_frequencies[i][j])
chi_squared_terms.append(row)
print("Chi-squared terms")
for r in chi_squared_terms:
for c in r:
print(c,end = " ")
print()
chi_squared = 0
#calculating chi squared
for i in range(rows):
for j in range(columns):
chi_squared += chi_squared_terms[i][j]
print("chi squared is", chi_squared, "and the number of degrees of freedom is", rows*columns-(rows+columns-1),".")
| true |
86194a8c37522488d322d2f6c382aca1d3ec82e6 | mcalidguid/string-manipulation | /string_manipulator.py | 1,875 | 4.34375 | 4 | def swap_case(sentence):
output = ""
for letter in sentence:
if letter == letter.upper():
output += letter.lower()
else:
output += letter.upper()
print(">>>: %s" % output)
def reverse_swap_words(sentence):
output = ""
for letter in sentence:
if letter == letter.upper():
output += letter.lower()
else:
output += letter.upper()
result_words = output.split()
reverse_words = " ".join(reversed(result_words))
print(">>>: %s" % reverse_words)
def split_and_join(sentence):
sentence = sentence.split(" ")
output = "-".join(sentence)
print(">>>: %s" % output)
while True:
print("""---------------------------------------------------------------
Select an option for String Manipulation:
Enter \"1\" for Swap
Enter \"2\" for Reverse & Swap
Enter \"3\" for Split & Join
Enter \"q\" to quit""")
user_input = input(">>>: ")
if user_input == "q":
print(">>>: Danke, tschüss!~")
break
elif user_input == "1":
print("You selected \'Swap\'"
"\nThis will swap the case of all letters in the string")
print("Input the string:")
words = input(">>>: ")
swap_case(words)
elif user_input == "2":
print("You selected \'Reverse & Swap\'"
"\nThis will reverse the word order and swap the case of all letters in the string")
print("Input the string:")
words = input(">>>: ")
reverse_swap_words(words)
elif user_input == "3":
print("You selected \'Split & Join\'"
"\nThis will split the string on a space delimiter and join using a hyphen")
print("Input the string:")
words = input(">>>: ")
split_and_join(words)
else:
print(">>>: Invalid input")
| true |
8dfe55144cae789d302f6bcba813b1389e925951 | aviik/intellipat_assignments | /Assignment_2_ComDs/05_character_to_string.py | 314 | 4.375 | 4 | #5.Write a Python program to convert a list of characters into a string.
# enter some characters
my_char = []
while True:
foo = input("==>")
if foo == 'done':
break
my_char.append(foo)
def string_maker(my_char):
my_string = ''.join(my_char)
print(my_string)
string_maker(my_char)
| true |
33a3181bfee5926139e75082d94345044a8855c1 | aviik/intellipat_assignments | /Assignment _1_(Cond, Loops,Funct)/05_squared_series_of_series.py | 286 | 4.25 | 4 | ## 1^2 + ( 1^2 + 2^2 ) + (1^2 + 2^2 + 3^2) + .......+nth_number
print("Give the nth number: ")
nth_number = int(input("> "))
i = 1
j = 1
sum = 0
while i <= nth_number:
total = 0
for j in range(0,i+1):
total = total + j**2
sum = sum + total
i = i + 1
print(sum)
| false |
576a955463ff5e791ad3298e5c08d8ff1adfaa99 | Luccifer/PythonCourseraHSE | /w02/e16.py | 397 | 4.125 | 4 | # Сколько совпадает чисел
def coincidence_of_numbers(num1, num2, num3):
if num1 == num2 == num3:
ans = 3
elif num1 == num2 or num2 == num3 or num1 == num3:
ans = 2
else:
ans = 0
return ans
if __name__ == '__main__':
num1, num2, num3 = int(input()), int(input()), int(input())
print(coincidence_of_numbers(num1, num2, num3))
| false |
e6d81842388a1f017975a84b9e97966183acf27a | DTIV/PythonDeepDive | /Variables_and_Memory/dynamic_vs_static.py | 649 | 4.34375 | 4 | # DYNAMIC VS STATIC TYPING
''' Python is dynamically typed - the variable can be whatever, it just changes the memory address for what is needed and rewrites.
Static typed must specify type and the variable is specific to that type always '''
print("Python variables can change dynamically throughout the code, changing variable memory addresses")
a = "hello"
print(type(a))
print(hex(id(a)),"\n")
a = 10
print(type(a))
print(hex(id(a)),"\n")
a = 10.23
print(type(a))
print(hex(id(a)),"\n")
a = True
print(type(a))
print(hex(id(a)),"\n")
a = lambda x: x ** 2
print(type(a))
print(hex(id(a)),"\n")
a = 3 + 4j
print(type(a))
print(hex(id(a))) | true |
40efaa887d904eaf1ac46162ad204045f0ab60ab | R-Gasanov/gmgcode | /String DataType/E_StringsTest.py | 1,559 | 4.5625 | 5 | # Not only can we ask for specific parts of the string, we can modify on how we percieve them as well
x = (' Good_Morning ')
# Now what we can do with this its change its case from upper to lower, here are the following commands
print (x.upper())
# The one above is upper
print (x.lower())
# The next one is lower
# As you can see the different, we changes the caps with upper and lower
print ('#######################')
# Now we can even replace certain letters with other with the command 'replace()'
print (x.replace('G', 'F'))
# We can even clean up the string, if its provdied with excess whitespace that is not even required
print ('#######################')
# This will remove the whitespaces that are from the beggining and the end
print (x.strip())
# We can even split the string itself to represent a list
print ('#######################')
# We are splitting from the specific symbol of _, in which Good and Morning will be shown seperatley
print (x.split('_'))
print ('#######################')
# Now we will even look into how we can combine two different strings into one as well (Concatenate)
y = ('Good')
# We've created seperate strings for the following to be connected
z = ('Morning')
# As shown below, both strings will be literally added each other and will be represented by a new variable (s)
s = y + z
print (s)
# Although the issue is that theres no space, so we can also add the in between
print ('#######################')
# So we will be properly formatting when the variables are finally updated
v = y + (' ') + z
print (v)
| true |
83cffd1b2b720d02ea4cc84173497d42b5df7019 | R-Gasanov/gmgcode | /AllCode/C_Python Practice/B_ DataTypes/String DataType/D_StringsTest.py | 1,267 | 4.625 | 5 | # Now we will be looking at slicing , essentially splitting strings seperately
x = 'Good Morning'
# Now as you can see from the bottom we're using a colon ':'
print (x[:4])
# Now what were doing is we selected a letter through the representation of numericle values
print ('#######################')
# And using the colon depending on which side, since its in front we're going backwards
# Reveal all the other letters that are after the inital letter with it as well
print ("""As you can see,
we got the word Good.
Since the 4th position in the string is d,
and the the colon (:) is in the beggining,
we went backwards which spelled Good.""")
# We can do this as well to go forwards additionally
print ('#######################')
# We will be using the colon after the specific numericle value as seen below
print (x[5:])
# The 5th position is M, and with the colon we will get (Morning)
print ('#######################')
# We can even go backwards with the numericle value, if your working with very long strings
print (x[:-7])
# Now we've went backwards, which in the end has printed Good since g the end of morning is -0
print ('#######################')
print (x[2:8])
# With this we can even go between numericle numbers to show what we might want in between
| true |
d02a46f80a02b48025d476b4409155fdda384f19 | R-Gasanov/gmgcode | /AllCode/I_Tuples/E_TupleTest.py | 2,485 | 5.0625 | 5 | # We can't technically change its values with a tuple, although there are some unique ways of doing so
vegtables = ('cucumber','carrot','zuccini','swiss chard','garlic')
# As a small portion of us know, zuccini is not a vegtable
veg_list = list(vegtables)
# What we're doing here, is converting this tuple into a list, which means we can change its content now
print (veg_list)
# Now we can change zuccini in an actual vegtable
veg_list[2] = 'kale'
# We know that the index of zuccini is 2, so we specify this value and change it to kale, which is an actual vegtable
vegtables = tuple(veg_list)
# Now we are doing the opposite with what we've done on our 2nd line of code, changing it back to a tuple
print (f"""As you can see,
we have changed the contents within this tuple.
How you might ask?
Well we converted the tuple into a list,
which then became changable,
so we reasigned the 3rd value,
into an actual vegtable.
As shown ahead, {vegtables}""")
# Which is one way to technically change the contents of a tuple
print ("""Now remember, a tuple can not be changed or add new values,
so you can not use the command (append) in order to add additonal information,
but as shown above we were able to change an existing value.
Via conerting it into a tuple.""")
# So how would we add an additional value within the tuple?
print ('####################')
# We will be doing the same thing essentially in basic principle
veg_list = list(vegtables)
# So we wil now be apending a list, which is actually doable.
veg_list.append('tomato')
# And we do the same thing, which is reversing it back to a tuple
vegtables = tuple(veg_list)
# Which indeed works, now we were able to add an additional value to the whole variable
print (vegtables)
# Now we done, change and add. What above removing?
print ('####################')
# It might be as you guessed it similar to what we've done previously
veg_list = list(vegtables)
# We do the same concept but of course, change the command using to (remove)
veg_list.remove('tomato')
# We all should know that tomatoes are not vegtables of course
vegtables = tuple(veg_list)
# As you can see from below, we've edited the tuple through the same system to remove tomato
print (vegtables)
# And finally what if we want to delete all together? Well you guessed it...
print ('####################')
# Its simple you simply use the del command
del vegtables
# If we were to print out vegtables we would recieve and error since, its now equivelant to nothing
| true |
95b51884352d71eabe74efbb6466a5744e5135ae | R-Gasanov/gmgcode | /AllCode/B_ DataTypes/NumbersTest.py | 848 | 4.5 | 4 | # We will now be looking at Numbers, and the various types
#There are 3 basic types
# Integer, a basic whole number
x = 1
# Float, a number that is a decimal
y = 17.7
# Complex a number with multiple featurs that involves with symbols and letters
z = 1j
# You can of course convert each number to a different number type depending on what you want
a = float(x)
b = int(y)
c = complex(x)
# From looking we are conerting these number depending on what statement (number type we want)
print (f'{x} Is the original, {a} is now changed')
print (type(a))
# Now the usage of the statement 'type', it allows us to see what datatype it is
print (f'{y} Is the original, {b} is now changed')
print (type(b))
print (f'{z} Is the original, {c} is now changed')
print (type(c))
# With out test running we can at the end see how it will look and operate | true |
527e950a38182ee8c94a7d20fe610da64b54ce74 | R-Gasanov/gmgcode | /AllCode/I_Tuples/A_TupleTest.py | 707 | 4.3125 | 4 | # Now first of lets begin our tests with Tuple, since they can store multiple values lets try it
atuple = ('China','America','United Kingdom','Russia','Poland')
print (atuple)
# As you can see when you review the atuple variable you can see the
print ('####################')
# Additionally as we have previously explained we can use duplicates
atuple_two = ('French','Czech Republic','Madagascar','French')
print (atuple_two)
# As you can see we can have duplicate values which is rather good for us
print ('####################')
# What we can even do is find the relative length of the Tuple
print(len(atuple_two))
# It prints out 4, meaning we have overall 4 different values within that Tuple
| true |
5dc7dc9d22063290ee88b2821a9e143ca570023c | R-Gasanov/gmgcode | /AllCode/L_Functions/C_Functiontest.py | 1,081 | 4.53125 | 5 | # Now we will be looking at passing a list as an argument throught the function
print ('#######################')
# So lets make our function!
def my_function(movies):
# As per usual we will iterate through the list
for x in movies:
print (x)
# Now lets provide us with the list
horror = ['Scream', 'Friday the 13th', 'Jigsaw', 'Conjuring']
# We've created the list now we will simply call upon the function
my_function(horror)
# As you can tell we siphon the list through the function and provie us with the intel through it
print ('#######################')
# To let functions provide certain values back, you can use the given command (function) to do so
def my_function(y):
return 2 * y
# This kind of acts like a print command but simply returns the value once its done its course
print(my_function(2))
# Although whats interersting with is that, you can use this value for various other things, so its similar to a variable you wish to edit
print (my_function(8))
# You can do it consistently as well which is very useful
print ('#######################') | true |
96213221e172e444f5cec4a847d2b71fbaca52c2 | jlheen/python-challenge | /PyPoll/main.py | 2,857 | 4.21875 | 4 | # python-challenge -- PyPoll
# Import Modules
import os
import csv
# Read csv file
PyPoll_Data = os.path.join("./Unit03 - Python_Homework_PyPoll_Resources_election_data.csv")
with open(PyPoll_Data) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# Skip the header row
csv_header = next(csvfile)
# Define variables, lists, and dictionaries
vote_counter = 0
all_candidates = []
candidate_vote_totals = {}
candidate_percent_totals = {}
percent = float
# Insert a for loop to count number of rows
# Number of rows will = total number of votes cast
for row in csvreader:
vote_counter += 1
# Assign a variable to the candidate name
# Give an index so that when it loops, that location can be stored
candidate_name = row[2]
# If the candidate's name has not yet appeared, it will be added to the list
if candidate_name not in all_candidates:
all_candidates.append(candidate_name)
# As candidates are added to this list, they are added
# to a dictionary that holds {candidate name: candidate votes}
candidate_vote_totals[candidate_name] = 1
else:
# When a candidate receives another vote, this gets added to their total
candidate_vote_totals[candidate_name] = candidate_vote_totals[candidate_name] + 1
# To calculate the percentage of votes:
# The loop will then capture the value of the individual's vote by
# their key; then this value is divided by the total amount of votes
for key, value in candidate_vote_totals.items():
percent = value / vote_counter
candidate_percent_totals.update({key: str("{:.3%}".format(percent))})
# Calculate the winner
# https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary
# By finding the key that corresponds with highest vote value total
max(candidate_vote_totals, key=lambda key: candidate_vote_totals[key])
# Print out the results
print("Election Results")
print("------------------------")
print("Total Votes: " + str(vote_counter))
print("The number of votes each candidate received was: " + str(candidate_vote_totals))
print("The percentage of votes each candidate received was: " + str(candidate_percent_totals))
print("Winner: " + str(max(candidate_vote_totals, key=lambda key: candidate_vote_totals[key])))
# Export the results to a text file
# Export the results to a text file
f= open("Election_Results.txt", "w+")
f.write("Election Results --- Total Votes: " + str(vote_counter) + " The number of votes each candidate received was: " + str(candidate_vote_totals) + " The percentage of votes each candidate received was: " + str(candidate_percent_totals) + " The Winner: " + str(max(candidate_vote_totals, key=lambda key: candidate_vote_totals[key])))
f.close() | true |
24b6df398f7d67ef5c4fa41ae36129d9689aa1c9 | amaizing-crazy/kv-055 | /python_basic/task3.py | 324 | 4.5625 | 5 | #Define a function reverse() that computes the reversal of a string.
# For example, reverse("I am testing") should return the string "gnitset ma I".
def reverse(string):
rstring = ''
for i in string[::-1]:
# for i in string[-1:0:-1]:
rstring = rstring + i
print(rstring)
reverse("I am testing")
| true |
7f72822d56efd0bfac9dc8c11d35c1478be6d074 | stemlatina/Python-Code | /h3q5MD.py | 601 | 4.21875 | 4 | #Marilu D
#Q5MD
#User Input
a = float(input("Please enter the length of first side: "))
b = float(input("Please enter the length of second side: "))
c = float(input("Please enter the length of third side: "))
#If Statements
if a == b and b == c and a ==c :
print("This is a equilateral triangle")
elif a == b or a == c or b == c:
print("This is a isoseles triangle.")
elif a == b or a == c or b == c and a**2 + b**2 == c**2 or a**2 + b**2 == c**2 or a**2 + b**2 == c**2:
print("This is an isosceles right triangle.")
else:
print("This is not an equilateral or isosceles triangle.")
| true |
d835091502b8867ed9d8062b1b48396fafdde20f | blky/python | /learning1/forloop.py | 593 | 4.3125 | 4 | # first line in this doc
forLine = 'www.google.com'
count = 0
for i in forLine:
count +=1
print format(count,'2d'), i
else:
print('out of for loop')
# () is used for tuple , which is read-only - unlike list .. iwth []
tup = (1,2,3,4,5,6)
for ea in tup:
print ea
# file can be thought as string.. therefore, for in to go through all lines in file
print 'read docment first line here .......'
# line = open('forloop.py','r').readline()
# print line
lines = open('forloop.py','r').readlines()
i=0
for c in lines:
print i, ')' ,c
i +=1
else:
print 'out readline', len(lines)
| false |
9cfc825230c0c9999879ca4d593c0c241ad9e717 | Kelley12/LearningPython | /Blake/Chapter 3 - Functions/practiceProject.py | 663 | 4.34375 | 4 | # Practice Project from Chapter 3: the Collatz Sequence
def collatz(number):
if number % 2 == 0:
number = number//2
print(str(number))
return number
else:
number = 3 * number + 1
print(number)
return number
def main():
print('Enter a number:')
try:
usersNumber = int(input())
while usersNumber != 1:
usersNumber = collatz(usersNumber)
except:
print('Error: You must enter number you idiot!')
main()
print('*** Collatz Sequence ***')
print('Enter a number ans using the collatz sequence it will eventually end up at 1')
print('')
main()
| true |
cc30c59ecfe69bfe7ef9cef978921b99e5fea390 | HeartAttack417/labs4 | /individual_1.py | 1,187 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Дано предложение. В нем слова разделены одним или несколькими пробелами (символ «-»
# в предложении отсутствует). Определить количество слов в предложении. Рассмотреть два
# случая:
# начальные и конечные пробелы в предложении отсутствуют;
# начальные и конечные пробелы в предложении имеются.
if __name__ == '__main__':
# Если пробела в начале строки нет
sentence = str(input("Введите предложение "))
sentence = sentence.split(' ')
count = 0
for item in sentence:
count += 1
print(count)
# Если пробел в начале строки есть
sentence = str(input("Введите предложение "))
len = len(sentence)
sentence = sentence[1:len-1]
sentence = sentence.split(' ')
count = 0
for item in sentence:
count += 1
print(count) | false |
616ae81759d0e0a7535c0224f881092c6df8e407 | Prajnahu/Python-program | /paliendrome.py | 783 | 4.15625 | 4 | def palindrome(string):
backwards=string[::-1].casefold()
return backwards==string.casefold() #returns true or false
return palindrome(string)
word=input("please enter a word to check")
if palindrome(word):
print("{} is a paliendrome".format(word))
else:
print("{} is not a paliendrome".format(word))
print()
print()
print()
# def alphanumeric(choice):
# string=""
# for char in choice:
# if char.isalnum():
# string+=char ##string contains only letters and digits
#
# print(string)
# return string[::-1].casefold()==string.casefold()
#
#
# sentence=input("enter the sentence")
# if alphanumeric(sentence):
# print("its a plaiendrome")
# else:
# print("mot a palienddrome")
| true |
3a7e2f0802f5cf4d660a531474f603bb768b3a96 | ddotafonso/CodeCabinet | /revertingstring.py | 350 | 4.28125 | 4 | # Reverting String in Python in O(n) Complexity
def revertingString(x):
str = ""
for word in x:
str = word + str
return str
phrase = "Hi my name is Dimbu"
print(revertingString(phrase))
# Reverting a string in O(1) complexity
def revertingString(x):
print(x[::-1])
phrase = "My name is Dimbu"
revertingString(phrase) | false |
ee1253259b1532b29be46cdc810ce441ebef2a8c | DamocValentin/PythonLearning | /BinarySearchAlgorithm.py | 1,404 | 4.21875 | 4 | # Create a random list of numbers between 0 and 100.
# Ask the user for a number between 0 and 100 to check whether their number is in the list.
# The programme should work like this. The programme will half the list of numbers and see whether
# the users number matches the middle element in the list. If they do not match, the programme
# will check which half the number lies in, and eliminate the other half. The search then continues
# on the remaining half, again checking whether the middle element in that half is equal to the
# user’s number. This process keeps on going until the programme finds the users number, or until
# the size of the subarray is 0, which means the users number isn't in the list
def __main__():
found = 0
numbers_list = []
for i in range(0, 100):
if i % 2 == 0:
numbers_list.append(i)
searched_number = int(input("What number do you want to search? "))
left_head = 0
right_head = len(numbers_list) - 1
while left_head <= right_head:
middle = int((left_head + right_head) / 2)
if searched_number == numbers_list[middle]:
print("Number found!")
found = 1
break
elif searched_number > numbers_list[middle]:
left_head = middle + 1
else:
right_head = middle - 1
if not found:
print("Number not found!")
__main__()
| true |
50c69cb28453275cbfc1cf90ae86620d6b6f341b | elenzi/algorithmsproject | /algorithmsproject/bruteforce.py | 2,204 | 4.125 | 4 | import copy
from algorithmsproject.airportatlas import AirportAtlas
from algorithmsproject.route import Route
from algorithmsproject.travelplan import TravelPlan
import itertools
class BruteForce:
"""Exhaustively searches for the shortest path."""
def __init__(self, travel_plan: TravelPlan):
self.travel_plan = travel_plan
def search(self):
"""Finds the shortest path"""
print('Initiating search.....')
# List comprehensions provide a concise way to create lists.
middle = [airport for airport in self.travel_plan.airports
if airport.code != self.travel_plan.start_airport.code]
# print(f'len(middle) = {len(middle)}')
# print(f'len(self.travel_plan.airports) = {len(self.travel_plan.airports)}')
assert len(middle) < len(self.travel_plan.airports), f'{len(middle)} {len(self.travel_plan.airports)}'
permutations = itertools.permutations(middle, r=len(middle))
route_collection = []
for p in permutations:
# Here p refers to a partial route
# route is a queue, why did you use a queue
route = Route()
route.enqueue(self.travel_plan.start_airport)
for airport in p:
route.enqueue(airport)
route.enqueue(self.travel_plan.start_airport)
route_collection.append(route)
# Let's look into our route collection
min_cost = None
cheapest_route = None
atlas = AirportAtlas()
for r in route_collection:
try:
cost = atlas.compute_cost(r, self.travel_plan.aircraft)
# print('Route collection', r, r.size())
if min_cost is None:
# print('\tSetting initial minimum cost')
min_cost = cost
cheapest_route = r
continue
if cost < min_cost:
# print('\tFound a new minimum cost')
min_cost = cost
cheapest_route = r
except ValueError:
raise
# We're done searching
return cheapest_route, min_cost
| true |
888d75b81e63ba39cea0efd63d6ef386c44279ec | isakfinnoy/INF200 | /src/isak_finnoy_ex/ex01/tidy_code.py | 1,187 | 4.375 | 4 | from random import randint as dice
__author__ = 'Isak Finnoy'
__email__ = 'isfi@nmbu.no'
"""This is a game of two dices, where the user is trying to guess the correct sum of the two dices,
decided by the random.randint function. The max number of valid guess attempts are 3, though you can make as many
invalid guesses (guess < 2) as you like, as they will not be counted by the program.
"""
def guess_input():
guess = 0
while guess < 2: # changed 1 to 2 since the sum of two dices can never be less than 2
guess = int(input('Your guess: '))
return guess
def dices_roll():
return dice(1, 6) + dice(1, 6)
def compare_sum_and_guess(f, g):
return f == g
if __name__ == '__main__':
win = False
remaining_attempts = 3
sum_eyes = dices_roll()
while not win and remaining_attempts > 0:
your_guess = guess_input()
win = compare_sum_and_guess(sum_eyes, your_guess)
if not win:
print('Wrong, try again!')
remaining_attempts -= 1
if remaining_attempts > 0:
print('You won {} points.'.format(remaining_attempts))
else:
print('You lost. Correct answer: {}.'.format(sum_eyes))
| true |
7dc02f383ad728300cf81c4f2aa999a9dad987a8 | Panlq/Algorithm | /剑指offer/两个等长数组和之差最小.py | 1,351 | 4.21875 | 4 | """
将两序列合并为一个序列,并排序,为序列Source
拿出最大元素Big,次大的元素Small
在余下的序列S[:-2]进行平分,得到序列max,min
将Small加到max序列,将Big加大min序列,重新计算新序列和,和大的为max,小的为min。
"""
def mean(sorted_list):
if not sorted_list:
return [], []
big = sorted_list[-1]
print(big)
small = sorted_list[-2]
print(small)
big_list, small_list = mean(sorted_list[:-2])
big_list.append(small)
small_list.append(big)
big_list_sum = sum(big_list)
small_list_sum = sum(small_list)
if big_list_sum > small_list_sum:
return big_list, small_list
else:
return small_list, big_list
source1 = [90, 25, 10]
source2 = [5, 35, 6]
a = source1 + source2
print(a)
a.sort()
l1, l2 = mean(a)
print(l1, l2)
print("Distance:\t", abs(sum(l1)-sum(l2)))
tests = [[1, 2, 3, 4, 5, 6, 700, 800],
[10001, 10000, 100, 90, 50, 1],
list(range(1, 11)),
[12312, 12311, 232, 210, 30, 29, 3, 2, 1, 1]
]
# for l in tests:
# l.sort()
# print()
# print("Source List:\t", l)
# l1,l2 = mean(l)
# print("Result List:\t", l1, l2)
# print("Distance:\t", abs(sum(l1)-sum(l2)))
# print('-*'*40)
| false |
a382c532d9dffade4e7cf2ede892e66ac17fc57d | calvinxuman/python_learn | /macheal_liao/recursive_function.py | 2,310 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/2/22 09:35
# @Author : calvin
#递归函数定义
def fact(n):
if n == 1:
return n
return n*fact(n-1)
'''如果一个函数在内部调用自身本身,这个函数就是递归函数.
递归函数的优点是定义简单,逻辑清晰。理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰.
使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,
栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。
解决递归调用栈溢出的方法是通过尾递归优化,事实上尾递归和循环的效果是一样的,所以,把循环看成是一种特殊的尾递归函数也是可以的。'''
#尾递归
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)
'''尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。
这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况。
上面的fact(n)函数由于return n * fact(n - 1)引入了乘法表达式,所以就不是尾递归了。
要改成尾递归方式,需要多一点代码,主要是要把每一步的乘积传入到递归函数中
尾递归调用时,如果做了优化,栈不会增长,因此,无论多少次调用也不会导致栈溢出。
遗憾的是,大多数编程语言没有针对尾递归做优化,Python解释器也没有做优化,
所以,即使把上面的fact(n)函数改成尾递归方式,也会导致栈溢出。'''
#汉诺塔游戏
#编写move(n, a, b, c)函数,它接收参数n,表示3个柱子A、B、C中第1个柱子A的盘子数量,然后打印出把所有盘子从A借助B移动到C的方法
def move(n,a,b,c):
if n == 1:
print(a,'---→',c)
if n > 1:
move(n-1, a, c, b)
print(a, '---→', c)
move(n-1, b, a, c)
move(3,'a','b','c')
| false |
6c517a29a5eaff0bbde1474f9a6814956f7fd58b | Jhedie/Comfortable_Python | /CodingBat/biggest_number_index.py | 698 | 4.28125 | 4 | # program to print the index of the biggest number in an array
#main function
def get_biggest(array):
position = 0
return biggest_number(array, position)
#recursive function for comparisons
def biggest_number(List, position1):
if position1 == len(List)-1:
return position1
else:
#position2 which we would compare with position 1
position2 = biggest_number(List, position1 + 1)
#if position2 is bigger we maintain position2
if List[position2] > List[position1]:
return position2
#otherwise position1 is maintained
else:
return position1
list1 = [9, -20, 6, 1, 80, 9, 2]
print(get_biggest(list))
| true |
917a9a9479b123d6499b194cd85616606b8f2101 | riccab/python-practice | /hello.py | 705 | 4.46875 | 4 | print("hello, world!")
"""This is a doc string
spanning multiple lines"""
#print("Enter your name:")
x = input("Enter Your name \n")
print("Hello, " + x)
#The for loop acts as an iterator, does not require an indexing variable
#In this example banana will not be printed because print is being skipped by the continue
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
#Simple recursion example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1) #for variable of 5 this ends up being 5+4+3+2+1=15, then 4+3+2+1=10, etc.
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(5)
| true |
2ad10828096ea4ab3c4fdd4d5003c49dceaf15e2 | gauravgrover95/Learn-Python-The-Hard-Way | /ex45.py | 2,249 | 4.15625 | 4 |
class Animal():
def __init__(self, name):
self.name = name
def speak(self):
print "check me out.. I am speaking"
## ?? Dog is-a class of Animal
class Dog(Animal):
def __init(self, name):
## ?? Dog has-a name
self.name = name
def speak(self):
print "Bow Bow!"
## ?? Cat is-a class of superclass Animal
class Cat(Animal):
def __init(self, name):
## ?? Cat has-a name
self.name = name
def speak(self):
print "Meow...... Meow"
## ?? Person is-a class of superclass object
class Person(object):
def __init__(self, name):
## ?? Person has-a name
self.name = name
## Person has-a pet of some kind
self.pet = None
def speak(self):
print "Hi my name is " + self.name + ". Happy to see you"
## ?? Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
## ?? hmm what is this strange magic
super(Employee, self).__init__(name)
## ?? Employee has-a salary
self.salary = salary
def speak(self):
print "Good Morning Sir, my name is", self.name
# TBN very carefully: the name of the method and the data member can not be same.
# It creates confusion for the interpretter, It starts calling the data member and gives the TypeError
# that this data member is not callable
def my_salary(self):
# print 120000
print "My salary is", self.salary
class Fish(object):
pass
## ?? Salmon is-a Fish
class Salmon(Fish):
pass
## ?? Halibut is-a Fish
class Halibut(Fish):
pass
## rover is-a dog
rover = Dog("Rover")
## ?? satan is-a Cat
satan = Cat("Satan")
## ?? mary is-a object of Person
mary = Person("Mary")
## ?? frank is-a Employee which has-a salary of 120000
frank = Employee("Frank", 120000)
## ?? frank has-a pet , which is an object, rover
frank.pet = rover
## ?? flipper is-a object of Fish
flipper = Fish()
## ?? crouse is-a object of Salmon
crouse = Salmon()
## ?? harry is-a object of Halibut
harry = Halibut()
print ""
print "This is me speaking as Person:"
gaurav = Person("Gaurav")
gaurav.speak()
print ""
print "This is me speaking as an Employee:"
gaurav = Employee("Gaurav Grover", 120000)
gaurav.speak()
gaurav.my_salary()
# bruno = Dog("Bruno")
# bruno.speak()
# mayank is the object of many classes
mayank = [Person("Mayank"), Animal("Mayank")] | false |
e0625a5687cc4a2b3d25ace6301be755abcf740c | KevinVaghani/ex01 | /2021-10-01_Vaghani_K_matrixMultiplication.py | 953 | 4.15625 | 4 | A=[]
print("Enter value for first matrix")
for i in range(3):
a=[]
for j in range(3):
j=int(input("enter input for ["+str(i)+"]["+str(j)+"]"))
a.append(j)
A.append(a)
B=[]
print("Enter value for second matrix")
for i in range(3):
b=[]
for j in range(3):
j=int(input("enter input for ["+str(i)+"]["+str(j)+"]"))
b.append(j)
B.append(b)
print("Value of first matrix")
for i in range(3):
for j in range(3):
print(A[i][j],end=" ")
print()
print("Value of second matrix")
for i in range(3):
for j in range(3):
print(B[i][j],end=" ")
print()
print("Multiplication of two 3*3 matrix")
result=[]
for i in range(3):
result.append([])
for j in range(3):
sum=0
for k in range(3):
sum=sum+(A[i][k]*B[k][j])
result[i].append(sum)
for i in range(3):
for j in range(3):
print(result[i][j],end=" ")
print()
| false |
b4061c0f5fd130dd7fa7d1f78a0edf84b32480fc | joaompinto/enclosed | /enclosed/__main__.py | 564 | 4.15625 | 4 | import argparse
from enclosed import Parser, is_enclosed
def main():
parser = argparse.ArgumentParser(description="Extract enclosed tokens from string")
parser.add_argument(
"target",
metavar="target",
type=str,
help="full string containing enclosed tokens",
)
args = parser.parse_args()
tokens_parser = Parser()
tokens = tokens_parser.tokenize(args.target)
enclosed_strs = [token[2] for token in tokens if is_enclosed(token)]
print(" ".join(enclosed_strs))
if __name__ == "__main__":
main()
| true |
b49f502b495aed530ecd17f4af988ef0f13a151b | BrucePorras/PachaQTecMayo2020-1 | /Semana3Sesion2/rcornejo/init.py | 1,062 | 4.21875 | 4 | #Este programa va hacer un carrito de compras
#Vamos a pedir el nombre del bodeguero.
print ("Hola ¿Cuál es tu nombre?")
strbodeguero = input()
print (f"{strbodeguero} ingresa tu primer producto")
lstproductos = []
lstproductounitario = []
strnombredelproducto = input()
print("Ingresa el valor del producto")
fltvalorproducto = float(input())
lstproductounitario.append(strnombredelproducto)
lstproductounitario.append(fltvalorproducto)
lstproductos.append(lstproductounitario)
print (lstproductounitario)
print (lstproductos)
print(f"{strbodeguero} Deseas agregar otro producto Y/N")
stropcion = input ()
if (stropcion == "Y"):
print (f"{strbodeguero} ingresa tu primer producto")
strnombredelproducto = input()
print("Ingresa el valor del producto")
fltvalorproducto = float(input())
lstproductounitario = []
lstproductounitario.extend([strnombredelproducto, fltvalorproducto])
lstproductos.append(lstproductounitario)
print (lstproductounitario)
print (lstproductos)
else:
print("Gracias por usar nuestro sistema")
| false |
ed01c5af7f7bbb690f7867bee4eeacfc38f8762e | juanmager/EstructurasDeDatos | /Recursividad/recursividad_fibonacci.py | 784 | 4.125 | 4 | # Ejercicio 3
# Implementar una función recursiva que calcule los números de la serie de Fibonacci.
# La función para generar la serie de Fibonacci es la siguiente (donde N es el índice
# del número en la serie):
# alt text
# Luego escribir un programa que pida un número N (mayor o igual a 0) al usuario e imprima por
# pantalla los primeros N números de la serie de Fibonacci
# Sobre la sucesion de Fibonacci:
# https://www.vix.com/es/btg/curiosidades/4461/que-es-la-sucesion-de-fibonacci
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
elif n > 1:
return fibonacci(n-1) + fibonacci(n-2)
# print(fibonacci(9))
repeats = int(input("Ingrese un numero entero positivo: "))
for x in range(repeats):
print(fibonacci(x))
| false |
eb3bab615bff56be26265fef235a7900259e4dc6 | zarjer/Cisco-BlackBeltLevel1 | /Task2.py | 789 | 4.125 | 4 | """
Zar Jerome C. Cajudo
Task 2
"""
#Libraries and Functions always come in handy to developers by allowing reusability of existing code.
#There are certain well known inherent libraries that you have access to after installing python.
#By using these libraries and functions in them,
#write a program (in Python 3) to guess a randomly generated number between 1 and 10.
#Hint: Figure out which library the “randint” function belongs to.
#-----------------------------------------------------------------------------------------------------
import random
a = random.randint(1,10)
while True:
b = int(input("Please enter a number: "));
if b == a:
print("Correct!");
break
elif b!= a:
print("Wrong number.Try again...");
| true |
601c9380d30a6e6291cc77ea76e798c9998c9142 | vinay432/inputs-from-the-user | /inputs from user.py | 434 | 4.21875 | 4 | #Taking inputs from user,we need to explain the user what type of input to be accepted by code like integer or float, it may be string type.
a=input("Enter your lucky number:") #a is a varable to store inputs which is given by user
print(a) #printing the lucky number out.
#if you wanna specify particularly, user can enter only strings then
a=str(input("enter your text here to dispaly:"))
print(a) #printing out the textZ
| true |
14b01be431db3db57e947f724d8978f98f2a3bb2 | Lisa-Mays/CMIS102_Assignments | /salesmanpay.py | 1,326 | 4.1875 | 4 | # This program calculates a salesman's weekly pay with a fixed hourly
# rate and a fixed commission percentage
# Set hourly rate to 27 dollars per hour Declare hourly_rate as float
hourly_rate = float(27.00)
# Set commission percentage to 25 percent
commission_percentage = 0.25
# Prompt for hours worked Declare hours_worked as int
hours_worked = int(input('Please enter your number of hours worked for this week: '))
# Prompt for total weekly sales Declare weekly_sales as float
weekly_sales = float(input('Please enter your total sales for this week: $'))
# Compute hourly rate and weekly commission and Set hourly pay, commission pay, and weekly pay
hourly_pay = hours_worked * hourly_rate
commission_pay = weekly_sales * commission_percentage
weekly_total_pay = hourly_pay + commission_pay
# Write hours worked, commission, and total pay for the week
print('Your total hours worked are: ', hours_worked)
print('Your hourly rate is : $', "{:.2f}".format(hourly_rate), "an hour")
print('Your base pay based on hours worked this week is: $', ("{:.2f}".format(hourly_pay)))
print('Your commission percentage of weekly sales is: ', commission_percentage, '%')
print('Your total commission for the week is: $', "{:.2f}".format(commission_pay))
print('Your total pay for the week is: $', "{:.2f}".format(weekly_total_pay)) | true |
a88885108e991e9b7204ee9cba4a5f1632406157 | gonsan20/misiontic | /Ciclo1/210619/main.py | 941 | 4.125 | 4 | from util import palabras, grafico
"""
Tareas
1. obtener palabra para adivinar
2. mostrar con __ las letras que conforman la palabra
3. preguntar por una letra al usuario
4. validar si la letra está en la palabra
5. mostrar las letras del palabra
6. preguntar por la palabra
7. validar si ha ganado o no
"""
def codificar_palabra(palabra):
print(type(palabra))
longitud = len(palabra) - 1
caracter = '__'
for i in range(longitud):
print(caracter, end=' ')
print()
def validar_letra(letra, palabra):
longitud = list(palabra)
if letra in palabra:
return True
else:
return False
"""
MAIN
"""
obj_palabras= palabras()
palabra_secreta = obj_palabras.get_palabra()
codificar_palabra(palabra=palabra_secreta)
print(palabra_secreta)
letra = input("Ingrese una letra: ")
esta_en_la_palabra = validar_letra(letra=letra, palabra=palabra_secreta)
dibujo = grafico()
print()
| false |
d7f76d7af932f16b1202d118982e8825b01e7816 | sunita18808/sunita18808 | /Len's Slice.py | 666 | 4.125 | 4 | # Your code below:
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]
prices = [2, 6, 1, 3, 2, 7, 2]
num_two_dollar_slices = prices.count(2)
num_pizzas = len(toppings)
print("We sell " + str(num_pizzas) + " different kinds of pizza!")
pizza_and_prices = [[2, "pepperoni"], [6, "pineapple"], [1, "chesse"], [3, "sausage"], [2, "olives"], [7, "anchovies"], [2, "mushrooms"]]
print(pizza_and_prices)
pizza_and_prices.sort()
cheapest_pizza = pizza_and_prices[0]
priciest_pizza = pizza_and_prices[-1]
pizza_and_prices.pop()
pizza_and_prices.append([2.5, "peppers"])
three_cheapest = pizza_and_prices[0:3]
print(three_cheapest) | true |
65f044891f824b888e9a1bcfb652ef32b0e76d7a | supermitch/Chinese-Postman | /chinesepostman/dijkstra.py | 2,163 | 4.125 | 4 | """Minimum Cost Path solver using Dijkstra's Algorithm."""
def summarize_path(end, previous_nodes):
"""
Summarize a chain of previous nodes and return path.
Chain is a dictionary linked list, e.g. {1: None, 2: 1, 3: None, 4: 2}
returns [1, 2, 4] for end = 4.
"""
route = []
prev = end
while prev:
route.insert(0, prev) # At beginning
prev = previous_nodes[prev]
return route
def find_cost(path, graph):
"""
Return minimum cost and route from start to end nodes.
Uses Dijkstra's algorithm to find shortest path.
"""
start, end = path
all_nodes = graph.node_keys
unvisited = set(all_nodes)
# Initialize all nodes to total graph cost (at least)
total_cost = graph.total_cost
node_costs = {node: total_cost for node in all_nodes}
node_costs[start] = 0 # Start has zero cost
previous_nodes = {node: None for node in all_nodes}
node = start
while unvisited: # While we still have unvisited nodes
for option in graph.edge_options(node).values():
next_node = option.end(node)
if next_node not in unvisited:
continue # Don't go backwards
# If this path was cheaper than the prior cost, update it:
if node_costs[next_node] > node_costs[node] + option.weight:
node_costs[next_node] = node_costs[node] + option.weight
previous_nodes[next_node] = node
unvisited.remove(node)
# Next node must be closest unvisited node:
options = {k: v for k, v in node_costs.items() if k in unvisited}
try:
# Find key of minimum value in a dictionary:
node = min(options, key=options.get) # Get nearest new node # type: ignore
except ValueError: # arg is empty sequence, aka dead ended
break
if node == end: # Since we're pathfinding, we can exit early
break
cost = node_costs[end]
shortest_path = summarize_path(end, previous_nodes)
return cost, shortest_path
if __name__ == '__main__':
import tests.run_tests
tests.run_tests.run(['dijkstra'])
| true |
1fc44e0f5bab8bd1caae1f070b6c8ea445d77ed2 | gitschwiftyyy/web_caesar | /caesar.py | 896 | 4.15625 | 4 | def encrypt(string, shift):
shift = int(shift)
shift = shift % 26
newstring = ""
for i in range(len(string)):
chrnumber = ord(string[i])
chrnumber = int(chrnumber)
if chrnumber > 64 and chrnumber < 91:
chrnumber = chrnumber + shift
if chrnumber > 90 and chrnumber < 97:
chrnumber = chrnumber % 90
chrnumber = chrnumber + 64
elif chrnumber > 96 and chrnumber < 123:
chrnumber = chrnumber + shift
if chrnumber > 122:
chrnumber = chrnumber % 122
chrnumber = chrnumber + 96
newchr = chr(chrnumber)
newstring = newstring + newchr
return newstring
def main():
string = input("Enter text: ")
shift = input("Encryption number: ")
print(encrypt(string, shift))
if __name__ == "__main__":
main() | false |
0733878ff327550bd6d688ec366b0c52dc1e11a0 | jainpiyush26/python_code_snippets | /python_tricks/namedtuples.py | 651 | 4.28125 | 4 | from collections import namedtuple
"""
syntax is to pass the object name and then the key names as a list of space
separated string,
I would prefer passing them explicitly as a list!
They are still tuples but can be used to store initial value of an object or
something like that
"""
test_obj = namedtuple('test_obj', ['obj_name', 'obj_fullname', 'obj_uid'])
test_obj_1 = test_obj('first', 'first_object', 1)
test_obj_2 = test_obj('second', 'second_object', 23)
print(test_obj_1)
print(test_obj_2)
print(test_obj._fields)
named_tuple_ordered_dict = test_obj_1._asdict()
for key, values in named_tuple_ordered_dict.items():
print(key, values)
| true |
bd4848b15e233d540097077f986b851f57586316 | oleg31947/jobeasy-algorithms-course | /lesson_4/HW_4/Count.py | 644 | 4.34375 | 4 | # Write a Python function, which will count how many times a character (substring)
# is included in a string. DON’T USE METHOD COUNT
# string = input(f"Enter a string ")
# substring = input(f"Enter a substring ")
def count(given_string, given_substring):
counter = 0
if len(given_substring) > len(given_string):
return counter
while given_string.find(given_substring) > -1:
index = given_string.find(given_substring)
given_string = given_string[index + len(given_substring):]
counter += 1
return counter
print(count('hello world of heroes', 'o'))
print('hello world of heroes'.count('o'))
| true |
3cf40241d8f485cc2e4b71a6ad9fc78f6093689c | oleg31947/jobeasy-algorithms-course | /lesson_4/No duplicate.py | 528 | 4.125 | 4 | # Your task is to remove all duplicate words from a string, leaving only single (first) words entries.
# Input
# 'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
# Output
# 'alpha beta gamma delta'
def no_duplicate(string):
array = string.split(' ')
result = []
for item in array:
if not (item in result):
result.append(item)
return ' '.join(result)
print(no_duplicate('alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'))
| true |
3d2de6b37d9b22649f370c9074f1cad602897279 | oleg31947/jobeasy-algorithms-course | /lesson_5/My_head_is_at_the_wrong_end.py | 735 | 4.1875 | 4 | # You're at the zoo... all the meerkats look weird. Something has gone terribly wrong - someone has gone
# and switched their heads and tails around!
# Save the animals by switching them back. You will be given an array which will have three values (tail, body, head).
# It is your job to re-arrange the array so that the animal is the right way round (head, body, tail).
# Same goes for all the other arrays/lists that you will get in the tests: you have to change the element positions
# with the same exact logics - simples!
def fix_the_meerkat(arr):
return arr[::-1]
print(fix_the_meerkat(['tail', 'body', 'head']))
print(fix_the_meerkat(['ground', 'rainbow', 'sky']))
print(fix_the_meerkat(['part3', 'part2', 'part1']))
| true |
d520ea776b4cffaf52273b1ecb9f3b550310b0ed | CoolHappyGuy/python-misc | /ElfName.py | 1,784 | 4.15625 | 4 | #This program determines your elf name based on the initial of the user's name as well as their birth month.
FirstInitial = {"a": "Perky", "b": "Nipper", "c": "Bubbles", "d": "Happy", "e": "Squeezy", "f": "Sunny", "g": "Merry",
"h": "Tootsie", "i": "Kringle", "j": "Puddin", "k": "Cookie", "l": "Tinker", "m": "Twinkle",
"n": "Buddy", "o": "Elfie", "p": "Jingle", "q": "Snowflake", "r": "Jolly", "s": "Elvis",
"t": "Sugarplum", "u": "Peaches", "v": "Gingerbread", "w": "Frisbee", "x": "Evergreen", "y": "Pinky",
"z": "Tinsel"}
BirthMonth = {"jan": "Angel-pants", "feb": "Floppy-feet", "mar": "Plum-pants", "apr": "McJingles", "may": "Peppermint",
"jun": "Toe-bells", "jul": "Sugarplum", "aug": "Sugar-socks", "sep": "Pickle-pants", "oct": "Sparkly-toes"
, "nov": "Monkey-buns", "dec": "Pointy-toes"}
#Prompt User for initial of first name and validate.
UserInitial = str(input("Please enter the initial of your first name: ")).lower()
while UserInitial not in FirstInitial:
print("Invalid! Please enter the letter (A-Z) of the initial of your first name.")
UserInitial = str(input("Please enter the initial of your first name: ")).lower()
#Prompt user for birth month and validate.
UserMonth = input("Please enter your birth month (first three letters of month): ").lower()
while UserMonth not in BirthMonth:
print("Invalid! Please enter the first 3 letters of your birthmonth (e.g. January = Jan, etc)")
UserMonth = input("Please enter your birth month (first three letters of month): ").lower()
# print("Your elf name is " + str(UserInitial) + " " + str(UserMonth) + ".")
print("\n" + "Your elf name is " + FirstInitial[UserInitial] + " " + BirthMonth[UserMonth] + ".")
| false |
e4cdb1a97f4b615353ec503717e9bc4ea0df60ef | mpv33/Advance-python-Notes- | /Threads/Threading.py | 1,307 | 4.15625 | 4 | #!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("Starting " + self.name)
print_time(self.name, 5, self.counter)
print("Exiting " + self.name)
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print("Exiting Main Thread")
'''
When the above code is executed, it produces the following result −
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
''' | true |
c4c521b0f14ce7a09573df822d15a5ff7160903f | sifatjahan230/Python-programming | /string/sWAP cASE.py | 572 | 4.3125 | 4 | '''
You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
For Example:
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
Input Format
A single line containing a string S.
Constraints
0<len(S)<=1000
Output Format
Print the modified string S.
'''
def swap_case(s):
out=''.join([i.lower() if i.isupper() else i.upper() for i in s])
return out
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
| true |
820536da887128b6ce19457d296550868b27443e | TanyoTanev/SoftUni---Python-Fundamentals | /Lists_adv_ElectronDistribution.py | 1,246 | 4.15625 | 4 | '''Electron Distribution
You are a mad scientist and you decided to play with electron distribution among atom's shells. You know that basic idea of electron distribution
is that electrons should fill a shell until it's holding the maximum number of electrons.
The rules for electron distribution are as follows:
Maximum number of electrons in a shell is distributed with a rule of 2n^2 (n being position of a shell a.k.a the list index + 1).
For example, maximum number of electrons in 3rd shield is 2*3^2 = 18.
Electrons should fill the lowest level shell first.
If the electrons have completely filled the lowest level shell, the other unoccupied electrons will fill the higher level shell and so on.'''
'''
input : Output
10
[2, 8]
44
[2, 8, 18, 16]'''
atom=[]
electrons = int(input())
i=0
'''
atom.append(2 * (0+1) ** 2)
electrons-=(2 * (0+1) ** 2)
i+=1
atom.append(2 * (1+1) ** 2)
electrons-=(2 * (1+1) ** 2)
i+=1
atom.append(2 * (2+1) ** 2)
electrons-=(2 * (2+1) ** 2)
i+=1'''
while electrons>0:
if 2*(i+1)**2> electrons:
atom.append(electrons)
electrons=0
else:
atom.append(2 * (i + 1) ** 2)
electrons -= (2 * (i + 1) ** 2)
i += 1
#print(i)
print(atom)
#print(electrons)
| true |
9ea71c52d86f9b499eecbba238cf33ffc46a0e59 | TanyoTanev/SoftUni---Python-Fundamentals | /Fund_Dictionaries - 6.Courses.py | 2,233 | 4.34375 | 4 | '''6.Courses
Write a program that keeps information about courses. Each course has a name and registered students.
You ewill be receiving a course name and a student name, until you receive the command "end". Check if such course already exists, and if not,
add the course. Register the user into th course. When you receive the command "end", print the courses with their names and total registered users,
ordered by the count of registered users in descending order. For each contest print the registered users ordered by name in ascending order.
Input
Until the "end" command is received, you will be receiving input in the format: "{courseName} : {studentName}".
The product data is always delimited by " : ".
Output
Print the information about each course in the following the format:
"{courseName}: {registeredStudents}"
Print the information about each student, in the following the format:
"-- {studentName}"
Examples
Input
Output
Programming Fundamentals : John Smith
Programming Fundamentals : Linda Johnson
JS Core : Will Wilson
Java Advanced : Harrison White
end
Programming Fundamentals: 2
-- John Smith
-- Linda Johnson
JS Core: 1
-- Will Wilson
Java Advanced: 1
-- Harrison White
Algorithms : Jay Moore
Programming Basics : Martin Taylor
Python Fundamentals : John Anderson
Python Fundamentals : Andrew Robinson
Algorithms : Bob Jackson
Python Fundamentals : Clark Lewis
end
Python Fundamentals: 3
-- Andrew Robinson
-- Clark Lewis
-- John Anderson
Algorithms: 2
-- Bob Jackson
-- Jay Moore
Programming Basics: 1
-- Martin Taylor
'''
courses = dict()
while True:
command = input().split(' : ')
if command[0] == 'end':
break
elif command[0] not in courses:
courses[command[0]] = [command[1]]
else:
courses[command[0]].append(command[1])
#print(courses)
#sorted_courses = dict( sorted(sorted_courses, key=lambda k: len(sorted_courses[k]), reverse=True))
sorted_courses = dict(sorted(courses.items(), key=lambda x:len(x[1]), reverse=True))
#print(sorted_courses)
for key in sorted_courses:
sorted_courses[key] = (sorted(sorted_courses[key], key= lambda x: x[0], reverse=False ))
for course in sorted_courses:
print(f"{course}: {len(sorted_courses[course])}")
for i in range(len(sorted_courses[course])):
print(f"-- {sorted_courses[course][i]}")
| true |
a555a9b776d85e3df2d9d0850bc76141bdc02d1b | TanyoTanev/SoftUni---Python-Fundamentals | /Classes Catalogues.py | 1,784 | 4.28125 | 4 | '''
Catalogue
Create a class Catalogue. The __init__ method should accept the name of the catalogue. Each catalogue should also have an attribute called
products and it should be a list. The class should also have three more methods:
add_product(product) - add the product to the product list
get_by_letter(first_letter) - returns a list containing only the products that start with the given letter
__repr__ - returns the catalogue info in the following format:
"Items in the {name} catalogue:
{item1}
{item2}
…"
The items should be sorted alphabetically (default sorting)
Example
Test Code
Output
catalogue = Catalogue("Furniture")
catalogue.add_product("Sofa")
catalogue.add_product("Mirror")
catalogue.add_product("Desk")
catalogue.add_product("Chair")
catalogue.add_product("Carpet")
print(catalogue.get_by_letter("C"))
print(catalogue)
['Chair', 'Carpet']
Items in the Furniture catalogue:
Carpet
Chair
Desk
Mirror
Sofa'''
class Catalogue:
def __init__(self, name):
self.name = name
self.products = []
def add_product(self, product):
self.products.append(product)
def get_by_letter(self, first_letter):
letter_list = []
for i in range(len(self.products)):
if self.products[i][0] == first_letter:
letter_list.append(self.products[i])
return letter_list
def __repr__(self):
result =""
result += f"Items in the {self.name} catalogue:\n"
result += '\n'.join(sorted(self.products))
return result
catalogue = Catalogue("Furniture")
catalogue.add_product("Sofa")
catalogue.add_product("Mirror")
catalogue.add_product("Desk")
catalogue.add_product("Chair")
catalogue.add_product("Carpet")
print(catalogue.get_by_letter("C"))
print(catalogue) | true |
5924f01f7768401e2789650b5c3d20ac165018b0 | CZnyu/rock-paper-scissors-exercise | /game.py | 1,292 | 4.125 | 4 | print("Rock, Paper, Scissors, Shoot!")
import random
arr = ["Rock","Paper","Scissors"]
def options (s):
if s == "Rock":
return arr[0]
if s == "rock":
return arr[0]
elif s == "Paper":
return arr[1]
elif s == "paper":
return arr[1]
elif s == "Scissors":
return arr[2]
elif s == "scissors":
return arr[2]
else:
return ("Hmmm...that's not an option. Try entering Rock, Paper, or Scissors", quit)
print("--------------------")
user_choice = input("Enter Rock, Paper, or Scissors Here: ")
item = options(user_choice)
print("YOU CHOSE:", item)
computer_choice = random.choice(arr)
print(f"COMPUTER CHOSE: '{computer_choice}'")
outcomes = {
arr[0]:{
arr[0]: None,
arr[1]: arr[1],
arr[2]: arr[0],
},
arr[1]:{
arr[0]: arr[1],
arr[1]: None,
arr[2]: arr[2],
},
arr[2]:{
arr[0]: arr[0],
arr[1]: arr[2],
arr[2]: None,
},
}
winning_choice = outcomes[user_choice][computer_choice]
if winning_choice:
if winning_choice == user_choice:
print("YOU WON")
elif winning_choice == computer_choice:
print("YOU LOST")
else:
print("TIE")
print("Thanks for playing. Please play again!") | false |
96be08c6e3211029ca2c689fd6d2110c2a7365e2 | thewalia/CP | /DS/LinkedList.py | 1,642 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.nextNode = None
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def insertStart(self, data):
self.size+=1
newNode = Node(data)
if not self.head:
self.head = newNode
else:
newNode.nextNode = self.head
self.head = newNode
def insertEnd(self, data):
self.size+=1
actualNode = self.head
newNode = Node(data)
while actualNode.nextNode is not None:
actualNode = actualNode.nextNode
actualNode.nextNode = newNode
def getSize(self):
return self.size
def removeNode(self, data):
if not self.head:
return
self.size-=1
currentNode = self.head
previousNode = None
while currentNode.data != data:
previousNode = currentNode
currentNode = currentNode.nextNode
if previousNode is None:
self.head = currentNode.nextNode
else:
previousNode.nextNode = currentNode.nextNode
def traverse(self):
actualNode = self.head
while actualNode is not None:
print(actualNode.data)
actualNode = actualNode.nextNode
# Driver Code
linkedList = LinkedList()
linkedList.insertStart(1)
linkedList.insertStart(2)
linkedList.insertEnd(3)
print(linkedList.getSize())
linkedList.traverse()
linkedList.removeNode(2)
print(linkedList.getSize())
linkedList.traverse() | true |
ffe716689c54473c7305bfebc5069a8b41b0ee8a | RayQinruiWang/SelfLearning | /Learning Space/Datascience/Python/Python notes.py | 849 | 4.59375 | 5 | ####################################### Data science with Python ########################################
# Dictionary
my_dict = {
"brand":"ford",
"model":"Mustang",
"year":1964
}
# or to use constructor dict
my_dict = dict(brand = "ford", model = "Mustang", year = 1964)
# To read by index
read_model = my_dict["model"]
# change value
my_dict["year"] = 1969
# loop through
## this print all keys
for keys in my_dict:
print item
## this print all values
for keys in my_dict:
print(my_dict[keys])
# or
for value in my_dict.values():
print(value)
# to print all key value pairs:
for key in my_dict:
print(key, my_dict[key])
# or
for key,value in my_dict.item():
print(key,value)
# pandas can form tables, access by index or index number, both in series or in dataframe format | true |
02eb1a5d54c1329cf1cfb8296782a739a4753508 | PBillingsby/CodewarsKata | /Python/oddoreven.py | 214 | 4.4375 | 4 | # Inputs integer and outputs if it is odd or if it is even
def even_or_odd(number):
if type(number) == int:
if int(number) % 2 == 0:
return ("Even")
else:
return ("Odd")
| true |
50c3767373e9c2a4eb0ee269e3b571907c342673 | isaszy/python_exercises | /types, conditional and variable/L1Ex10Triangulos.py | 299 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 10 22:08:26 2020
@author: isinha
"""
def triangulo (a: float, b: float, c: float) -> str:
if a + b > c or b + c > a or a + c > b:
return 'É lado de triângulo'
else:
return 'Não é lado de triângulo' | false |
80efc890da80fc7ec9eef9d50313399f899f315b | adhikaridev/python_assignment_II | /16_game_model_player_class_8puzzle.py | 2,839 | 4.46875 | 4 | # 16. Imagine you are creating a Super Mario game. You need to define
# a class to represent Mario. What would it look like? If you aren't
# familiar with SuperMario, use your own favorite video or board game
# to model a player.
# Because I am not familiar with Super Mario, I am trying to model a
# player of game 8-puzzle.
# It is played on a 3-by-3 grid with 8 square blocks labeled 1 through 8
# and a blank square. Your goal is to rearrange the blocks so that they are
# in order. You are permitted to slide blocks horizontally or vertically
# into the blank square. The following shows a sequence of legal moves
# from an initial board position (left) to the goal position (right).
class EightPuzzle:
goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
def __init__(self, board_config):
self.board_config = board_config
def show_current_board(self):
print(self.board_config)
def move_right(self):
blank_position = self.board_config.index(0)
if blank_position != 2 and blank_position != 5 and blank_position != 8:
self.board_config[blank_position] = self.board_config[blank_position+1]
self.board_config[blank_position+1] = 0
else:
print("Not possible to move right.")
def move_left(self):
blank_position = self.board_config.index(0)
if blank_position != 0 and blank_position != 3 and blank_position != 6:
self.board_config[blank_position] = self.board_config[blank_position-1]
self.board_config[blank_position-1] = 0
else:
print("Not possible to move left.")
def move_up(self):
blank_position = self.board_config.index(0)
if blank_position != 0 and blank_position != 1 and blank_position != 2:
self.board_config[blank_position] = self.board_config[blank_position-3]
self.board_config[blank_position-3] = 0
else:
print("Not possible to move up.")
def move_down(self):
blank_position = self.board_config.index(0)
if blank_position != 6 and blank_position != 7 and blank_position != 8:
self.board_config[blank_position] = self.board_config[blank_position+3]
self.board_config[blank_position+3] = 0
else:
print("Not possible to move down.")
def goal_test(self):
if self.board_config == EightPuzzle.goal:
print("Congratulations! You have reached the goal.")
else:
print("Goal not reached yet.")
# Here 0 acts as a blank cell
initial = [7, 1, 3, 4, 2, 5, 0, 8, 6]
game1 = EightPuzzle(initial)
game1.show_current_board()
game1.move_right()
game1.show_current_board()
game1.move_left()
game1.show_current_board()
game1.move_up()
game1.show_current_board()
game1.move_down()
game1.show_current_board()
game1.goal_test()
| true |
729b3bf3510acb4897088e31b25b47175e057e8c | adhikaridev/python_assignment_II | /10_camel_snake_kebab.py | 761 | 4.5625 | 5 | # 10. Write a function that takes camel-cased strings (i.e.
# ThisIsCamelCased), and converts them to snake case (i.e.
# this_is_camel_cased). Modify the function by adding an argument,
# separator, so it will also convert to the kebab case
# (i.e.this-is-camel-case) as well.
def to_snake_or_kebab(camel, separator):
converted = ""
start = 0
for i in range(1, len(camel), 1):
if camel[i].isupper():
converted = converted + camel[start:i] + separator
start = i
converted = converted + camel[start:]
return converted.lower()
camel = input("Enter a camel-cased string: ")
snake = to_snake_or_kebab(camel, "_")
kebab = to_snake_or_kebab(camel, "-")
print("Snake-cased: ", snake)
print("Kebab-cased: ", kebab)
| true |
f69b77574ae862d8fde1040d31fa1e6a5cac9010 | malikyilmaz/Class4-PythonModule-Week4 | /3- Number Guessing Game.py | 1,926 | 4.21875 | 4 | """
WAs a player, I want to play a game which I can guess a number the computer chooses in the range I chose.
So that I can try to find the correct number which was selected by computer.
Acceptance Criteria:
Computer must randomly pick an integer from user selected a range, i.e., from A to B, where A and B belong to Integer.
Your program should prompt the user for guesses
if the user guesses incorrectly, it should print whether the guess is too high or too low.
If the user guesses correctly, the program should print total time and total number of guesses.
You must import some required modules or packages
You can assume that the user will enter valid input.
"""
import random
from time import time
print("******************************************************\n"
"*** Quess the number ***\n"
"******************************************************")
print("Enter the range of the game")
while True:
try:
low_lim = int(input('Please Enter Lower Limit of Prediction: '))
upp_lim = int(input('Please Enter Upper Limit of Prediction: '))
break
except ValueError:
print("Please enter only number")
t_time = time()
number = random.randint(low_lim, upp_lim)
counter = 0
guess = []
print("***I'm ready. Guess my number***")
while guess != number:
counter += 1
try:
guess = int(input("\nEnter your guess: "))
except (ValueError, TypeError):
print("Please enter a number")
if guess > number:
print("Try again! It is Too high...")
elif guess < number:
print("Try again! It is Too low...")
else:
print("\nCongratulation!!!")
print("My Number is", number)
print("Total number of your guesses, ", counter)
t_time = time() - t_time
print("Total time of your guesses, ", round(t_time, 1), "seconds")
| true |
5f8cba55b7a5ee2e8ccf448ae4d4603592d22296 | CWxMaxX/al_python_demo | /Day 1 Basic/Test5.py | 417 | 4.25 | 4 | a = float(input("Number A : "))
b = float(input("Number B : "))
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
modulus = a % b
expoment = a ** b
floorDivision = a // b
print("A + B = ", addition)
print("A - B =", subtraction)
print("A * B =", multiplication)
print("A / B =", division)
print("A % B =", modulus)
print("A ** B =", expoment)
print("A // B =", floorDivision)
| false |
5e58817bdbd6be6b022b467bc79ae44861a4b664 | PyOrSquare/Python | /Module 1/m1_circumference.py | 209 | 4.5 | 4 | # Calculate Circumference of a Circle with known radius
# c = 2 * Pi * radius
import math
print('Enter Radius')
r=input()
c=2*math.pi*r
print ('Circumference of the Circle with radius %d cms = %.2f'% (r,c))
| true |
2712a9f2890a5e022ac77e54665d0ff38a2a81df | Ritzing/Algorithms-2 | /TernarySearch/Python/ternary.py | 647 | 4.25 | 4 | def ternary_search (L, key):
left = 0
right = len(L) - 1
while left <= right:
ind1 = left
ind2 = left + (right - left) // 3
ind3 = left + 2 * (right - left) // 3
if key == L[left]:
print("Key found at:" + str(left))
return
elif key == L[right]:
print("Key found at:", str(right))
return
elif key < L[left] or key > L[right]:
print("Unable to find key")
return
elif key <= L[ind2]:
right = ind2
elif key > L[ind2] and key <= L[ind3]:
left = ind2 + 1
right = ind3
else:
left = ind3 + 1
return
| true |
186938082eae6b93c9f8d872b59b26e0af6a5e56 | Ritzing/Algorithms-2 | /SelectionSort/Python/selectionSort.py | 906 | 4.40625 | 4 | def selection_sort(array):
"""
Selection sort sorts an array by placing the minimum element element
at the beginning of an unsorted array.
:param array A given array
:return the given array sorted
"""
length = len(array)
for i in range(0, length):
min_index = i # Suppose that the first (current) element is the minimum of the unsorted array
for j in range(i+1, length):
# Update min_index when a smaller minimum is found
if array[j] < array[min_index]:
min_index = j
if min_index != i:
# Swap the minimum and the initial minimum positions
array[min_index], array[i] = array[i], array[min_index]
return array
# Example:
if __name__ == '__main__':
example_array = [5, 6, 7, 8, 1, 2, 12, 14]
print(example_array)
print(selection_sort(example_array))
| true |
2e502c966ce9329c238908a49e712e8c712b8f02 | waliasandeep/Learn-python-the-hard-way | /Ex11.py | 507 | 4.21875 | 4 | #Exercise 11
#Taking basic inputs from the user
print "How old are you?"
age = raw_input()
print "How tall are you?"
height = raw_input()
print "How much do you weigh?"
weight=raw_input()
print "So you are %r years old,%r tall and %r heavy." %(age,
height, weight)
#Skipping excersice 12 as it is making you do the same difference
#being age = raw_input("How old are you")
# another useful thing to learn from this excersice is
#-m pydoc raw_input which will show us what raw_input does
| true |
75f45ea5b4e661377fc66e6c70fb99ae58208473 | tapsevarg/1st-Semester | /Session 08/Activity1.py | 600 | 4.25 | 4 | # This is a program for creating multiplication tables.
def get_value():
print("Enter value to multiply")
value = int(input())
return value
def get_expressions():
print("Choose number of expressions")
expressions = int(input())
return expressions
def process_math(value, expressions):
count = 1
while count <= expressions:
result = value * count
print(str(value) + " x " + str(count) + " = " + str(result))
count += 1
def main():
value = get_value()
expressions = get_expressions()
process_math(value, expressions)
main()
| true |
de9dfa0449f1ff51bd61f2f0c5f514a58a4c1bfb | nnekaou/TriTesting | /TestTriangle.py | 2,090 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from Triangle import classifyTriangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html has a nice description of the framework
class TestTriangles(unittest.TestCase):
# define multiple sets of tests as functions with names that begin
#right triangles
def testRightTriangleA(self):
self.assertEqual(classifyTriangle(3,4,5),'Right','3,4,5 is a Right triangle')
def testRightTriangleB(self):
self.assertEqual(classifyTriangle(5,3,4),'Right','5,3,4 is a Right triangle')
#equilateral triangles
def testEquilateralTriangleA(self):
self.assertEqual(classifyTriangle(1,1,1),'Equilateral','1,1,1 should be equilateral')
def testEquilateralTriangleB(self):
self.assertEqual(classifyTriangle(7,7,7),'Equilateral','7,7,7 should be equilateral')
#isosceles triangles
def testIsoscelesTriangleA(self):
self.assertEqual(classifyTriangle(3,4,4), 'Isosceles', '3,4,4 should be isosceles')
def testIsoscelesTriangleB(self):
self.assertEqual(classifyTriangle(6,5,6), 'Isosceles', '6,5,6 should be isosceles')
#scalene triangles
def testScaleneTriangleA(self):
self.assertEqual(classifyTriangle(5,6,7), 'Scalene', '5,6,7 is scalene')
def testScaleneTriangleB(self):
self.assertEqual(classifyTriangle(8,7,6), 'Scalene', '9,1,3 is scalene')
#not valid test
def testInvalidInputA(self):
self.assertEqual(classifyTriangle(5000,4000,3000), 'InvalidInput', 'Outside of 200 pt parameter')
def testInvalidInputB(self):
self.assertEqual(classifyTriangle(5,-4,-3), 'InvalidInput', 'Two factors are negative')
def testInvalidInputC(self):
self.assertEqual(classifyTriangle(3.5,4,3), 'InvalidInput', 'Invalid instance')
if __name__ == '__main__':
print('Running unit tests')
unittest.main()
| true |
cdd2e6f8f01af3a67c7baca73969ef21360d0062 | phifertoo/python_basics | /basics/referencing.py | 1,021 | 4.40625 | 4 | # Variables are just references to a value
# although you modify the new reference (cheese), the new reference still points to the same data [0, 1, 2, 3, 4, 5]
# therefore, any references pointing to the same data will reflect the altered data
spam = [0, 1, 2, 3, 4, 5]
cheese = spam
cheese[1] = 'hello'
print(cheese) # [0, 'hello', 2, 3, 4, 5]
print(spam) # [0, 'hello', 2, 3, 4, 5]
#________________________________________________________________________________________________________
def eggs(input):
input.append('hello')
# although the input variable is destroyed after eggs() is called, input is a reference to my_list.
# therefore, the original data (my_list) is altered
my_list = [1, 2, 3]
eggs(my_list)
print(my_list)
import copy
# instead of creating a reference to the list, we can create a whole new list, we can use deepcopy
deepcopy = copy.deepcopy(spam)
deepcopy[0] = 'start'
print(deepcopy)
print(spam) # spam is unaffected by the changes we made to deepcopy | true |
9b20ec2adb891724dd57f4e8a012a160f2d8773f | MohitPanchasara/Sorting-Algorithms | /Heap and Heap Sort.py | 2,510 | 4.28125 | 4 | # Build Heap
# Heap Inserton
# Heap Deletion
# Heap Sort
import time
import random
def Swap(Heap , i , j):
Heap[i] , Heap[j] = Heap[j] , Heap[i]
def heapify(Heap, n, i):
largest = i
left_child = 2 * i + 1
right_child = 2 * i + 2
if left_child < n and Heap[i] < Heap[left_child]:
largest = left_child
if right_child < n and Heap[largest] < Heap[right_child]:
largest = right_child
if largest != i:
Swap(Heap , largest , i)
heapify(Heap, n, largest)
def delete_root(Heap , size):
element = Heap[0]
Heap[0] = Heap[size - 1]
heapify(Heap , size - 1 , 0)
return element
def Heap_Sort(Heap):
size = len(Heap)
for i in range ((size // 2) - 1 , -1 , -1):
heapify(Heap , size , i)
for i in range (size - 1 , 0 , -1):
Swap(Heap , 0 , i)
heapify(Heap , i , 0)
def Heapify_One_element(Heap , size , i):
parent = int((i - 1) / 2)
S = int(i)
if Heap[S] > Heap[parent]:
Swap(Heap , parent , S)
Heapify_One_element(Heap , size , parent)
def Insert_Node(Heap , size , key):
Heap.append(key)
Heapify_One_element(Heap , size , size)
# driver code to run program
Heap = []
#initially a empty array/list is created
#INSERTION OF EACH ELEMENT
time_Insertion_1 = time.time()
#start time
for i in range(1 , 2001):
Insert_Node(Heap, len(Heap) , i)
#inserts each element and heapify simultaneously
time_Insertion_2 = time.time()
#end time
print("The time taken for running the insertion of heap element one by one :")
#runtime in seconds and microseconds
print(f"{time_Insertion_2 - time_Insertion_1} seconds")
print("-------------------------------------------------------------------------")
#DELETION OF ROOT
time_Insertion_1 = time.time()
#start time of deletion
print("Time Taken in perfoming the deetion of root operation :")
p = delete_root(Heap , len(Heap))
time_Insertion_2 = time.time()
#endtime
#runtime in seconds and microseconds
print(f"{time_Insertion_2 - time_Insertion_1} seconds")
print("-------------------------------------------------------------------------")
#HEAP SORT
time_Insertion_1 = time.time()
#start time
print("Time taken in perfoming the Heap sort algorithm :")
Heap_Sort(Heap)
time_Insertion_2 = time.time()
#end time
#runtime in seconds and microseconds
print(f"{time_Insertion_2 - time_Insertion_1} seconds") | false |
b0a661b051a1df590b2228e5e37fc76b06dcced3 | S-Luther/school-python | /Python-Sam/EvenOdd.py | 336 | 4.4375 | 4 | ##Sam Luther
##EvenOdd: It tells you whether or not a inputed number is even
##11/3/16
n=float(input("Please input a number to see if it is even:"))
def is_odd(n):
c = float(n%2)
if(c==0):
print(str(n)+' is an even number.')
if(c!=0):
print(str(n)+' is not an even number.')
is_odd(n)
| true |
2a1acdf65abf610bdee548968a102a98f5bc4e30 | S-Luther/school-python | /Python-Sam/paskal.py | 864 | 4.21875 | 4 | # -----------------------------------------+
# Sam Luther |
# pascasl.py |
# Last Updated: January 9, 2016 |
# -----------------------------------------|
# It is a program |
# -----------------------------------------+
def combination(n, k):
valueToReturn = 0
if(k==0 or k == n):
return "1"
else:
valueToReturn = valueToReturn + int(combination(n-1,k-1)) + int(combination(n-1,k))
return valueToReturn
def pascals_triangle(rows):
for row in range(rows):
answer = ""
for column in range(row + 1):
answer = answer + str(combination(row, column)) + "\t"
print(answer)
while(True):
entered = int(input("Input a number to enter paskals triangle: "))
pascals_triangle(entered)
| false |
43d8232bf0fbbf7f83083db65ae42d023a1bfdcf | S-Luther/school-python | /Bernard/ThreeTurtleLearn.py | 1,010 | 4.40625 | 4 | #ThreeTurtleLearn
#Bernard Kintzing
#10/25/16
import turtle
#Go to where the mouse is clicked
screen = turtle.Screen()
screen.onclick(turtle.goto)
#Actions based off of key pressed
i = 0
def up():
while(1 == 1):
turtle.forward(1)
def down():
while(1 == 1):
turtle.forward(-1)
def right():
while(1 == 1):
turtle.right(1)
def left():
while(1 == 1):
turtle.left(1)
def red():
turtle.pencolor('red2')
def blue():
turtle.pencolor('blue')
def green():
turtle.pencolor('green3')
def space():
if(i == 0):
turtle.pu()
i = i + 1
if(i == 1):
turtle.pd()
i = i - 1
screen.listen()
screen.onkeypress(up,'Up')
screen.onkeypress(down,'Down')
screen.onkeypress(right,'Right')
screen.onkeypress(left,'Left')
screen.onkey(red, 'r')
screen.onkey(green, 'g')
screen.onkey(blue, 'b')
screen.onkey(space, 'space')
#Drag the turtle around
turtle.ondrag(turtle.goto)
| false |
9a2e7a4b11a51d2891e50055d4e76666e2db3012 | afs2015/SmallPythonProjects | /FunPythonProjects/Summation.py | 387 | 4.21875 | 4 | #!/usr/bin/python
# Author: Andrew Selzer
# Purpose: Simple function that sums all numbers for a provided integer
# Example: 5 would return 1 + 2 + 3 + 4 + 5 a.k.a., 15
print ("Type summation(number) to use this program.")
def summation(num):
counter = 1
tot = 0
while (counter <= num):
tot += counter
counter += 1
return tot
| true |
6d849def5e8612e54a2016f4c0e775b753d56323 | afs2015/SmallPythonProjects | /FunPythonProjects/StringReverser.py | 308 | 4.71875 | 5 | #!/usr/bin/python
# Author: Andrew Selzer
# Purpose: Simple function to use reverse a string.
print ("Type reverse(text) to use this program.")
# This works by reading a string a single character at a time and appending it to a variable.
def reverse(text):
a=""
for i in text:
a=i+a
return a | true |
e5bd4c753f78731fa381f5b3fa2e7211cf14a5ae | Ashuduklan/Algorithms | /Array_Exercise.py | 2,462 | 4.40625 | 4 | # 1. Let us say your expense for every month are listed below,
# January - 2200
# February - 2350
# March - 2600
# April - 2130
# May - 2190
# Create a list to store these monthly expenses and using that find out,
#
# 1. In Feb, how many dollars you spent extra compare to January?
# 2. Find out your total expense in first quarter (first three months) of the year.
# 3. Find out if you spent exactly 2000 dollars in any month
# 4. June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list
# 5. You returned an item that you bought in a month of April and
# got a refund of 200$. Make a correction to your monthly expense list
# based on this
# Solution 1.
Month_expences = [2200, 2350, 2600, 2130, 2190]
print(Month_expences[1]- Month_expences[0], "Dollars")
print("Total expense in first quarter: ",Month_expences[0]+Month_expences[1]+Month_expences[2])
for item in Month_expences:
if item==2000:
print("Yes")
else:
print("No")
A= Month_expences.append(1980)
print(Month_expences)
Month_expences[3] = 1930
print(Month_expences)
# 2. You have a list of your favourite marvel super heros.
# heros=['spider man','thor','hulk','iron man','captain america']
# Using this find out,
#
# 1. Length of the list
# 2. Add 'black panther' at the end of this list
# 3. You realize that you need to add 'black panther' after 'hulk',
# so remove it from the list first and then add it after 'hulk'
# 4. Now you don't like thor and hulk because they get angry easily :)
# So you want to remove thor and hulk from list and replace them with doctor strange (because he is cool).
# Do that with one line of code.
# 5. Sort the heros list in alphabetical order (Hint. Use dir() functions to list down all functions available in list)
# solution 2
heroes = ['spider-man', 'thor', 'hulk', 'iron man', 'captain america']
print(len(heroes))
updated = heroes.append("Black panther")
print(heroes)
heroes.remove("Black panther")
heroes.insert(3, "Black panther")
print(heroes)
heroes[1:3]= ["docter-strange"]
print(heroes)
heroes.sort()
print(heroes)
# 3. Create a list of all odd numbers between 1 and a max number. Max number is something
# you need to take from a user using input() function
# solution 3
max_num = int(input("Write the number: "))
li =[]
i = 0
while(i<max_num):
i = i+1
if i%2!=0:
li.append(i)
print(li)
| true |
41a05c88202898e224c10adb9c8cfe8516926f3f | youzhian/helloPython | /IfAndElsePractice.py | 1,053 | 4.125 | 4 | # -*- coding: utf-8 -*-
age = 20
if age >= 18:
print("your age is",age)
print("adult")
# elif是 else if的缩写
age = 3
print("your age is",age)
if age >= 18:
print("adult")
elif age >= 6:
print("teenager")
else:
print("kid")
# 使用input()与int()
s = input("你的出生年份:")
brith = int(s)
if brith < 2000:
print("00前")
else:
print("00后")
# 练习题,小明身高1.75m,体重80kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数得到结果
# 低于18.5:过轻
# 18.5-25:正常
# 25-28:过重
# 28-32:肥胖
# 高于32:严重肥胖
xmHeigth = 1.75
xmWeigth = 80
xmBMI = xmWeigth/xmHeigth**2
# 判断结果
if xmBMI < 18.5:
result = "过轻"
elif xmBMI <= 25:
result = "正常"
elif xmBMI <= 28:
result = "过重"
elif xmBMI <= 32:
result = "肥胖"
elif xmBMI > 32:
result = "严重肥胖"
print("小明身高为:", xmHeigth, ",体重为:", xmWeigth, ",其BMI值为:", xmBMI, "评判结果为:", result)
| false |
080b9c3e24cdb07ae7385ea5579868798853c437 | Shantanu1395/Algorithms | /LinkedList/endTofront.py | 961 | 4.15625 | 4 | class Node(object):
def __init__(self,data):
self.data=data
self.next=None
class LinkedList(object):
def __init__(self):
self.head=None
def length(head):
temp=head
count=0
while temp!=None:
count+=1
temp=temp.next
return count
def printList(head):
temp=head
while temp!=None:
print(temp.data,end=' ')
temp=temp.next
print()
def LastToFront(head):
temp=head
previous=None
while temp.next!=None:
previous=temp
temp=temp.next
temp.next=head
previous.next=None
head=temp
return head
l=LinkedList()
l.head=Node(1)
l.head.next=Node(2)
l.head.next.next=Node(3)
l.head.next.next.next=Node(4)
l.head.next.next.next.next=Node(5)
l.head.next.next.next.next.next=Node(6)
l.head.next.next.next.next.next.next=Node(7)
printList(l.head)
l.head=LastToFront(l.head)
printList(l.head)
| false |
d9a9d80a3d4129521c5b10a7762e499565d16754 | goatber/dice_py | /main.py | 1,342 | 4.1875 | 4 | """
Dice Rolling Simulator
by Justin Berry
Python v3.9
"""
import random
class Die:
"""
Creates new die with methods:
roll
"""
def __init__(self, sides: int):
self.sides = sides
def roll(self) -> int:
"""
Rolls die, returns random number
based on probability
"""
result = random.randint(1, self.sides)
return result
def main():
"""
Runs simulator
"""
choosing_sides = True
print("----------\n"
"Type 'stop' to end program at any time"
)
while choosing_sides:
print("----------")
inp = input("How many sides should the die have? (4, 6, 8, 12, etc):\n")
if inp.isalpha():
if inp == "stop":
raise SystemExit()
if inp.isdigit():
inp = int(inp)
if inp > 0:
if inp < 1000:
die = Die(inp)
print("You rolled a:", die.roll())
else:
print("Die must have less than 1000 sides.")
else:
print("Die must have more than 0 sides.")
else:
print("Input must be numeric (including '-').")
# Run game on compile:
if __name__ == "__main__":
main()
| true |
d655cce31f34b46df4a649ba9b3cdd34cf13e076 | chapman-cpsc-230/hw3-massimolesti | /turtlestarter.py | 527 | 4.15625 | 4 | import turtle
def draw_reg_polygon(t,num_sides,side_len):
t.left(30)
for i in range(num_sides):
t.forward(side_len)
t.left(360.0/num_sides)
# Ask user for input here.
# Now create a graphics window.
t = turtle.Pen()
for j in range (3):
draw_reg_polygon(t,6,50)
t.right(150)
# Put the rest of your code can go here
# Prevent the graphics window from diappearing too
# quickly to see it.
stopper = raw_input("Hit <enter> to quit.")
# Now remove the graphics window before exiting.
turtle.bye()
| true |
e620ea1e1a2a45e5e0cbbd29951d6f20eae70228 | Kulbhushankarn/Find-area-of-circle | /code.py | 241 | 4.25 | 4 | #area of circle
#This code is written by Kulbhushan Karn
print ("Find the area of circle")
r = float(input("Enter the radius:"))
if (r>= 0 and r <= 100) :
area = 3.14 *r*r
print("area : %f " %area )
else :
print("Enter valid number upto 100")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.