blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
90cbdf3e418a8a18219d24148c7b5e3fa52d977f
darkmatter18/Udacity-Computer-Vision-Nanodegree
/CVND_Exercises/3_5_State_and_Motions/3. color.py
1,164
4.375
4
import matplotlib.pyplot as plt ''' The color class creates a color from 3 values, r, g, and b (red, green, and blue). attributes: r - a value between 0-255 for red g - a value between 0-255 for green b - a value between 0-255 for blue ''' class Color(object): # Initializes a color with rgb values def __init__(self, r, g, b): self.r = r self.g = g self.b = b # Called when a Color object is printed out def __repr__(self): '''Display a color swatch and returns a text description of r,g,b values''' plt.imshow([[(self.r/255, self.g/255, self.b/255)]]) return 'r, g, b = ' + str(self.r) + ', ' + str(self.g) + ', ' + str(self.b) ## TODO: Complete this add function to add two colors together def __add__(self, other): '''Adds the r, g, and b components of each color together and averaging them. The new Color object, with these averaged rgb values, is returned.''' r = (self.r + other.r)/2 g = (self.g + other.g)/2 b = (self.b + other.b)/2 return Color(r, g, b)
true
0fa7b1641e51a4253c1e4349746bfc200f1dc8d3
dev-tilda/SCAMP-Assesment
/fibonacci.py
280
4.375
4
def fibonacci (n): if n<=1: return n else: return (fibonacci(n-1) + fibonacci(n-2)) if __name__ == "__main__" : n= int(input("Enter the number you want to output the fibonacci sequence of: ")) for n in range (0,n): print (fibonacci(n))
false
259498a1ddae3ec96c0bffaa872ca1d7869c8ee5
WalaaAbdeltwwab/FAcoders
/Python/exr2.py
465
4.25
4
print('Rock Paper Scissors') player1_choice=input('Please Player 1,Enter one matching one of these three words: ') player2_choice=input('Please Player 2,Enter one matching one of these three words: ') if player1_choice=='Rock' and player2_choice=='Scissors' or player1_choice=='Scissors' and player2_choice=='Paper' or player1_choice=='Paper' and player2_choice=='Rock' : winner='Player 1' else : winner='Player 2' print(winner + ' wins,, Congratulations')
true
f752db4f22c46258b18ee82266526b23fe12c011
xiangtian/pytest
/class_learning/slots_in_inherit.py
947
4.15625
4
""" This will show how to restrict attr of instance Only attr in __slot__ can instance has, If subClass has __slots__, it will inherit __slots__ from Parent. or Parent's __slots__ has no effect on the child attr. Author: xiangtian.hu Date: 2017-6-9 """ class Parent: """instance of Parent attr in __slots__""" __slots__ = ("name", "age") def __init__(self, name, age): self.name = name self.age = age class Child(Parent): pass class Child2(Parent): __slots__ = tuple() pass if __name__ == "__main__": child = Child("Child", 10) child.salary = 0 # Parent's slot will not affect child's attribute if Child has no __slot__ child2 = Child2("Child2", 2) child2.salary = 0 # Parent's slot will affect child's attribute, this will cause error parent = Parent("Parent", 30) parent.salary = 10000 # add salary to Parent instance will cause error
true
cde87c2e000094dce60e6b9b79f84554a92e54e6
irinaignatenok/Dev-Inst
/Week7/Day3/ExeXP/ExeXP2.py
1,406
4.15625
4
def get_age(year, month, day): curr_year = 2020 curr_month = 6 curr_day = 6 curr_age = curr_year - year if curr_month < month: return curr_age - 1 elif curr_month > month: return curr_age elif curr_day < day: return curr_age - 1 else: return curr_age def can_retire(age, sex): if (sex == "M" and age >= 67) or (sex == "F" and age >= 65): return True else: return False def favourite_shirt_pos(size="L", text="I Love Python"): print(f"you ordered a shirt sized {size} with a '{text}' as text") def describe_city(city ="Tel Aviv", country ="Israel"): print(f"{city} is in {country}") def display_message(): print("I am learning hot to properly use functions") def main(): # exe1 year, month, day = input("enter you birthday in format YYYY/MM/DD \n>>").split("/") age = get_age(int(year), int(month), int(day)) sex = input("enter your sex F or M\n>> ") if can_retire(age, sex): print("you can retire") else: print("you can't retire just yet") # exe2 favourite_shirt_pos("XL", "you say a villain like it's a bad thing") favourite_shirt_pos("M") favourite_shirt_pos() # exe3 describe_city() describe_city("Tokyo","Japan") describe_city("Pskov","Russia") # exe4 display_message() if __name__ == "__main__": main()
false
00ba50486256034243b00259b622416106c8d76f
irinaignatenok/Dev-Inst
/Week10/Day1/exe Gold.py
762
4.21875
4
from datetime import date from datetime import timedelta import holidays def countownd(today): days_between = date(2021, 1, 1) - today for i in range(days_between.days, 0, -1): print(f"there are {i} days until january first") print("\n\n") def next_holiday(today): i = 1 holi_day = "" while True: if holidays.Israel().get(timedelta(days=i) + today): holi_day = holidays.Israel().get(today + timedelta(days=i)) break i += 1 for i in range(i, 0, -1): print(f"there are {i} day until {holi_day}") print(f"{holi_day} is today!") def main(): today = date.today() print(today) countownd(today) next_holiday(today) if __name__ == "__main__": main()
false
98c10ca11dc8b52e18275d7892ddc517c2c6d783
Emily-Garcia/CursoDjango_While
/dict_operations.py
750
4.1875
4
cellphone = { 'marca': 'Xiomi', 'RAM': 6, 'almacenamiento': 64, 'color': 'negro' } print('La marca es:', cellphone['marca']) new_marca = input('Dame el nombre de la nueva marca: ') #ACTUALIZAR VALOR EN UN DICCIONARIO cellphone['marca'] = new_marca print(cellphone) #AGREGAR UN NUEVO ELEMENTO AL DICCIONARIO so = input('Cual es el sistema operativo?: ') cellphone['so'] = so print(cellphone) #ELIMINAR UN ELEMENTO DE UN DICCIONARIO print('ELIMINAMOS COLOR') del cellphone['color'] print(cellphone) for clave, valor in cellphone.items(): print(f'La clave es: {clave}, y su valor es {valor}') for clave in cellphone.keys(): print('La clave es: ', clave) for value in cellphone.values(): print('El valor es: ', value)
false
d9e1f19dc6f1686342c64311e9ec0af2d9ff1433
sheeba23/pythonprograms
/4_report_card.py
2,846
4.28125
4
"""Write a program to generate student score card/exam report. Please take input from user, it contains 4 subjects(maths, science, s.s, english) mark, name of the student and standard. You will need to generate score report based on below cases.. 1.Any subject mark less than 18 then student will be failed. 2. Calculate percentage for 4 subjects.make sure that user will give input mark out of 50. 3.Exam report will include class(failed, second, first, distinction) of the student which he/she will get based on percentage.. If percentage is A.less than 35, class should be failed. B.less than 60 but greater than or equals 35, class should be second. C.less than 70 but greater than 60, class should be first. D. Above or equals 70, class should be distinction.""" import re regex_special_char= re.compile("[@_!#$%^&*()<>?/'/'\'/'|}{~;:]") regex_numbers = re.compile("[0-9]") def calculate_percentage(): avg = (maths + ss + sci + eng) per = (avg / 200) * 100 student_class = "" print(f"Percentage : {per}%") if (per >= 35 and per < 60): student_class = "Second Class" elif (per < 70 and per >= 60): student_class = "First Class" else: student_class = "Distinction" print (f"class :-{student_class}") def print_marks(): print("***Report Card***") print(f"Name: {student_name.strip()}\nStandard: {student_standard} class") print("***Subject & Marks***") print(f"Maths: {maths}\nSS: {ss}\nScience: {sci}\nEnglish: {eng}") try: student_name = str(input("Please enter student name: ")) if regex_numbers.search(student_name) is not None: print("Please do not enter digits in student name") exit() if regex_special_char.search(student_name) is not None: print("Please do not enter special characters in student name !") exit() student_standard = int(input("Please enter standard of student: ")) if (student_standard > 12 or student_standard <= 0): print("Please enter standard from 1 to 12 only") exit() maths = float(input("Enter maths marks: ")) if maths < 0 or maths > 50: exit(print("Enter marks from 0 to 50 only")) ss = float(input("Enter ss marks: ")) if ss < 0 or ss > 50: exit(print("Enter marks from 0 to 50 only")) sci = float(input("Enter sci marks: ")) if sci < 0 or sci > 50: exit(print("Enter marks from 0 to 50 only")) eng = float(input("Enter eng marks: ")) if eng < 0 or eng > 50 : exit(print("Enter marks from 0 to 50 only")) print_marks() if (maths < 18.0 or ss < 18.0 or sci < 18.0 or eng < 18.0): print("Percentage: -\nClass: Failed") else: calculate_percentage() except(TypeError,ValueError): print("Please enter the numeric data in the fields!")
true
32bb83d9d8ddd6a575ebfbd2e3102d3a9ae987ec
sheeba23/pythonprograms
/1_list_elements_functions.py
627
4.34375
4
"""Take input from user and do the below programs:- 1. based on user input print the value from object(list, tuple) user input:-"apple", "banana", "grapes""" a = str(input("a : ")) b = str(input("b : ")) c = str(input("c : ")) fruits = [a,b,c] print(fruits) print(fruits[0]) print(fruits[2]) d = str(input("d : ")) fruits.append(d) print(fruits) fruits.pop() print(fruits) e = str(input("e : ")) fruits.append(e) print(fruits) fruits.insert(1,'papaya') print(fruits) fruits.remove(fruits[0]) print(fruits) vegetables = ["potato", "tomato", "onion"] new_list = vegetables + fruits print(new_list)
false
18b739e9c7cfd8f2b2c728653a8faceba3e75634
3bp3/code
/python/COMP9021/challenge/mean_median_standard_deviation.py
2,396
4.125
4
from random import seed, randint from math import sqrt from statistics import mean, median, pstdev import sys # Prompt the user for a seed for the random number generator, # and for a strictly positive number, nb_of_elements. # # See previous challenge. # Generate a list of nb_of_elements random integers between -50 and 50. # # See previous challenge. # Print out the list, compute the mean, standard deviation and median of the list, # and print them out. # # To compute the mean, use the builtin sum() function. # To compute the standard deviation, use sum(), the sqrt() from the math module, # and the ** operator (exponentiation). # To compute the median, first sort the list. # # The following interaction at the python prompt gives an idea of how these functions work: # >>> from math import sqrt # >>> sqrt(16) # 4.0 # >>> L = [2, 1, 3, 4, 0, 5] # >>> L.sort() # >>> L # [0, 1, 2, 3, 4, 5] # >>> L = [2, 1, 3, 4, 0, 5] # >>> sum(L) # 15 # >>> sum(x ** 2 for x in L) # 55 # >>> L.sort() # >>> L # [0, 1, 2, 3, 4, 5] # # Then use the imported functions from the statistics module to check the results. arg_for_seed = input('Input a seed for the random number generator: ') try: arg_for_seed = int(arg_for_seed) except ValueError: print('Input is not an integer , giving up') sys.exit() nb_of_elements = input('How many elements do you want to generate? ') try: nb_of_elements = int(nb_of_elements) except ValueError: print('Input is not an integer , giving up') sys.exit() if nb_of_elements <= 0: print('Input is not a strictly positive number , giving up') sys.exit() seed(arg_for_seed) L = [randint(-50,51) for _ in range(nb_of_elements)] print('\nThe list is:',L) mean_cal = sum(L)/nb_of_elements deviation_cal = sqrt(sum(i**2 for i in ([(L[i]-mean_cal) for i in range(nb_of_elements)]))/nb_of_elements) L.sort() median_cal = L[int((nb_of_elements-1)/2)] if nb_of_elements%2 else (L[int(nb_of_elements/2 - 1)] + L[int(nb_of_elements/2)])/2 print(f'\nThe mean is {mean_cal:.2f}.') print(f'The median is {median_cal:.2f}.') print(f'The standard deviation is {deviation_cal:.2f}.') print('') print('Confirming with functions from the statistics module:') print(f'The mean is {mean(L):.2f}.') print(f'The median is {median(L):.2f}.') print(f'The standard deviation is {pstdev(L):.2f}.') #Do not use function name as a variable name !!!!!
true
badfaf162ff064ee9c0f44f7e602d3721ab7c0c5
juanchax/MagaPython
/Week 1/06. Calculate Interest.py
509
4.1875
4
# 06 ----- # Create a program that calculates how much money you'll # have after a month if you deposit $2000 in your bank # account and the monthly interest rate is 5%. Print out the # total. # # Crear un programa que calcule cuánto dinero tendré # al cabo de un mes si deposito hoy 2000 en el banco # y el interés mensual es de 5%, y luego devuelva por pantalla ese valor. initial_deposit = 2000 monthly_interest = 1.05 total_upToDate = initial_deposit * (monthly_interest ** 1) print(total_upToDate)
false
ca66c57bedddfbfa7595c436ac31a9b58003b7f2
sanaturies/pyflakes
/temp/algorithm_practise/tree/more_tree_stuff.py
1,268
4.125
4
#what am i doing?????? #first we do baby steps #find one num in the tree class Node: def __init__(self,data): self.left=None self.right=None self.data=data def insert(self,data): if self.data: if data<self.data: if self.left is None: self.left=Node(data) else: self.left.insert(data) elif data>self.data: if self.right is None: self.right=Node(data) else: self.right.insert(data) else: self.data=data def printTree(self): if self.left!=None: self.left.printTree() print(self.data) if self.right !=None: self.right.printTree() def findTree(self,num,found): if self.left != None: self.left.findTree(num,found) if self.data==num: print(True) found = True if self.right != None: self.right.findTree(num,found) root=Node(40) root.insert(10) root.insert(20) root.insert(70) root.printTree() found = False root.findTree(10,found) print(found)
false
b169bd3e728754e23f3a89f04836779abe57d303
NishkarshRaj/Programming-in-Python
/Module 1 Assignments/assignment22.py
737
4.21875
4
name="John" institute="ABC Training Institute" courses=("Python Programming","RDBMS","Web Technology","Software Engg.") electives=("Business Intelligence","Big Data Analytics") print(("Number of courses opted by %s are %d ")%(name,len(courses))) print(("Courses opted by %s are")%(name)) for i in range(0,4): print(courses[i],end=" ") '''courses.insert(5,electives[0]) courses.insert(6,electives[1])''' print("") '''Are you kidding me!!!! Tuples are immutable! First typecast as list change and then remake as tuple''' courses=list(courses) courses.append(electives[0]) courses.append(electives[1]) courses=tuple(courses) print("Added elective with complete list are now shown") for i in range(0,6): print(courses[i],end=" ")
true
bece4c0c1dddad1ff873dc59d88267fb67f4b9e6
NishkarshRaj/Programming-in-Python
/Module 1 Assignments/assignment45.py
1,093
4.1875
4
cust_details="Hello John, your customer id is j181" import re print("1 Find if the customer name is preceded by hello or Hello and mention if yes") match=re.search("hello |Hello ",cust_details,re.I) if (match.group()!=None): print("The name is preceded by Hello or hello as:",match.group()) else: print("Name is not greeted as asked") print("") print("") print("2) Find, if the given string ends with a pattern containing only one alphabet followed by three numbers? If pattern is found, print the searched result") match=re.search("\D\d{3}",cust_details) if match.group()!=None: print("The query is true and has result:",match.group()) else: print("Query is not true") print("") print("") print('''3) Replace the word starting with "j" followed by three numbers to only the number(remove the alphabet).''') cust_details=re.sub("j181","181",cust_details) print(cust_details) print("") print("") print('''4) Replace the word starting with "j" followed by three numbers to only the number(remove the alphabet).''') cust_details=re.sub("id","ID",cust_details) print(cust_details)
true
eff479e594d9d6afd37433ec956b09edaa0cc0b2
NishkarshRaj/Programming-in-Python
/Module 1 Assignments/assignment9.py
549
4.125
4
i=10 #creates an integer variable. This is a single line comment print("i=",i) #prints 10 ''' Below code creates a Boolean variable in Python (This is a multiple line comment) ''' s=True print("s=",s) #prints True, Here, s is a Boolean variable with value True """ Below code assigns string data to variable 's'. Data type of variable can change during execution. Hence, Python supports Dynamic Semantics. (This is a multi-line comment used for documentation) """ s=24 print("s=",s) #prints 24, Here, s is changed to integer data type with value 24
true
7185a23e3fb52884959467b9dcf64f8ab74b1f21
NishkarshRaj/Programming-in-Python
/Module 1 Assignments/assignment14_3.py
252
4.15625
4
print("Prime number programme!!!") num=int(input("Enter a number: ")) flag=0 for x in range(1,num+1): if num%x==0: flag=flag+1 else: pass if(flag==2): print("Number is prime") else: print ("Not prime")
true
007af8f27aff789abaea68523a2a74bf4f63b977
FelixZFB/Python_advanced_learning
/01_Python_basic_grammar_supplement/007_Python重点基础知识补充2(已分类添加到开发技巧总结项目中)/002_字符串操作_小写大写统计重复.py
390
4.21875
4
# -*- coding: utf-8 -*- # Page48 str1 = "hi, python!" # 只将字符串的第一个字母大写 print(str1.capitalize()) # 统计字符串中某个字符出现的次数 print(str1.count('h')) # 全部大写 print(str1.upper()) # 全部小写 print(str1.lower()) # 重复输出字符串三次,中间会连接在一起 print(str1 * 3) # 每个单词首字母大写 print(str1.title())
false
36eaf934f40bf19fba354c0e1895c31393782226
FelixZFB/Python_advanced_learning
/02_Python_advanced_grammar_supplement/001_3_高级语法(深拷贝-浅拷贝-GIL全局解释器锁)/001_copy_deepcopy_浅拷贝和深拷贝2.py
819
4.125
4
# 3. copy.copy:浅拷贝,只拷贝引用, # 列表中的每个元组,只拷贝每个元素的指向内存地址的引用 # copy与赋值不同,赋值是变量当做一个整体拷贝了引用 import copy a = [11, 22] d = copy.copy(a) print() print(id(a)) print(id(d)) print(id(a[1])) print(id(d[1])) # 输出结果显示,a和d的地址并不同,因为d并不是浅拷贝的a这个整体 # 拷贝的是里面每个元素地址的引用 # 4. 浅拷贝补充 a = [11, 22] b = [33, 44] c = [a, b] d = c #d指向c,浅拷贝 e = copy.copy(c) # e拷贝的是c里面a和b地址的引用 print() print(e) print(id(c)) print(id(d)) print(id(e)) # 输出结果显示,e并不是指向c的地址 print() print(id(a)) print(id(e[0])) print(id(b)) print(id(e[1])) # 输出结果显示,e指向的是a和b的地址
false
328b71e68b5e8da2578587b4d5672d46a5d79904
FelixZFB/Python_advanced_learning
/02_Python_advanced_grammar_supplement/001_2_高级语法(装饰器-闭包-args-kwargs)/011-语法糖之装饰器_1_为什么要装饰器.py
1,836
4.21875
4
# -*- coding: utf-8 -*- # python装饰器就是用于拓展原来函数功能的一种函数 # 装饰器函数的特别之处: # 1.参数是一个函数(函数的参数是一个函数); # 2.返回值是一个函数(内部定义一个函数,返回值就是返回这个函数) # 装饰器好处:使用python装饰器的可以在不用更改原函数的代码前提下给函数增加新的功能 # 1. 看一个例子,定义一个函数a # 2. 我们需要获取函数a的运行时间 # 3. 方法1:篡改原函数a,参照篡改后的函数b # 4. 方法2:不篡改原函数a, 定义一个新函数c,函数a作为参数传入,参照函数c import time # 原始函数 def func_a(): print("hello") time.sleep(1) print("world") # 方法1:直接修改函数增加获取函数运行时间的功能 def func_b(): startTime = time.time() print("hello") time.sleep(1) print("world") endTime = time.time() msecs = (endTime - startTime)*1000 print("函数func_a运行耗时:%d ms" %msecs) func_b() print() # 方法2:定义一个新函数func_c,函数func_a作为参数传入 def func_c(func_a): startTime = time.time() func_a() endTime = time.time() msecs = (endTime - startTime) * 1000 print("函数func_a运行耗时:%d ms" % msecs) # 运行上面的func_c函数,将func_a作为参数传入 if __name__ == '__main__': # 将原始函数func_a作为参数传入到func_c函数中 f = func_a func_c(f) # 函数f的名称就是func_a print("f.__name__is:", f.__name__) # 函数c可以实现获取运行时间的功能 # 但是如果有1000个func_a函数,则需要把func_a函数传入到func_c函数1000次 # 然后运行func_c函数1000次 # 是不是非常耗时和耗电呢? # 看011-语法糖之装饰器_2.py
false
11f3e0665977a943fcc974390ba9c6279c7efa71
FelixZFB/Python_advanced_learning
/01_Python_basic_grammar_supplement/009_oop-面向对象编程(看下面02文件夹解释更清晰明了,来自TLXY_study_note)/13_4_自定义一个类.py
567
4.21875
4
# 11. 自定义类的实例 # 函数名称可以直接作为变量名使用 def sayHello(name): print("{0}, 你好! 来一发?".format(name)) sayHello("Felix") # 自己组装一个类 class A(): pass def say(self): print("saying...") # A类和say函数组装成B类 class B(): def say(self): print("saying...") # 直接调用函数say say(111) # A作为一个类,将say函数赋值给A.say函数,A.say就相当于A类下的一个方法say,该方法就调用的是say函数 A.say = say a = A() a.say() b = B() b.say()
false
45992ab8544367fb2fc6215654caa1b206b8dd95
FelixZFB/Python_advanced_learning
/02_Python_advanced_grammar_supplement/001_12_高级语法(内置函数_元类_实现ORM)/006_int_str_class_都是type元类创建的.py
797
4.1875
4
# -*- coding:utf-8 -*- # 对象的__class__方法可以查看对象是属于哪个类 class A(): pass print(int.__class__) print(str.__class__) print(A.__class__) print('*' * 50) # 运行结果显示,字符串,整数,类都是属于type元类 a = 100 # a属于int类,int类属于type元类 print(type(a)) print(a.__class__) print(a.__class__.__class__) print('*' * 50) # ************************************************** # <class 'int'> # <class 'int'> # <class 'type'> # ************************************************** # 在python2中上面输出结果应该是<type 'int'> # 在python3以后type都改成class为了更加清晰的区分 # 元类就是创建类这种对象的东西。type就是Python的内建元类, # 当然了,你也可以创建自己的元类。
false
ee565ffaa897dd573deb8059c5b72a5f37148e34
FelixZFB/Python_advanced_learning
/02_Python_advanced_grammar_supplement/002_多线程_多进程_协程_进阶汇总/002_多进程/009案例测试文件夹[复件]/numbers_7_3.py
315
4.25
4
# coding=utf-8 # һ֣ȷǷ10 integer = input("Please give me a integer: ") integer = int(integer) print(integer) if integer % 10 == 0: print("The number " + str(integer) + " is integer of 10.") else: print("The number " + str(integer) + " isn't integer of 10.")
false
2eaf7b90a408b5e6b2c7b2af73ef31c02e38e579
Samuel1P/Python_OOPs
/InheritanceSection/single_inheritance.py
1,312
4.15625
4
class Shape: pass class Ellipse(Shape): pass class Circle(Ellipse): pass class Polygon(Shape): pass class Rectangle(Polygon): pass class Square(Rectangle): pass class Triangle(Polygon): pass print() print(f"issubclass(Ellipse, Shape) --> {issubclass(Ellipse, Shape)}") print(f"issubclass(Circle, Ellipse) --> {issubclass(Circle, Ellipse)}") print(f"issubclass(Circle, Shape) --> {issubclass(Circle, Shape)}") sh = Shape() sq = Square() rt = Rectangle() print() print(f"isinstance(sh, Shape) --> {isinstance(sh, Shape)}") print(f"isinstance(sq, Square) --> {isinstance(sq, Square)}") print(f"isinstance(sq, Square) --> {isinstance(sq, Shape)}") print() cr = Circle() el = Ellipse() print(f"type(Ellipse) -> {type(Ellipse)}") print(f"type(el) -> {type(el)}") print() print(f"isinstance(cr, type(el)) -> {isinstance(cr, type(el))}") print(f"issubclass(type(cr), type(el)) -> {issubclass(type(cr), type(el))}") """ Output: issubclass(Ellipse, Shape) --> True issubclass(Circle, Ellipse) --> True issubclass(Circle, Shape) --> True isinstance(sh, Shape) --> True isinstance(sq, Square) --> True isinstance(sq, Square) --> True type(Ellipse) -> <class 'type'> type(el) -> <class '__main__.Ellipse'> isinstance(cr, type(el)) -> True issubclass(type(cr), type(el)) -> True """
false
8aa4dac762eddc1aa72f8ddda092f6427a884316
Samuel1P/Python_OOPs
/PolymorphismSection/format_dunder_method.py
617
4.15625
4
""" Implementing custom format is complex and goes outside the scope of OOP. We will reuse the existing formatting spec of the objects to get around. """ from datetime import date class Person: def __init__(self, name, dob) -> None: self.name = name self.dob = dob def __repr__(self): return f"Person({self.name}, {self.dob})" def __format__(self, format_spec): return f"{self.name}:{format(self.dob, format_spec)}" p = Person("Pat", date(1993, 10, 1)) print(p) # Person(Pat, 1993-10-01) print(format(p, f" %A, %d-%B-%Y")) # Pat: Friday, 01-October-1993
true
8de0aacf49152448c8a842a71d65be1fc9a784fa
htmtri/pythonstuff
/hw/4.4.7.py
1,498
4.21875
4
#Write a function called "reader" that reads in a ".cs1301" #file described in the previous problem. The function should #return a list of tuples representing the lines in the file like so: # #[(line_1_number, line_1_assignment_name, line_1_grade, line_1_total, line_1_weight), #(line_2_number, line_2_assignment_name, line_2_grade, line_2_total, line_2_weight)] # #All items should be of type int except for the name (string) #and the weight (float). You can assume the file will be in the #proper format -- in a real program, you would use your code #from the previous problem to check for formatting before #trying to call the function below. # #Hint: Although you could use readlines() to read in all #the lines at once, they would all be strings, not a list. #You still need to go line-by-line and convert each string #to a list. #Write your function here! def reader(filename): out = open(filename,'r') result = [] for lines in out: split_l = lines.split() temp = (int(split_l[0]), split_l[1], int(split_l[2]), int(split_l[3]), float(split_l[4])) result.append(temp) out.close() return result #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: #[(1, 'assignment_1', 85, 100, 0.25), (2, 'test_1', 90, 100, 0.25), (3, 'exam_1', 95, 100, 0.5)] print(reader("sample.cs1301"))
true
53f66641f18a285a900a86e3c6128761b94510fe
dannykvu/Caesar-Cipher
/cipher.py
2,413
4.3125
4
""" Your mission if you choose to accept it.. (you really have no choice) is to create an encryption key and a decryption key using the alphabet. You can use the Caesar Cipher or a Random Alphabet Cipher. You will need to create a string for the alphabet. Then a string that has the coded alphabet. encode(): You will need to check each letter of 'theString' with each letter of the alphabet, then change it to the coded letter. decode(): You will need to do the exact opposite of what you did in encode() """ def encode(theString): eString = "" alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" omega = "JKLMNOPQRSTUVWXYZABCDEFGHI" #RANDOM/SHIFTED ALPHABET, Use ALL CAPS for x in theString: eString = eString + omega[alpha.find(x)] #Since this is a super secret spy mission, you MUST delete these comments #you will need to FIND each letter of the string #in the alphabet, then add the coded letter to the #encrypted string return eString def decode(theString): dString = "" alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" omega = "JKLMNOPQRSTUVWXYZABCDEFGHI" #RANDOM/SHIFTED ALPHABET, Use ALL CAPS for x in theString: if ((x != " ") or int("9")): dString = dString + alpha[omega.find(x)] #Since this is a super secret spy mission, you MUST delete these comments #you will need to FIND each letter of the encrypted word #in the coded alphabet, then add the decoded letter to the #decrypted string dString = dString #+ something return dString # Test cases... wordList = ["Hello", "Ciphers are fun!", "This Sunday is Valentine's day.","CyWoods","Computer Science 1 K","John Wayne"] for x in wordList: encoded = encode(x.upper()) decoded = decode(encoded) print ("'" + x + "' decodes to '" + encoded + "' and back to '" + decoded + "'") #outputs: # 'Hello' decodes to 'QNUUX' and back to 'HELLO' # 'Ciphers are fun!' decodes to 'LRYQNABIJANIODWI' and back to 'CIPHERSZAREZFUNZ' # 'This Sunday is Valentine's day.' decodes to 'CQRBIBDWMJHIRBIEJUNWCRWNIBIMJHI' and back to 'THISZSUNDAYZISZVALENTINEZSZDAYZ' # 'CyWoods' decodes to 'LHFXXMB' and back to 'CYWOODS' # 'Computer Science 1 K' decodes to 'LXVYDCNAIBLRNWLNIIIT' and back to 'COMPUTERZSCIENCEZZZK' # 'John Wayne' decodes to 'SXQWIFJHWN' and back to 'JOHNZWAYNE'
true
196b2002c40b88055e03b13a4a80c1703cc75cc4
cadancai/Python-Codes
/check anagram
1,218
4.34375
4
#!/usr/bin/python __author__ = 'Lee Cai' #This little code fraction is for checking whether two words are anagram string1 = 'mary' string2 = 'armyt' def count_letters(string): string_set = set(list(string)) letter_counts = {} for i in string_set: letter_counts[i] = string.count(i) return (string_set,letter_counts) #prnt is used for controling output def check_annagrams(string1, string2, prnt = 1): if len(string1) != len(string2): if prnt == 1: print 'The two strings %s and %s are not annagrams.' %(string1,string2) return False else: string1_tup = count_letters(string1) string2_tup = count_letters(string2) if string1_tup[0].issubset(string2_tup[0]) and string2_tup[0].issubset(string1_tup[0]): for i in string1_tup[0]: if string1_tup[1][i] == string2_tup[1][i]: continue else: if prnt == 1: print 'hah The two strings %s and %s are not annagrams.' %(string1,string2) return False if prnt == 1: print 'The two strings %s and %s are annagrams.' %(string1,string2) return True else: if prnt == 1: print 'The two strings %s and %s are not annagrams.' %(string1,string2) return False print check_annagrams(string1,string2, prnt = 1)
false
811e81832a10d03acdb9acea446f2db1d63faf4a
IsadoraFerrao/Python-beginners
/oddoreven.py
385
4.21875
4
# Programa para calcular se um numero e par ou impar numero = 0 while(numero != -1): print("Informe um número OU digite -1 para sair") numero = int(input()) resto = numero%2 if(resto == 0): print(f"\nO número {numero} é par :)") elif (numero == -1): print("Bye bye") exit() else: print(f"\nO número {numero} ímpar :)")
false
228ab6946e2ec1bdc226ab1997adf8417dd22e06
jleakakos-cyrus/euler
/python/problem4.py
862
4.15625
4
# Problem 4 # Find the largest palindrome made from the product of two 3-digit numbers. twoDigitNumbers = range(10, 100) twoDigitNumbers.reverse() threeDigitNumbers = range(100, 1000) threeDigitNumbers.reverse() fourDigitNumbers = range(1000, 10000) fourDigitNumbers.reverse() def palindromic (list): largest = 0 for first in list: for second in list: value = first * second if (isPalindrome(value)): if (value > largest): largest = value return largest def isPalindrome (number): palindrome = str(number) length = len(palindrome) while(len(palindrome) > 1): if (palindrome[0] == palindrome[len(palindrome) - 1]): palindrome = palindrome[1:len(palindrome) - 1] else: return False return True if __name__ == '__main__': print palindromic(threeDigitNumbers) #print palindromic(fourDigitNumbers)
false
7b010aac39fbab6b972dacacbb1fc6284df2a18b
Taomengyuan/Demo
/Pythonbasic/函数练习/demo7.py
290
4.125
4
#匿名函数 #练习1: #1、定义一个匿名函数,赋值给一个变量 f1=lambda x,y,z:print("三个函数相乘为:%d" %(x*y*z)) #2、通过变量名调用匿名函数 f1(1,2,3) #练习2: #1、定义一个匿名函数,没有参数 f2=lambda :print("hello Python!") f2()
false
afeab01f312807ba5ecaceb6ff19933883d2044c
Taomengyuan/Demo
/Pythonbasic/06-字符串和列表练习/demo7.py
994
4.1875
4
#编写Python程序,演示各种列表函数和列表操作 lst1=['java','cloud',1995,2010] lst2=[3,6,9,12,15] lst3=["p ","q ","r ","s "] print("Various list operations:") print(lst1[0]) print("list split operations:") print(lst2[1:5]) print(lst2[1:18]) print(lst2[:3]) print(lst2[1:]) print(lst2[::-1]) print(lst2[3:1]) lst1=['java','cloud',1995,2010] lst2=[3,6,9,12,15] print("Modify elements of the list:") lst1[2]=2001 print(lst1) print("Delete element from list:") del lst1[2] print(lst1) print(len(lst1)) print(max(lst2)) print(min(lst2)) print(sum(lst2)) print(sum(lst2)/len(lst2)) print(lst2.count(3)) lst3=["p","q","r","s"] print(len(lst3)) print(max(lst3)) print(min(lst3)) print(lst3.count("p")) tup=(1,2,3) print(list(tup)) lst1.extend(lst2) print(lst1) print(lst1.index('java')) lst3.insert(4,"w") print(lst3) lst1=['java','cloud',1995,2010] print(lst1.pop()) print(lst1) lst1.remove('cloud') print(lst1) lst1.reverse() print(lst1) lst2=[3,6,9,12,15,1] lst2.sort() print(lst2)
false
408d65b953c38a171ef823764242020915d05bbd
Taomengyuan/Demo
/Pythonbasic/08-文件和异常练习/demo00_4.py
894
4.25
4
#异常知识点学习 file_name='E:/Python/demo/python/readme.txt' try: file=open(file_name,'x') file.write('hello python!') except FileExistsError: print("文件已经存在,不能进行修改!") else: print("Content written successfully!") try: file=open(file_name,'x') file.write('hello python!') except FileExistsError: print("文件已经存在,不能进行修改!") except IOError: print("Can't find file for writing data!") else: print("Content written successfully!") try: file=open(file_name,'x') file.write('hello python!') except: print("文件已经存在,不能进行修改!") print("Can't find file for writing data!") else: print("Content written successfully!") try: file = open(file_name, 'x') file.write('hello python!') finally: print("无论如何该语句都会得到执行!")
false
0ce4040e2b6d4f07df02b818a24ea588c9254c2b
Utku-Cobanlar/Random_Projects
/simple_calc.py
926
4.53125
5
print("This is a simple calculator.") while True: try: num1 = float(input("Enter a number: ")) result = num1 break except: print("Enter a proper number please.") while True: oper = input("Chose operation(+,-,*,/,=):" ) if oper == "+" or oper == "-" or oper == "*" or oper == "/": while True: try: num2 = float(input("Enter a number: ")) break except: print("Enter a proper number please.") if oper == "+": result = result + num2 elif oper == "-": result = result - num2 elif oper == "*": result = result * num2 elif oper == "/": result = result / num2 elif oper == "=": print("Result is :" + str(result)) break else: print("Enter a correct operator!")
true
749ba5346f8dd735c302500f078d156fa4dbb72c
Sarah358/Skaehub-repo
/assignments/day1/duplicates.py
323
4.1875
4
# a function to remove duplicates from a list with list as an argument def rm_duplicate(x): # create a dictionary using list items as keys return list(dict.fromkeys(x)) # create a list and call the func fruits = rm_duplicate(['apple','banana','mango','apple','kiwi']) # print the unduplicated list print(fruits)
true
401c008ac5d502a01c1f9d76880f2870c0d18c68
Bharathi-raja-pbr/Python-if-else-exercises-
/2b7.py
1,189
4.3125
4
print("Enter type of calculation need to be performed") print("*For addition enter 1") print("*For subtraction enter 2") print("*For multiplication enter 3") print("*For division enter 4") print("*for any other input division will be performed by default") print("x---------x-----------X-----------x") a=int(input()); if a==1 : print(" You have choosen addition") n1=int(input("enter number 1: ")); n2=int(input("enter number 2:" )); sum=n1+n2; print("the sum of {0} and {1} is {2}".format(n1,n2,sum)) elif a==2 : print("You have choosen subtraction") n1=int(input("enter number 1: ")); n2=int(input("enter number 2:" )); difference=n1+n2; print("the difference of {0} and {1} is {2}".format(n1,n2,difference)) elif a==3: print("You have choosen multiplication ") n1=int(input("enter number 1: ")); n2=int(input("enter number 2:" )); product=n1*n2; print("the product of {0} and {1} is {2}".format(n1,n2,product)) else: print("You have choosen division") divident=int(input("enter divident : ")); divisor=int(input("enter divisor:" )); answer=divident/divisor; print("the value after division of {0} and {1} is {2}".format(divident,divisor,answer))
true
cc5587028aa0091da31d0799844a3acf67bf55c9
kc113/pyprog
/ex19.py
377
4.15625
4
people = 20 cat = 30 dog = 15 if people < cat: print("too many cats!") if people > cat: print("too many people!") if people > dog: print("more people than dogs!") if people < dog: print("too many dogs!") dog += 5 if people >= dog: print("more people than dogs!") if people <= dog: print("too many dogs!") if people == dog: print("people are dogs!")
false
16ce444a507e99e57a02564497d75456e580465c
kc113/pyprog
/ex7.py
332
4.15625
4
#print using escape sequence. days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMarg\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec" print ("Days of week are: %s" % "\'\"",days) print ("Names of month are: ",months) print (""" What is this three double-quotes. We'll be able to type as much as possible. Yay!""")
true
c4b7e4c873b7e19260dfa40d943df11cc195ead0
anshu189/parents_day
/PARENTS DAY.py
1,979
4.125
4
# IMPORTING RANDINT FUNCTION FROM RANDOM MODULE (INBUILT). from random import randint def arusha_science(): """finds the parent's child name in the Arusha science""" print("Welcome to arusha science.") child_name = input("What is your child name?") while True: try: guest_number = int(input("How many guest have you come with? \n")) except ValueError: print(' Enter a valid number ') else: print("*****Thank you for bringing some(", guest_number, ")guests****.") break print(child_name.title() + " is very lucky to come to Arusha science school." + ".\n") print("-->Here is a simple task for you<--") arusha_science() # secret_number = 6 # HERE RANDOM MODULE IS MORE HELPFUL AND FUN FOR THE USER. # THE --secret_num-- ALWAYS CHANGES TO A RANDOM NUMBER EVERY TIME THE WHOLE PROGRAM RUNS. secret_number = randint(1, 10) while True: guess_number = int(input("What is the secret number? Between 1 to 10.")) if guess_number > secret_number: print("That is too high, try again.") elif guess_number < secret_number: print("That number is too low, try again.") elif guess_number == secret_number: print("*****Congratulations you have guessed successfully!*****") break else: print(" Sorry. Try again!") print("-->Let us play a little game number<--") print("1.Think of a number") print("2.Do not enter your number in the terminal") print("*Press enter to continue in every step*") while True: ans = input("-->Hit Enter-key to continue<--") if ans == "": step_2 = input("1.Now double your answer") step_3 = input("2.Now add six") step_4 = input("3.Divide your answer by two") step_5 = input("4.Take away the original number") print('The answer is "3"') break else: print("Please follow the instructions")
true
6beb808f8828e0b06c0b0b5a58691622014a63ea
nyccowgirl/coding-challenges
/random/maxproduct.py
2,013
4.21875
4
"""Given list of integers, return the largest possible product of 3 numbers. >>> max_product([3, 2, 1, 3, 4, 6, 5]) 120 >>> max_product([-9, 2, 1, -7, 8, 7]) 504 >>> max_product([-1, -5, 0, -200, 1]) 1000 >>> max_product([-6, -5, -4, -3, -2, -1]) -6 >>> max_product([-100, -4, 0, -500]) 0 """ from heapq import nlargest, nsmallest from operator import mul def max_product(lst): """Given list of integers, return largest possible product of 3 numbers.""" if len(lst) < 3: raise ValueError('list does not have 3 numbers') elif len(lst) == 3: max_product = reduce(mul, lst) else: top_three = nlargest(3, lst) bottom_two = nsmallest(2, lst) top_one = nlargest(1, lst) # Max product is either top 3 positive integers or top 1 positive integer # and bottom 2 negative integers a = reduce(mul, top_three) b = reduce(mul, bottom_two) * top_one[0] if a > b: max_product = a else: max_product = b return max_product # ALTERNATIVE SOLUTION: # def max_product(lst): # if len(lst) < 3: # raise ValueError('list does not have 3 numbers') # elif len(lst) == 3: # max_product = lst[0] * lst[1] * lst[2] # else: # # Do not need to remove last items (e.g., max_three or min_two) as it # # would result in error in situation where list has 4 numbers only. # max_one = max(lst) # lst.remove(max_one) # max_two = max(lst) # lst.remove(max_two) # max_three = max(lst) # min_one = min(lst) # lst.remove(min_one) # min_two = min(lst) # a = max_one * max_two * max_three # b = min_one * min_two * max_one # if a > b: # max_product = a # else: # max_product = b # return max_product if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TEST PASSED. YIPPEE!\n"
true
eb1ab815894a32140ee92adb60924f025941176f
dylan-fox/Python_Projects
/hardway/ex16.py
1,353
4.53125
5
#Imports this script and the file to be edited from sys import argv script, filename = argv #Prompt user to abandon ship or go through with erasing the file print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") #opens the file in write mode, and assigns to variable 'target' print "Opening the file..." target = open(filename, 'w') #Truncates the file. Since no parameter is listed, it truncates it to 0. #print "Truncating the file. Goodbye!" #target.truncate() #Opening filename in write mode should erase it. print "File ready to be rewritten." #Gets user input for three lines and assigns them to variables. print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") #Writes the lines to the file, with line breaks inbetween. print "I'm going to write these to the file." fulltext = line1 + "\n" + line2 + "\n" + line3 + "\n" target.write(fulltext) """target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n")""" #Close file, which saves it. print "And finally, we close it." target.close() #Reopens, reads, and closes the new file. newfile = open(filename) print "The file now reads:" print newfile.read() newfile.close()
true
084a60073d44a928db7b8464bb568e4fdb389e4b
CoderFemi/AlgorithmsDataStructures
/practice_challenges/python/love_letter.py
1,257
4.15625
4
def theLoveLetterMystery(letter) -> int: """Count number of operations needed to make a palindrome""" count_operations = 0 reversed_letter = letter[::-1] letter_length = len(letter) if reversed_letter == letter or letter_length < 2: return count_operations # letter_list = list(letter) middle = int(letter_length / 2) next_index = middle + 1 prev_index = middle - 1 is_even = letter_length % 2 == 0 if is_even: first_middle = letter[middle] second_middle = letter[prev_index] diff = abs(ord(first_middle) - ord(second_middle)) count_operations += diff # letter_list[prev_index] = first_middle if letter_length == 2: return count_operations prev_index = middle - 2 while next_index < letter_length: next_char = letter[next_index] prev_char = letter[prev_index] diff = abs(ord(next_char) - ord(prev_char)) count_operations += diff # letter_list[next_index] = prev_char next_index += 1 prev_index -= 1 return count_operations print(theLoveLetterMystery("abc")) print(theLoveLetterMystery("abcba")) print(theLoveLetterMystery("abcd")) print(theLoveLetterMystery("cba"))
false
879b5078f9cc9c77420801a64443aec6f5fe169c
umairshaheen78/while-loop
/main.py
1,419
4.125
4
''' 02/11/2021 --------------------------------- Review: Boolean Operators: if (5 > 4 or "python" != 5) Types: and or not --------------------------------------------- import random (importing random library) variable = random.randint(start, end) ===================================================== while loop repeats a set of statements as long as a condition is True Formula: while (Condition) BODY else: <---- optional BODY ------------------------------------------------------ Example: while (True): print ("This statement prints forever.") Rule: A loop becomes infinite loop if a condition never becomes FALSE. An infinite loop might be useful in client/server programming where the server needs to run continiously. However, you must use caution when using while loops because of the possibility that this condition resolves to a FALSE value. To avoid a infinite loop, make sure to use a variable and keep track of its value. Exercise 1 Expected outputs Hello Python Python Evergreen Evergreen Evergreen 2021 ''' ''' integer = 1 while (integer < 10): print ("This statement prints forever.") integer += 1 #Incremenration ''' student = 0 while (student <= 6): if (student < 1): print ("Hello!") elif (student < 3): print ("Python!") elif (student < 3): print ("Bye!") elif (student <= 5): print ("Evergreen!") else: print ("2021!") student += 1
true
a78b3de74985b50588746f4b66924c1b382c6ae6
rdmunden/logic_chain
/chain_of_logic_advanced.py
1,551
4.25
4
""" generate random strings of logic v2 - randomly adds 'not' before values TODO: 1. add random parentheses, 2. add expressions like 'i==1' or 'print()' for values TODO: Make it more explicit as to which True or False value it is evaluating to. The cycle: 1. Start with a True a. keep doing 'and True' to the end b. if you hit an 'or' before then, stop there (before the 'or', with the current True value) c. if you hit 'and False' look for the next 'or' i. if you find one, start the cycle again from there (after the 'or') ii. if you don't then stop there (on that False value) 2. Start with a False a. look for the next 'or' i. if you find one, start the cycle again from there (after the 'or') ii. if you don't then stop there (on that False value) """ import random def r2(): return random.randint(0, 1) def r7(): return random.randint(0,6) tv = true_values = ["'a'", "'b'", "'c'", "'d'", "'e'", "'f'", "'g'"] fv = false_values = ["''", 0, (), [], {}, set(), None] lv = logic_values = ['and', 'or'] nv = ['', 'not '] vals = [tv, fv] n = 5 cont = '' while cont == '': expr = "{}{}".format(nv[r2()], vals[r2()][r7()]) for i in range(n): item = " {} {}{}".format(lv[r2()], nv[r2()], vals[r2()][r7()]) expr += item print('\n' + expr + '\n') resp = input("Enter for answer...") ans = eval(expr) if isinstance(ans, str): ans = ans or "''" print(f"result: {ans}") cont = input("\nEnter to continue... ")
true
4226c8a9b4418ffb36470db144607f56a3145542
magladde/Python-CSC-121
/Lesson 05/Lab05P1.py
1,056
4.34375
4
# Lab 5 problem 1 # program introduction print('This program takes user input in the form of as many integers') print('that the user wants, from 1-10. These integers will be stored in') print('a list. The list will be displayed, along with the average and ') print('if the average is higher than 7 we will subtract 1 from every ') print('number in the list then display the modified list.') print() # get user input again = 'y' num_list = [] while again == 'y': user_input = int(input('Enter an integer from 1 to 10: ')) num_list.append(user_input) again = input('Enter another integer? [y/n] ') # display the list generated by the user print('Number list: ' + str(num_list)) # calculate average of the user generated list length = len(num_list) total = 0 for integer in num_list: total = total + integer average = total / length # display average print('Average: ', average) # modify list if average is greater than 7 if average > 7: i = 0 while i < length: num_list[i] = num_list[i] - 1 i = i + 1 # print modified list print(num_list)
true
c725a99d8f40fa2bdd9e86f7182586199b988546
magladde/Python-CSC-121
/Lesson 04/M1.py
1,037
4.46875
4
# Temperature conversion program (celcius-fahrenheit / Fahrenheit-Celcius) # display program welcome print('This program will convert temperatures (Fahrenheit/Celsius)') print('Enter (F) to convert Fahrenheit to Celsius') print('Enter (C) to convert Celsius to Fahrenheit') # Get temperature to convert which = input('Enter selection: ') while which != 'F' and which != 'C': which = input("Please enter 'F' or 'C': ") temp = int(input('Enter temperature to convert: ')) # determine temperature tconversion needed and display results if which == 'F': while temp < -459.67: temp = int(input('That temperature is below absolute zero. Enter a temperature: ')) converted_temp = format((temp - 32) * 5/9, '.1f') print(temp, 'degrees Fahrenheit equals', converted_temp, 'degrees Celsius') else: while temp < -273.15: temp = int(input('That temperature is below absolute zero. Enter a temperature: ')) converted_temp = format((9/5 * temp) + 32, '.1f') print(temp, 'degrees Celsius equals', converted_temp, 'degrees Fahrenheit')
true
3d33726e85521751c60a4485770b484e402b7402
magladde/Python-CSC-121
/Lesson 05/Lab05P2.py
979
4.25
4
# lab 5 problem 2 # program introduction print('This program simulates course registration. Users can add and ') print('drop courses. The program will display error messages and the') print('courses choosen by the user.') print() # get user input for the courses course_catalog = [] user_input = 'A' while user_input != 'E': user_input = input('Enter A to add course, D to drop course, and E to exit: ') if user_input == 'A': course = input('Enter course to add: ') if course in course_catalog: print('You are already registered in that course.') print() else: course_catalog.append(course) course_catalog.sort() print('Course added') print('Courses registered: ', course_catalog) print() elif user_input == 'D': drop_course = input('Enter course to drop: ') if drop_course in course_catalog: course_catalog.remove(drop_course) course_catalog.sort() print('Course dropped') print('Courses registered: ', course_catalog) print()
true
2df4091cd20942b8d7f89488583e95f30579cdfa
magladde/Python-CSC-121
/Lesson 07/Lab07P4.py
1,964
4.40625
4
# Wake Tech. CSC 121 Lesson 7 Problem 4 # This program calculates a course grade using two functions # define main function, prompt user for how many labs there are. Use a loop # to enter lab scores and store in a list, display lab scores. Perform # the same for tests. Get the weights for labs and tests (default weights # are 50 percent and 50 percent). Call grade_calculator function def main(): lab_scores = [] test_scores = [] num_labs = int(input('How many labs? ')) for i in range(num_labs): lab_score = int(input('Enter a lab score: ')) lab_scores.append(lab_score) print('Lab scores:', lab_scores) num_tests = int(input('How many tests? ')) for i in range(num_tests): test_score = int(input('Enter a test score: ')) test_scores.append(test_score) print('Test scores:', test_scores) print() print('The default weights for course grade are 50% labs and 50% tests.') weight = input('Enter C to change the weights or D to use default weights: ') if weight == 'C': lab_weight = int(input('Enter lab percentage (without the % sign): ')) test_weight = int(input('Enter test percentage (without the % sign): ')) grade_calculator(lab_scores, test_scores, lab_weight, test_weight) elif weight == 'D': grade_calculator(lab_scores, test_scores) # define grade_calculator function def grade_calculator(lab_scores, test_scores, lab_percent = 50, test_percent = 50): # calculate lab average total = 0 for score in lab_scores: total = total + score lab_average = total / len(lab_scores) print('Lab average:', lab_average) # calculate test average total = 0 for score in test_scores: total = total + score test_average = total / len(test_scores) print('Test average:', test_average) # calculate course grade lab_portion = lab_average * lab_percent / 100 test_portion = test_average * test_percent / 100 course_grade = lab_portion + test_portion print('Course grade:', course_grade) # call main function main()
true
5602e44f3afa9edeecc923ded5ddff4f80c133ae
magladde/Python-CSC-121
/Lesson 06/Lab06P3.py
1,328
4.125
4
# Lesson 6 problem 3 # get user input for Jean's four scores print("Please enter Jean's scores one by one.") jeans_scores = [] for i in range(4): jean_score = int(input('Enter a score: ')) jeans_scores.append(jean_score) print("Jean's scores:", jeans_scores) print() # get user input for Kayla's four scores print("Please enter Kayla's scores one by one.") kaylas_scores = [] for i in range(4): kayla_score = int(input('Enter a score: ')) kaylas_scores.append(kayla_score) print("Kayla's scores:", kaylas_scores) print() # get user input for Connie's four scores print("Please enter Connie's scores one by one.") connies_scores = [] for i in range(4): connie_score = int(input('Enter a score: ')) connies_scores.append(connie_score) print("Connie's scores:", connies_scores) print() # create a list that is a list of jean's scores, kayla's scores and # connie's scores all_scores = [jeans_scores, kaylas_scores, connies_scores] print('All scores:', all_scores) # add one point to each score using a set of nested for loops for row in range(3): for col in range(4): all_scores[row][col] = all_scores[row][col] + 1 print("All scores after extra point: ", all_scores) # sort each list inside all_scores and redisplay all_scores for i in range(3): all_scores[i].sort() print("All score's afer sorting:", all_scores)
false
84e6474343792b86cf9c28822a3adce646011d88
magladde/Python-CSC-121
/Lesson 08/Lab08P3.py
325
4.3125
4
# Lesson 08 lab problem 3 print('This program creates a list of odd numbers in the range of your choice.') start_num = int(input('Enter a starting number: ')) end_num = int(input('Enter ending number: ')) my_list = list(num for num in range(start_num, end_num + 1) if num % 2 == 1) print('odd numbers in the range:', my_list)
true
85104ce9d37e85d72c311778fef0c705a5748c19
magladde/Python-CSC-121
/Lesson 03/Lab03P1.py
802
4.40625
4
# This program calculates the number of seconds since midnight # program introduction print('Hello, this program calculates the number of seconds since ') print('midnight. You will be asked to enter 4 pieces of information: ,') print('hour, minute, second, and AM/PM.') # get user input for hour, minute, second, and AM/PM hour = int(input('\nEnter hour: ')) minute = int(input('Enter minute: ')) second = int(input('Enter second: ')) meridiem = input('Enter AM or PM: ') meridiem = meridiem.lower() # calculate seconds since midnight if meridiem == 'pm' and hour == 12: hour = 12 elif meridiem == 'am' and hour == 12: hour = 0 elif meridiem == 'pm': hour = hour + 12 total_seconds = (hour * 3600) + (minute * 60) + second # display output print('Seconds since midnight: ', total_seconds)
true
02f0f74b34701af27304577b5be4155b724932d2
nmaley/iba_python
/homework_1/3_2.py
834
4.15625
4
# Сформировать одномерный список целых чисел A, используя генератор случайных чисел (диапазон от 0 до 99). Размер списка n ввести с клавиатуры. # Задание 3_вариант_2. Все четные по значению элементы исходного списка A поместить в новый список B. import random n = int(input('Введите размер списка: \n')) A = [] for i in range(n): A.append(random.randint(0, 99)) print("Элементы списка A:") for i in range(n): print(A[i]) B = [] print("Четные элементы списка А в новом списке В:") for i in range(n): if A[i] % 2 == 0: B.append(A[i]) print(B)
false
cfd12bef71063923423a070e74cfa03263b3f993
arovit/Coding-practise
/linked_list/loop_detect.py
1,538
4.125
4
#!/usr/bin/python class Node: def __init__(self): self.data = None self.next = None def __str__(self): return "Data %s: Next -> %s"%(self.data, self.next) class LinkedList: def __init__(self): self.head = Node() self.curNode = self.head def insertData(self, data): node = Node() node.data = data node.next = None if self.head.data == None: self.head = node self.curNode = node else: self.curNode.next = node self.curNode = node return node def insertNode(self, node): self.curNode.next = node self.curNode = node def printList(self): print self.head def loopDetect(self): """ FLoyd's loop detection algo - O(N) """ slower = self.head if slower.next and slower.next.next: faster = slower.next.next else: return False while True: if slower == faster: return True if faster.next and faster.next.next: faster = faster.next.next else: return False if slower.next: slower = slower.next else: return False l = LinkedList() l.insertData(1) nod = l.insertData(2) l.insertData(34) l.insertData(4) l.insertData(5) l.insertData(6) #l.insertNode(nod) if l.loopDetect(): print "Loop detected" else: print "Loop not detected"
true
0d7be74bf23aa07e55184f1f59f24823d21712ce
arovit/Coding-practise
/linkedln/coding1/flatten-nested-list-iterator.py
1,893
4.21875
4
#!/usr/bin/python # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.mainStack = [(0,nestedList)] def next(self): """ :rtype: int """ curIndex, curList = self.mainStack[-1] ele = curList[curIndex] curIndex += 1 self.mainStack[-1] = (curIndex, curList) return ele def hasNext(self): """ :rtype: bool """ if not self.mainStack: return False curIndex, curList = self.mainStack[-1] if curIndex >= len(curList): # curList is finished self.mainStack.pop() return self.hasNext() if curList[curIndex].getInteger() == None: self.mainStack[-1] = (curIndex+1, curList) self.mainStack.append((0,curList[curIndex].getList())) return self.hasNext() if curIndex < len(curList): return True return False
true
9c1adef3cd5d762a4470380cd58ae2fe3ba72783
NightRoadIx/Piton
/inin38.py
2,191
4.375
4
''' Multithreading (multihilos) En computación, un proceso es una instancia de un programa computacional el cual está siendo ejecutado. Cualquier proceso tiene 3 componentes básicos: * Un programa ejecutable * Los datos asociados al programa (variables, buffers, etc.) * El estado del proceso Un hilo es una entidad dentro de un proceso que puede ser programada para su ejecución. También, es la menor unidad de procesamiento que puede ser ejecutada en un Sistema Operativo (OS) En palabras simples, un hilo es una secuencia de instrucciones detro de un programa que pueden ser ejecutadas de manera independiente de otro código Un hilo cuenta con la siguiente información: * Identificador del hilo, el nombre del hilo * Apuntador de la pila, es un apuntador a las variables que se usan en el hilo * Contador de programa, lleva el registro de que instrucción se está ejecutando * Estado del hilo, en ejecución, esperando, iniciando, finalizado * entro otros En un solo proceso es posible que existan diferentes hilos, los cuales se pueden ejecutar al mismo tiempo. ''' # importar la librería para el manejo de hilos import threading # Crear una función para obtener e imprimir el cubo de un número def print_cubo(num): print("Cubo: {}".format(num**3)) # Crear una función para obtener e imprimir el cuadrado de un número def print_cuad(num): print("Cuadrado: {}".format(num**2)) # # Crear los hilos (se instancia un objeto con su constructor) # el argumento del constructor es la función a ejecutar # y los datos que recibe dicha función (en caso de que así sea) t1 = threading.Thread(target = print_cuad, args=(10,)) t2 = threading.Thread(target = print_cubo, args=(10,)) # Comenzar con el hilo 1 t1.start() # comenzar el hilo 2 t2.start() # esperar hasta que el hilo 1 se haya ejecutado completamente t1.join() # esperar hasta que el hilo 2 se haya ejecutado completamente t2.join() # esto es importante para detener la ejecución de los hilos print('Listo!')
false
3ad6a67de7f7b76629c568786f1908c1440c08be
NightRoadIx/Piton
/inin43.py
1,113
4.53125
5
''' *ARGS, **KWARGS en Python La sintaxis especial *args en la definición de funciones es utilizada para pasar un número variable de argumentos a una función. Es utilizado para pasar argumentos sin palabras clave (variables), esto es una lista de argumentos variables Esta notación proviene desde C, el cual permitía mandar argumentos variables cuando el programa se ejecuta, aún se puede osbervar esto, por ejemplo cuando se ejecuta la instrucción 'pip' para instalar librerías en Python, ya que el programa se llama pip, pero se ejecuta con los argumentos: pip install ALGO Por tanto, esta es la reminiscencia de los apuntadores * -> algo similar a un arreglo ** -> algo similar a una arreglo de arreglos (matriz) ''' def miFuncion(*args, **kwargs): print("args: ", args) print("kwargs: ", kwargs) # Ahora se pasan los argumentos y sus valores en la función # pueden ser de cualquier longitud miFuncion("Helden", "David", "Bowie", primer = 666, segundo = "Heroes") # ¿Qué regresa esta función?
false
edbc103c69c81beab8825f88f7d1981bdb2cbdf1
ronitafter/python
/פונקציות של מחלקות.py
1,383
4.21875
4
## methods # list(class): # 1.count(method in list) ##L = [1, 2, 1, 1, 3, 1, 2] ##res = L.count(1) ##print(res) # 2.append(method in list) ## ##L = [1, 2, 3] ##L.append(4) ##print(L) # List class functions ##L = ["Hello", "Shalom", "Marhaba"] ##L.append("Bonjour") #add element at the end of list ##print(L) ##L.remove("Hello") #remove element from list ##print(L) ##L = L * 2 ##print(L) ##L.insert(2, "Hola") #insert "Hola" at index 2, push forward the elements after it ##print(L) ##print(L.count("Hello")) ##L.reverse() #method reverse has no parameters ##print(L) ##print("Thank you!") ## # String replace operations ##st = "I am a string" ##st = st.replace("a", "A") ##print(st.replace("a", "A")) #replace every "a" by "A" ##print(st.replace(" ", "_")) #replace every space by "_" ##print(st) #did st change? # String replace operation using an empty string ##st = "I am a string" ##print(st.replace("a", "*")) #replace every space by an empty string => elete all spaces ##string_name.capitalize() ##name = "use the force" ##print(name.capitalize()) ##name1 = "use" ##name2 = "the" ##name3 = "force" ##print(name1.capitalize() + name2.capitalize() ## + name3.capitalize()) ## ## ##string.upper() ##txt = "Hello my friends" ## ##x = txt.upper() ## ##print(x)
true
3e95575965ed7fc3791565e5c7d9ea70d2b7990d
steban1234/Ejercicios-universidad
/01_acimut_linea.py
1,427
4.125
4
""" Programa que calcula el acimut de una linea recta a partir de coordenadas cartesianas de sus vertices. """ import math # Importo la libreria de matematicas # Solicita los datos al usuario x1 = float(input('Digite la coordenada Este del punto 1: ')) y1 = float(input('Digite la coordenada Norte del punto 1: ')) x2 = float(input('Digite la coordenada Este del punto 2: ')) y2 = float(input('Digite la coordenada Norte del punto 2: ')) # Calcular las deltas de coordenadas dx = x2 - x1 dy = y2 - y1 # Calcular el rumbo y determinar el valor del acimut if dy != 0: # Calcula el rumbo rumbo = math.atan(dx/dy) rumbo = math.degrees(rumbo) # Determinar el valor del acimut if dx > 0 and dy > 0: #Para el primer cuadrante acimut = rumbo elif dx > 0 and dy < 0: #Para el 2so cuadrante acimut = 180 + rumbo elif dx < 0 and dy <0: #Para el 3er cuadrante acimut = 180 + rumbo elif dx > 0 and dy > 0: #Para el 4to cuadrante acimut = 360 + rumbo elif dx == 0 and dy > 0: #para Y+ acimut = 0 elif dx == 0 and dy < 0: #Para el eje Y- acimut = 180 else: # Cuando Y = 0 if dx > 0: acimut = 90 elif dx < 0: acimut = 270 else: acimut = 'No se puede calcular el acimut de un punto' print() print('='*80) print('El acimut de la linea es:',acimut) print('='*80)
false
78fa493279415d3952f611d13f9941f30c17052c
OlgaUlrich/prework
/PY-Training/12.py
884
4.1875
4
# def factorial(n): # #define counter for multiplying # s = 1 # #define for loop, where 1 is beggining and n+1 is the end # #Last number is not in the range, that is why, we should add 1 # for i in range(1, n+1): # #every iteration we redefine our counter # s = s * i # # at the end of the loop, return the last result of our counter # return s # #print result in the console # print(factorial(3)) def factorial(n): t = n # decrement n newNum = n - 1 # define counter counter = 1 # define the end of the programm - it should stop when n is = 0 if newNum > 0: # every iteration we redefine our counter counter = n * factorial(newNum) return counter # at the end of recirsion (when n is = 0), return the last result of our counter # return counter #print result in the console print(factorial(3))
true
51361ebb7f21ab896994d5dc834c3c77be3930be
Hackin7/Programming-Crappy-Solutions
/School Exercises/2. NYJC A Level Computing 2019-2020/Practicals/Practical 1/3.5.py
395
4.15625
4
binary = int(input("Enter a binary integer: ")) denary = 0 #Converted binary # Finding length length = 0 # Loop through powers of 10 until power of 10 bigger than input while binary //(10**length) != 0: length+=1 for i in range(length):#len(binary)): #binary = int(binary) denary += (2**i) * binary // (10**i)%10 #denary+=(2**i)*int(binary[-i-1]) print(denary)
true
0494c9427433aa1ffd01a9462afe2eb420f43792
DuarteMPAndre/birthday_calculator_v2
/main.py
2,175
4.21875
4
# Calculador da data de nascimento # Descrição # dddddd # # # Historico # v1.0 - Versão inicial - 20210130 # # (c) 2021 Duarte André #imports import tkinter as tk from tkinter import * import datetime today = datetime.date.today() screen = Tk() screen.title("Birthday Calculator") def run(): global label name = name_storage.get() age = age_storage.get() birthday = birthday_storage.get() birthday_day, birthday_month = birthday.split("/") birthday_day = int(birthday_day) birthday_month = int(birthday_month) age = int(age) if birthday_month < today.month and birthday_day < today.day: birthday_year = today.year - age label.config(text="Hello " + name + " you are " + str(age) + " years old. You were born in " + str(birthday_year) + ".") elif birthday_month == today.month and birthday_day == today.day: birthday_year = today.year - age label.config(text="Happy birthday " + name + " you are " + str(age) + " years old. You were born in " + str(birthday_year) + ".") elif birthday_month > today.month: birthday_year = today.year - 1 - age label.config(text="Hello " + name + " you are " + str(age) + " years old. You were born in " + str(birthday_year) + ".") else: birthday_year = today.year - age label.config(text="Hello " + name + " you are " + str(age) + " years old. You were born in " + str(birthday_year) + ".") label = tk.Label(screen, text="") label.grid(row=5, column=0) first_text = Label(text="Enter your name") first_text.grid(row=1, column=0) second_text = tk.Label(text="Enter your age") second_text.grid(row=2, column=0) third_text = tk.Label(text="Enter your birthday(dd/mm)") third_text.grid(row=3, column=0) click_when_done = Button(text="Click when done", command=run) click_when_done.grid(row=4, column=0) name_storage = StringVar() name = Entry(textvariable=name_storage) name.grid(row=1, column=1) age_storage = StringVar() age = Entry(textvariable=age_storage) age.grid(row=2, column=1) birthday_storage = StringVar() birthday = Entry(textvariable=birthday_storage) birthday.grid(row=3, column=1) screen.mainloop()
false
7424008d462a5b0ec9ccaab28b92e3410e26c2f8
ChukwurahVictor/CodeLagosPythonProjects
/leapYear.py
562
4.25
4
#Print out the purpose of the program print("This is a program to test if a year is a leap year") #Print out the instructions of the program print("This program takes only years!") #Prompt the user to enter a year year = int(input("Please enter a year: ")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("You entered: ", year, "\n and it is a leap year ") else: print("Not a leap year!") else: print("You entered: ", year, "\n and it is a leap year") else: print("Not a leap year")
true
3960dce33c6837457ce148beebab77f94535d4da
bruno-novo-it/python
/lists.py
2,981
4.21875
4
### Nesting ### M = [[1,2,3], [4,5,6], [7,8,9]] count = 0 print("Valores da Matriz: ", M) print() # Pula Linha for itens in M: print("Valores da Matriz: ",itens) print() for itens in M: print("Valor",count,"da Matriz: ",itens) count += 1 print() print(M[1]) # Captura a linha 2 print() print(M[1][2]) # Captura a linha 2 e mostra o 3 elemento print() ### Comprehensions ### # Coleta os itens na coluna 2 col2 = [row[1] for row in M] print("Valores da Coluna 2: ",col2) print() # Coleta os itens na coluna 2 e soma 1 em cada um deles col2_plus_1 = [row[1] + 1 for row in M] print("Valores da Coluna 2 + 1:",col2_plus_1) print() # Coleta os itens na coluna 2 apenas se forem pares col2_odd = [row[1] for row in M if row[1] % 2 ==0 ] print("Valores da Coluna 2 Pares: ",col2_odd) print() # Coleta os itens na coluna 2 apenas se não forem pares col2_no_odd = [row[1] for row in M if row[1] % 2 !=0 ] print("Valores da Coluna 2 Ímpares: ",col2_no_odd) print() # Coleta a diagonal da Matriz diag = [M[i][i] for i in [0,1,2]] print("Diagonal da Matriz M: ",diag) print() # Repete os caracteres em uma String doubles = [c * 2 for c in 'spam'] print("Duplica os caracteres em uma string: ",doubles) print() # Gera lista de 0..3 lista = list(range(4)) print("O tipo da lista é: ", list) print("Lista(0..3): ",list(range(4))) print("Lista(0..3): ",lista) print() # Gera lista de -6..6 de 2 em 2 lista2 = list(range(-6,7,2)) # Segundo elemento é o ultimo da lista + 1 print("Lista(-6..6): ",lista2) print() # Gera uma lista com multiplicação dos seus valores originais lista3 = [[x ** 2, x ** 3] for x in range(4)] print("Lista Multiplicada: ", lista3) print() # Soma e Lista os elementos contidos em M print("Soma dos elementos de M: ",list(map(sum,M))) print() #### Dictionaries #### D = {'food': 'Spam', 'quantity': 4, 'color':'pink'} print("Dicionário D: ",D) print("Valor de food: ",D['food']) D['quantity'] += 1 print("Dicionário D + 1 na quantidade: ",D) # Creating a Dictionary from zero E = {} E['name'] = 'Bruno' E['job'] = 'DevOps' E['age'] = 27 ##### VERIFICAR ESSA ETAPA DO PRINT print("Dicionário completo do Bruno: ",E) print("Meu nome é %s" % E['name']) print("Sou %s" % E['job']) print("Tenho %d anos" % E['age']) print("My name is %s, i'm %s and i'm %d years old" % (E['name'],E['job'],E['age'])) print("My name is {}, i'm {} and i'm {} years old".format(E['name'],E['job'],E['age'])) F = {'b': 2, 'a': 1, 'c': 3} Ks = list(F.keys()) def print_key(): for key in Ks: print(key, '=>', F[key]) def print_key_sorted(): for key in sorted(F): print(key, '=>', F[key]) print("Desordenado:",Ks) print_key() Ks.sort() print("Ordenado:",Ks) print_key() def upper_string(word): for c in word: print(c.upper()) upper_string('spam') def print_string_n_times(number,word): x = number while x > 0: print(word * x) x -= 1 print_string_n_times(4,'spam')
false
273b6cde8f8b6554b2b7f9febae2f10058ad598b
bruno-novo-it/python
/the_for_loop.py
2,137
4.46875
4
#!/usr/bin/env python # http://www.dreamsyssoft.com/python-scripting-tutorial/loops-tutorial.php ## Verify if the Values Entries are Number's or Not userInput = input('Enter a list of numbers between 1 and 100, separated by spaces: ') nums = userInput.split() for strNum in nums: if not strNum.isdigit(): print("Not a Number:", strNum) elif int(strNum) < 1: print("Number is less than 1:", strNum) elif int(strNum) > 100: print("Number is greater than 100:", strNum) else: print("Number is valid:", strNum) # The for loop is used when you want to loop through a list of items. # The body of the loop works the same as it does in a while loop. # Let's say that we want to write a program that will validate numbers in a given list. # These numbers can be loaded from a file, hard coded, or manually entered by the user. # For our example, we will ask the user for a list of numbers separated with spaces. # We will validate each number and make sure that it is between 1 and 100. # The best way to write a program like this would be to use a for loop. # If you enter the text "5 2 7 0 100 101 1 45 a b c", the function String.split will convert # this into an array by taking each item separated by a space and converting it into a new array # element. The array variable "num" is then given to the for loop using the in keyword. # It will loop one time for each element in the array and assign the variable "strNum" the value # of that object in the array. # Now that we have the strNum object, which is the string representation of the current item in the # array, first we need to make sure that it's a number, we can do this with the String.isdigit() # function. If it is not a number, it will return false, then we will print out the validation # error. If it is a number, then the elseif conditions will continue, the next condition checks # to see if the number is less than 1, if so it prints the error. Next it checks for greater than # 100 and prints an error. If all checks pass, the else block is called, printing the valid number message.
true
15df35dd890a84b710dd125643e2f2ec81d68452
s-avra/CEBD1100-intro2
/Class 2/escape.py
394
4.21875
4
my_text1 = "This is a \\quote \" symbol" my_text2 = '\fthis is a quote \t " sym\nbol' my_text3 = "x" print(my_text1) print(my_text2) print(my_text3 * 10) line_length = input( "How long would you like your line?") print("_"* int(line_length)) line_length2 = input( "How many characters would you like?") character = input(" what character should I use") print(character * int(line_length2))
false
ba4b2af14d9b1004ab79af1662d839e88d9b7d28
satyasashi/Algorithms_Data_Structures
/Datastructures/double_linked_list/dllist_addNodeBefore.py
2,023
4.40625
4
class Node: def __init__(self, data) -> None: self.data = data self.prev = None self.next = None class DoublyLinkedList: def __init__(self) -> None: self.head = None def insertNodeBefore(self, reference_node, new_data): """Takes in a `reference_node` before which we need to place a new_node. Else we take the `reference_node` and change the pointers accordingly. Possible places we might Insert: 1. Inserting in between any 2 Nodes in the list. 2. Inserting before the HEAD. """ new_node = Node(new_data) new_node.prev = reference_node.prev new_node.next = reference_node if reference_node.prev is not None: # if we are placing new_node in between any 2 nodes. reference_node.prev.next = new_node else: # else if we are placing new_node at front of HEAD, # make this new_node as HEAD. self.head = new_node # finishing up with the connections from reference_node to new_node # before it. reference_node.prev = new_node def printList(self, node): print("Doubly Linked List:") last = None print("Forward Traversal: ") while node is not None: print(node.data, end=" ") last = node node = node.next print("") print("Reverse Traversal: ") while last is not None: print(last.data, end=" ") last = last.prev if __name__ == "__main__": dllist = DoublyLinkedList() dllist.head = Node(3) second = Node(4) third = Node(5) fourth = Node(1) dllist.head.next = second second.prev = dllist.head second.next = third third.prev = second third.next = fourth fourth.prev = third print("Before:") dllist.printList(dllist.head) dllist.insertNodeBefore(fourth, 2) print("After: ") dllist.printList(dllist.head)
true
058bb870113a0683a889d56d2a2ffb95445b0650
satyasashi/Algorithms_Data_Structures
/Datastructures/linked_list/linked_list_delete_node.py
2,819
4.21875
4
''' Five nodes have been created. We have references to these three blocks as first, second and third llist.head second third similarly | | | | | | | | till +----+------+ +----+------+ +----+------+ +---+------+ | 1 | None | | 2 | None | | 3 | None |...| 5 | None | +----+------+ +----+------+ +----+------+ +---+------+ ''' ''' Now next of first Node refers to second. So they both are linked. Similarly till end Link them up. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o--------> | 3 | o--------> +----+------+ +----+------+ +----+------+ ''' class Node: """Node holds Data and Pointer to next Node""" def __init__(self, data): self.data = data self.next = None class LinkedList: """LinkedList has a Head""" def __init__(self): self.head = None def printList(self): # Print all the nodes starting from Head. present_ele = self.head while present_ele: print(present_ele.data) present_ele = present_ele.next # Delete a Node from LinkedList # Pass a KEY def delete_node(self, key): present_ele = self.head # If HEAD is the KEY we need to Delete if present_ele is not None: if present_ele.data == key: # Make next Node as HEAD and kill former Head self.head = present_ele.next present_ele = None return # If not in Head, search in the LinkedList # Keep track of Previous-Node as we need it's -> .next while present_ele is not None: if present_ele.data == key: break # Break out of the loop prev = present_ele # Remember! present element becomes Previous, when we go forward. # just like incrementing, we point to next node present_ele = present_ele.next if (present_ele==None): return # Unlink the Node to be Deleted prev.next = present_ele.next present_ele = None if __name__=="__main__": '''Make a LinkedList object and assign Node object to it''' llist = LinkedList() llist.head = Node(1) # Declare Nodes second = Node(2) third = Node(3) fourth = Node(4) fifth = Node(5) # Link them llist.head.next = second second.next = third third.next = fourth fourth.next = fifth # Print them. llist.printList()
false
2f420314c3d9740cb481a573ce5d04fc778bcbcd
satyasashi/Algorithms_Data_Structures
/Practice/Datastructures/Binary Search Tree/binary_search_tree.py
2,931
4.21875
4
""" Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 """ # from Datastructures.BinarySearchTree.binary_search_delete_node import inorder, insert class Node: def __init__(self, data) -> None: self.data = data self.left = None self.right = None def insert_node(root, data): """We always insert node at the leaf.""" # Base case: If tree is empty if root is None: return Node(data) # Otherwise traverse from Root to the suitable leaf # to insert the new node if data < root.data: root.left = insert_node(root.left, data) else: root.right = insert_node(root.right, data) return root def inorder(root): """Traversing to the left most element in the tree then moving to the parent node then right most element in the tree. This traversal is called Inorder. The output will be a Sorted list of elements.""" if root is not None: inorder(root.left) print(root.data) inorder(root.right) return def min_of_right_subtree(root): """From the root node passed, find the minimum of that subtree""" min_element = root while min_element is not None: min_element = min_element.left return min_element def delete_node(root, target): """ Deletion has 3 scenarios: 1. Target is Leaf 2. Target has 1 Child node 3. Target has 2 Child nodes """ # Base case: if root is None: return None # now check till the Target is found. if target < root.data: root.left = delete_node(root.left, target) elif target > root.data: root.right = delete_node(root.right, target) else: # the node might have 0 or 1 child if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp # if the node has 2 children # then findout the Min of right subtree temp = min_of_right_subtree(root) # now replace the Target root key with # minimum element we just found. root.data = temp.data # now delete the original minimum element # from the Right-subtree. root.right = delete_node(root.right, temp.data) return root # Driver code. if __name__ == "__main__": root = Node(50) # Insert nodes into the tree. insert_node(root, 30) insert_node(root, 20) insert_node(root, 40) insert_node(root, 60) insert_node(root, 70) insert_node(root, 80) # Do a Inorder traversal inorder(root) print("\n Deleting node 40. \n") # delete a node from the tree. delete_node(root, 40) # check if the node got deleted # by printing. inorder(root)
true
2ffdedc63caf8ec18d13fb4c9c94b16df6145273
satyasashi/Algorithms_Data_Structures
/Datastructures/linked_list/delete_note_at_key.py
2,597
4.15625
4
class Node: """A node has 'data' and 'next' pointer to the next node""" def __init__(self, data) -> None: self.data = data self.next = None class LinkedList: """List of Nodes chained together""" def __init__(self) -> None: self.head = None def push(self, new_data): """Make this new node as Head.""" new_node = Node(new_data) new_node.next = self.head self.head = new_node def print_llist(self): """Start from the HEAD and print all the Nodes in the LinkedList""" current_node = self.head while current_node is not None: print(current_node.data) current_node = current_node.next return def deleteNodeAt(self, key): """ We will find out the presence of the 'Key' and delete that from the LinkedList. Example: Elements: 3 *-> 2 *-> 43 *-> 5 *-> 8 *-> 10 Target Key: 43 Output: 3 *-> 2 *-> 5 *-> 8 *-> 10 """ # Start from HEAD temp = self.head # if HEAD itself is the Target if temp is not None: if temp.data == key: # make NEXT of current Head as new HEAD & delete the target Node. self.head = temp.next temp = None return prev_node = None current_node = temp # while the node is not None (reach till end of the list) while current_node is not None: if current_node.data == key: # BASE CASE: Break if we found the Key. break # Remember previous node and keep track of next node. prev_node = current_node current_node = current_node.next # If we didn't find the Key, then we must just return. if current_node is None: return # Once we found the Key in the list, we link up previous_node with upcoming node. prev_node.next = current_node.next # Once linking up is done, we save memory by removing the Node from memory. # So set it to NONE. current_node = None if __name__ == "__main__": # Driver Code llist = LinkedList() # Add Nodes to the Linkedlist llist.push(3) llist.push(2) llist.push(43) llist.push(5) llist.push(8) llist.push(10) # Print original list. print("Before the deletion: ") llist.print_llist() print() # Delete at a node at key llist.deleteNodeAt(3) print("After the deletion: ") llist.print_llist()
true
0d2d603e23d0fa25caa50cb899ddce32a57830a8
satelite54/BUSAN_IT_ACADEMY
/python/Test/ex5.py
232
4.28125
4
def printRighttriangle(num): while num != 0: i = num; while i != 0: print("*", end='') i -= 1 print() num -= 1 num = int(input("input number:")) printRighttriangle(num)
false
cea162add13890caba55a6f169ab0f15bcbb18b1
Saurab17/Maze
/console_app.py
2,336
4.125
4
"""This script lets you choose any maze img, whose path given as commandline argument, and draw the path between chosen start and end point. Usage: python main.py [path to maze image] Click on maze image to set start and end points and press enter to generate the corresponding path. If clicked on a point unintentionally, press 'r' key to reset start and end points. To quit the program, press 'q' key. """ import cv2 import os import sys from maze_solver.maze import Maze from maze_augmenter.img_handler import ImgMaze ENTER_KEY = 13 click_number = 0 start = () end = () def mouse_callback(event, x, y, flags, param): global click_number global start global end if event == cv2.EVENT_LBUTTONDOWN: if click_number is 0: start = (x, y) print(f"start: ({x},{y})") click_number = 1 else: end = (x, y) print(f"end: ({x},{y})") click_number = 0 def main(): if len(sys.argv) is not 2: print("Error: Please provide path to maze image!!") exit(1) global start, end, click_number img_path = sys.argv[1] img_path = os.path.abspath(img_path) img_obj = ImgMaze(img_path, is_filebytes=False) maze_orig = img_obj.get_bgr_maze() maze_aug = img_obj.get_augmented_bgr_maze() cv2.namedWindow('Maze image') cv2.setMouseCallback('Maze image', mouse_callback) while True: cv2.imshow('Maze image', maze_orig) key = cv2.waitKey(0) & 0xFF if(key == ord('r')): click_number = 0 start = () end = () continue elif(key == ENTER_KEY): print("Processing...") sol_obj = Maze(maze_aug, is_augmented=True) sol_obj.get_shortest_path(start, end) sol_img = sol_obj.get_solution_image(alt_img=maze_orig, line_width=2, line_color=(0,0,255)) cv2.imshow('Solution', sol_img) print("Done!!!") cv2.waitKey(0) cv2.destroyWindow('Solution') elif(key == ord('q')): cv2.destroyAllWindows() break if __name__ == "__main__": main()
true
a8a4dfec5870476830c1969d3b4216e2fc596552
zlatozar/study-algorithms
/sorting/max_heap.py
1,316
4.15625
4
#!/usr/bin/env python # # -*- coding: utf-8 -*- # Chapter 6: Heaps p.151 # ___________________________________________________________ # NOTES # Important facts based on heap property # 1. First element of the heap is the biggest one # 2. First half of the heap are roots, second one contains only leaves # ___________________________________________________________ # IMPLEMENTATION def PARENT(i): return (i - 1) // 2 def LEFT(i): return 2*i + 1 def RIGHT(i): return 2*i + 2 # A[i] "float down" in the max-heap so that the sub-tree rooted # at index i obeys the max-heap property. def MAX_HEAPIFY(A, i, size): left = LEFT(i) right = RIGHT(i) if left <= size and A[left] > A[i]: largest = left else: largest = i if right <= size and A[right] > A[largest]: largest = right if largest != i: # exchange A[i], A[largest] = A[largest], A[i] MAX_HEAPIFY(A, largest, size) def BUILD_MAX_HEAP(A): heap_size = len(A) for i in range(heap_size // 2, -1, -1): MAX_HEAPIFY(A, i, heap_size - 1) # ___________________________________________________________ # TEST
true
bdb8bb6a0ce740c673e3a3a23797efdde49e75ab
Peixinho20/Fundamentos-da-Computacao
/python2/soma-diagonais.py
571
4.15625
4
#Leia uma matriz 3x3 e imprima a soma dos elementos da diagonal principal e a soma dos elementos da diagonal secundária. mat=[] soma=0 soma2=0 for i in range(0,3): mat.append(0) mat[i]=[] for j in range(0,3): mat[i].append(input('Numero ')) for i in range(0,3): for j in range(0,3): if i==j: soma=soma+mat[i][i] soma2=soma2+mat[i][3-i-1] for i in range(0,3): for j in range (0,3): print "%3d" % mat[i][j], print print'Soma da diagonal principal ',soma,'\nSoma da diagonal secundaria ',soma2
false
742566629221061cabc4922403d3932afb47e16a
hansbu/CSE537_Fall17
/Search Algorithm/Dijkstra.py
2,701
4.25
4
#### implementing Dijkstra's algorithm #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 2 16:09:25 2017 @author: mac """ #import queue import heapq as HQ # define the class Graph to define the vertices and the edges class Graph_def: def __init__(self): self.edges = {} #edges are dict type def Neighbors(self, vertice): temp = self.edges[vertice] #output a dictionary return list(temp.keys()) #cast the keys to the list def Cost_movement(self, current_node, next_node): return self.edges[current_node][next_node] graph = Graph_def() graph.edges = { #define the weighted edges of the graph 'A': {'B':4, 'D':1}, 'B': {'A':5, 'C':3, 'D':10}, 'C': {'A':1}, 'D': {'E':2}, 'E': {'B':7} } #The lowest valued entries are retrieved first (the lowest valued entry is the #one returned by sorted(list(entries))[0]). A typical pattern for entries is a #tuple in the form: (priority_number, data). def Dijkstra_algo(graph, start, goal = ''): parent_list = {} #mark the node that just generated and keep track the #parent of each node parent_list[start] = None # fringe_list = queue.PriorityQueue() fringe_list = [] HQ.heappush(fringe_list, (0, start)) # fringe_list.put(start, 0) cost_now = {} cost_now[start] = 0 # while(not fringe_list.empty()): #check if the fringe list is empty or not while(len(fringe_list)): # current_node = fringe_list.get() current_node = HQ.heappop(fringe_list)[1] print(current_node) if(current_node == goal): #Stop search when reaching goal break for new_node in graph.Neighbors(current_node): new_cost = cost_now[current_node] + graph.Cost_movement(current_node, new_node) if new_node not in cost_now or new_cost < cost_now[new_node]: HQ.heappush(fringe_list, (new_cost, new_node)) # fringe_list.put(new_node, new_cost) parent_list[new_node] = current_node cost_now[new_node] = new_cost path_found = [goal] path_found.append(parent_list[goal]) print(parent_list) ### trace back the path to find the solution path temp = goal path_found = [temp] while temp != start: temp = parent_list[temp] path_found.append(temp) # path.append(start) # optional path_found.reverse() # optional return path_found #print('Search Dijkstra: ') Found_route = Dijkstra_algo(graph,'B','E') print(Found_route)
true
4cc4293b7794834a210634316ecbdec82daff9c9
himanshuKp/python-practice
/challenges/delete_starting_evens.py
691
4.34375
4
# Write a function called delete_starting_evens() # that has a parameter named lst. # The function should remove elements from the front of lst until # the front of the list is not even. The function should then return lst. # For example if lst started as [4, 8, 10, 11, 12, 15], # then delete_starting_evens(lst) should return [11, 12, 15]. # Make sure your function works # even if every element in the list is even! def delete_starting_evens(lst): count = 0 for count in range(len(lst)): position = 0 if(lst[position]%2==0): lst.pop(position) else: break return lst print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
true
d95f37e1f6e2df3b9d0cad758ce5fec16f160f6a
rp248/PythonGuide
/numbers.py
2,322
4.65625
5
# Scientific form Numbers _sci_form = 1.23E-7 # 0.000000123 = 1.23 x 10^7 _another_sci_form = 1.23E-7 print(type(_sci_form)) # will display <class 'float'> print(_sci_form-_another_sci_form) # 0.0 ''' We can define numbers in scientific form. Scientific form = a x 10^b . In Python we can define sci-form as aE-b ''' # Complex Numbers ''' We can define complex numbers as realNumber+ImaginaryNumber(J) Example: In Math we write 3+2i, in python 3+2j ''' _complex_number = 3+2j print(_complex_number) # (3+2j) print(type(_complex_number)) # <class 'complex'> # not Operator print(not (200 == 210)) # True print(not ("Java" == "Java")) # False # or Operator print((100 < 200) or (55 < 6)) # True print((100 < 99) or (55 < 6)) # True. ''' In above case, (100>99) is True, and so is the whole logical expression. Hence there is no need to evaluate the expression (55<6). ''' # Truthy and Falsy values ''' Truthy Values : Values which are equivalent to 'True' is known as Truthy values. Falsy Values: Values which are equivalent to 'False' is known as False values. Falsy Values in Python: None, False, 0, 0.0 Empty Sequence (List) for example, '', [], () Empty Dictionary for example, {} We can check whether the value is Truthy or Falsy using bool(value_to_find) ''' print(bool(0)) # False print(bool('')) # False print(bool([])) # False print(bool({})) # False # bool type ''' A bool type represents only two state true or false. In Python we define bool types using reserved keyword 'True' and 'False' Python uses 1 and 0 to represent true and false.We can verify this fact by using int() function on True and False keywords. ''' print(int(True)) # 1 print(int(False)) # 0 # Breaking single statements into multiple lines ''' Python allows us to break long expression into multiple lines using line continuation symbol ( \ ). The \ symbol tells the Python interpreter that the statement is continued on the next line. For example: ''' _long_variable = "Hello Hello Hello Hello Hello Hello Hello Hello Hello" \ " Hello Hello Hello Hello Hello" \ " Hello Hello Hello Hello Hello Hello Hello Hello " print(_long_variable) # Type conversion ''' int(), float(),str() function can be used for type conversion ''' print(int("2")) # 2
true
43fd504252890a93079349ed566138ae56fdc8b2
allansdefreitas/python
/student_avg_conditional_exercise.py
2,574
4.1875
4
# Calcular media de estudante, faltas e dar resultado # 70% frequencia e media >= 6 #resutados: reprovado por media e falta, por falta, por media, aprovado # imprimir nome, media, porcentual e resultado # Validação: # Nunca interromper por erro # nota entre 0 e 10 (inclusive) # número de faltas entre 0 e 20 (inclusive) total_classes = 20 approved = False valid = False print('Student data ---------------------\n') name = input('Name: ') # input grade 1 (validation) ----------------------- while valid == False: grade_test1 = input('Test 1 (grade): ') try: # validation 1: Try convert to float grade_test1 = float(grade_test1) # validation 2: is it a number? if (grade_test1 >= 0 and grade_test1 <= 10): valid = True else: print("Grade have to be between 0 and 10") except: print("Grade have to be a number separeted by '.' ") # Lets validate second grade! valid = False # input grade 2 (validation) ----------------- while valid == False: grade_test2 = input('Test 2 (grade): ') try: # validation 1: Try convert to float grade_test2 = float(grade_test2) # validation 2: is it a number? if (grade_test2 >= 0 and grade_test2 <= 10): valid = True else: print("Grade have to be between 0 and 10") except: print("Grade have to be a number separeted by '.'") # Lets validate absences! valid = False # Input Absences ----------------- while valid == False: absences = input('Absences: ') try: # Try convert: is it a number value? absences = int(absences) # Verify the interval if( absences >= 0 and absences <= 20): valid = True else: print("Absences have to be between 0 and 20") except: print("Absences have to be a integer number") # percentual de aulas que compareceu frequency_classes = ( (total_classes - absences)/total_classes ) *100 #média grades_avg = (grade_test1 + grade_test2) / 2 result = '' # atingiu a frequência de 70%? if frequency_classes >= 70: if grades_avg >= 6.0: result = 'Approved' else: result = 'Disapproved for grade' elif grades_avg < 6.0: result ='Disapproved for grade and absence' else: result = 'Disapproved for absence' print('Results ----------------------------') print('Name:', name) print('Grade average:', grades_avg) print('Frequency:', frequency_classes, '%') print('Result:', result)
false
1b01366ef52a0e4d16fbd428d4fa67bd69dd479a
Sawpol/RetosPy2021
/ejercicios.py
2,021
4.25
4
# RetosPy2021 Ejercicio 1 Crear una función que reciba un número como argunmento y devuelva el largo de este número. def number_length(number): contador=0 if isinstance(number, str): return None,'El valor tiene que ser número' elif numero < 0: return None,'El valor tiene que ser positivo' else: for i in str(number): contador += 1 return (f'El largo del numero es:{contador}') number_length(-3) ## Ejercicio 2 ​ Crear una funcion que reciba dos numeros como argumentos (numero, longitud), y devolver una lista con los multiplos del numero dada la longitud **Ejemplos** `list_of_multiples(7, 5) ➞ [7, 14, 21, 28, 35]` `list_of_multiples(17, 6) ➞ [17, 34, 51, 68, 85, 102]` **Notas** Vean que la lista contiene el numero que le pasan como argumento ​ **Restricciones** - Los argumentos no puede ser negativos - Los argumentos deben ser enteros def multiplos(numero,rango): list_Numbers = [] result = numero for i in range(rango): result += numero*i list_Numbers.append(result) return list_Numbers multiplos(3,4) def factorial(number): if number > 1: number = number * factorial (number-1) return number factorial(5) Ejercicio 4 Crear una funcion que formatee numeros 😄 Ejemplos format_numer(1000) -> '1,000' format_numer(43214124) -> '43,214,124' Restricciones El argumento no puede ser negativo El argumento deben ser entero Ejercicio 4.1 Agregar el separador que el usuario indique Ejemplo format_numer(1000,'#') -> '1#000' format_numer(43214124) -> '43#214#124' def numeros_formateados(numero,caracter): if not isinstance(numero,int): return None,'No es entero' if not isinstance(caracter,str): return None,'No es válido' i= 20 [i for i in range (100) if not i % 2 == 0 ]
false
5a04434d618ccb463fb39e5bd806abc058a100af
J14032016/LeetCode-Python
/leetcode/algorithms/p0707_design_linked_list_2.py
2,890
4.125
4
class Node: def __init__(self, value=None): self.value = value self.prev = None self.next = None class MyLinkedList: def __init__(self): """ Initialize your data structure here. """ self.head = None def get(self, index: int) -> int: """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. """ i = 0 current = self.head while current and i < index: current = current.next i += 1 return current.value if current else -1 def addAtHead(self, val: int) -> None: """ Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. """ new_head = Node(val) self.head, new_head.next = new_head, self.head if self.head.next: self.head.next.prev = self.head def addAtTail(self, val: int) -> None: """ Append a node of value val to the last element of the linked list. """ current = self.head while current and current.next: current = current.next if current: new_tail = Node(val) current.next, new_tail.prev = new_tail, current else: self.addAtHead(val) def addAtIndex(self, index: int, val: int) -> None: """ Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. """ i = 0 prev = None current = self.head while current and i < index: prev, current = current, current.next i += 1 if i != index: return if prev: new_node = Node(val) prev.next, new_node.next = new_node, current new_node.prev = prev if current: current.prev = new_node else: self.addAtHead(val) def deleteAtIndex(self, index: int) -> None: """ Delete the index-th node in the linked list, if the index is valid. """ i = 0 prev = None current = self.head while current and i < index: prev, current = current, current.next i += 1 if i != index: return if prev and current: prev.next, current.next = current.next, None if prev.next: prev.next.prev = prev elif current: current.next, self.head = None, current.next if self.head: self.head.prev = None
true
f9a8acbe210d47dd995b70588067aae6bb101cd3
MVanDenburg92/StringManipulation
/exercise1.py
1,366
4.21875
4
# Name: Miles Van Denburg # Assignment title: OldMacdonald Capitalization # Time to complete: 20 minutes # Description: Capitalize the 1st and 4th letters in the name "Old MacDonald" #Created a function with takes input "name1" #The function slices first letter value at index 0 and the 4th letter value at index 4, capitalizing them using the .capitlalize method. #The sliced sections of the name are concatenated together along with the none capitalized sections of the name and stored in name2 #The function then returns the value within name2 #The value of name2 is then printed. def old_macdonald(name1): name2 = name1[0].capitalize() + name1[1:3] + name1[4:5].capitalize() + name1[5:] return name2 print(old_macdonald("old macdonald")) #def old_macdonald(name): #name2 = name.capitalize() #name2 = [] #name2 = name.split() #name2[0,3.upper() #name 3 = name2.join() #print(name2) #old_macdonald(name) ##for i in name2 ##if i == 0 # replace this line with code #def old_macdonald(name): #print("Enter in a word to capitalize the 1sta and 4th character) #index = 0 #for i in name # if name[0].islower(): #return name[0].capitalize() + name[1:4] + name[4:5] #elif ireturn name2 #else: #print("You done goofed") #print(old_macdonald("timmy"))
true
489c01f7ba4b299586f542cf9abbc05463c7cb55
python20180319howmework/homework
/huangyongpeng/20180402/h3.py
300
4.1875
4
''' 利用map()函数将用户输入的不规范的英文名字,变为首字母大写,其他字符小写的形式 1) 假定用户输入的是["lambDA", “LILY”, “aliCe”] ''' l=['lambDA','LILY','aliCe'] l1=[] def hy(m): return m.title() r=map( hy,l) for i in r: l1.append(i) print(l1)
false
14b8b2a05810b2d9ce5585fc9abeb05570ed5b50
python20180319howmework/homework
/huangchaoqian/20180330/t1.py
1,352
4.3125
4
''' 完成一下步骤: (1) 在任意位置创建一个目录,如'~/小练习' (2) 在此目录下创建一个文件Blowing in the wind.txt      将以下内容写入文件 Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. (3) 在文件头部插入标题“The Zen of Python” (4) 在标题后插入作者“Tim Peters” (5) 在文件末尾加上字符串“你的名字和作业时间” (6) 在屏幕上打印文件内容 (7) 以上每一个要求封装成小函数 ''' import os def dir(): if os.path.exists("./小练习")!=True: os.mkdir("./小练习") def fil(filename,context): with open(filename,"w") as fd1: fd1.writelines(context) def filere(): fd=open("./t1.txt") l=[] for i in fd: l.append(i) file1="./小练习/"+"Blowing in the wind"+".txt" return fil(file1,l) def mytitle(filename): with open(filename,"w") as fd2: fd2.writeline("The Zen of Python") def zuozhe(filename): with open(filename,"w") as fd3: fd3.writeline("Tim Peters") def nametime(filename): with open(filename,"w") as fd4: fd4.writeline("你的名字和作业时间") if __name__=="__main__": filere() print(dir()) print(mytitle(file1)) print(zuozhe(file1)) print(filere()) print(nametime(file1))
false
44e86b5f41846ec89edfacdb2866fff84b8582ed
python20180319howmework/homework
/huangchaoqian/20180403/t2.py
1,010
4.25
4
''' 定义一个北京欢乐谷门票类,应用你所定义的类,计算两个社会青年和一个学生平日比节假日门票能省多少钱 票价是: 除节假日票价100元/天 节假日为平日的1.2倍 学生半价 ''' class Ticket(): def __init__(self,price=100): self.__price=price def teenager(self): return self.__price # print("社会青年的票价为:{}".format(self.__price)) def student(self): return self.__price/2 # print("学生的票价为:{}".format(self.__price/2)) def setprice(self): # newprice=self.__price*1.2 # self.__price=newprice self.__price*=1.2 def savemoney(m1,m2): return m2-m1 t=Ticket() t1=t.teenager() t.setprice() t2=t.teenager() save1=savemoney(t1,t2) stu=Ticket() st1=stu.student() stu.setprice() st2=stu.student() save2=savemoney(st1,st2) x,y=eval(input("please input teenagernum x and studentnum y:")) print("{}个社会青年和{}个学生平日比节假日门票能省{}元".format(x,y,x*save1+save2*y))
false
66583d93852aab33eb12fc8d74b3a9f4bd631723
python20180319howmework/homework
/huangchaoqian/20180329/t3.py
642
4.125
4
''' 编写一个函数: 1)此函数可以传递任意一组键值对,函数将所有的键存放到一个列表中,返回 2) 升级以上函数,使得用户必须有的键值为:name:"xxx" city:"xxxx" ''' def dic(**kw): print("kw",kw) l=[] for i in kw.keys(): l.append(i) return l def dic2(*,nam,city,**kw): if "name" not in kw.keys(): kw["name"]=nam if "city" not in kw.keys(): kw["city"]=city return kw if __name__=="__main__": # name=input("name:") print(dic(name="huang",city="hubei")) # print(dic2("chao","beijing",age=16,sex="男")) print(dic2(height=170,nam="chao",city="beijing",age=16,sex="男"))
false
84ac9f8bf9dd1f0484d9039e7b60e8ec17f06a99
python20180319howmework/homework
/huangyongpeng/20180405/h2.py
555
4.40625
4
''' 定义一个直线类(Line)和点类(Point),提供一个方法getLength方法,获取直线的长度 ''' import math class Point(object): def __init__(self,x,y): self.__x=x self.__y=y def showX(self): return self.__x def showY(self): return self.__y class Line(): def __init__(self,m,n): self.__x=n.showX()-m.showX() self.__y=n.showY()-m.showY() def getLength(self): return math.sqrt(self.__x*self.__x+self.__y*self.__y) p1=Point(2,3) p2=Point(5,7) l=Line(p1,p2) print("俩点的距离是:{}".format(l.getLength()))
false
c4f60e2098beefb1173f5415bcbeab97928333da
Georycoco/pythonTutorial
/python基础/34.py
651
4.1875
4
# 给程序传参数 import sys print(sys.argv) # name = sys.argv[1] # print('Welcome %s !!!'%name) #可以在程序外直接传入name的值 # 列表生成式 a = [i for i in range(1, 8)] print(a) b = [6 for i in range(1, 8)] print(b) c = [i for i in range(10) if i % 2 == 0] print(c) d = [i for i in range(3) for j in range(2)] print(d) e = [(i, j) for i in range(3) for j in range(2)] print(e) f = [(i, j, k) for i in range(3) for j in range(2) for k in range(2)] print(f) aa = (11,22,33,44,55,11,22,33) bb = [11,22,33,11,22,33] print(aa) print(bb) print(type(aa)) cc = set(bb) #set 也有去重效果 print(cc) dd = list(cc) print(dd)
false
ca4fe387291938202cdf1dc2017caabc7a43320e
Georycoco/pythonTutorial
/python基础/29.py
701
4.375
4
# 多继承 # class Base (object) object 表示无论子类有没有添加都将被继承 class Base(object): def test(self): print('this is base class') class A(Base): def testA(self): print('this is A class') class B(Base): def testB(self): print('this is B class') class C(A, B): def testC(self): print('this is C class') c = C() c.test() # polymorphism class Dog(object): def test(self): print('hello every one~~this is boss here~') class xiaotian(Dog): def test(self): print('hello this is xiaotian here') def introduce(temp): temp.test() dog1 = Dog() dog2 = xiaotian() introduce(dog2) introduce(dog1)
false
311036af5cc9d3bd39afb5ea0a268b1bcc00b106
bigdatasciencegroup/T-I-L
/python/SoloLearn/code-scripts/BMI-Calculator.py
204
4.1875
4
weight=float(input()) height=float(input()) bmi=weight/(height*height) if bmi>=30: print("Obesity") elif bmi>=25: print("Overweight") elif bmi>=18.5: print("Normal") else: print("Underweight")
false
cc705dafcd15e288b5e344be6ae128062f18a150
vickytseng0906/Coursera-UMichigh-Python
/py4e/2_4/ex8_4.py
303
4.34375
4
fname = input("Enter file name: ") #prompt for file name fh = open(fname) #open the file lst = list() #build empty list for line in fh: line = line.strip() line = line.split() # a list of words for word in line: if word not in lst: lst.append(word) lst.sort() print(lst)
true
eee25bd963e53cee87a3b2cde57db530897b07d2
reshamj/DataStructures-Algorithms
/romannumbers.py
1,261
4.1875
4
#1. Verify if an roman number is valid #2. sort an array of roman numbers import re import collections #is it a valid Roman number def isRoman(inputRoman): thousand = r'M{0,3}' hundred = r'(C[MD]|D?C{0,3})' ten = r'(X[CL]|L?X{0,3})' digit = r'(I[VX]|V?I{0,3})' result = bool(re.match(thousand+ hundred+ten+digit+'$', inputRoman.upper())) return result def romanToint(roman_num): #print roman_num nums = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1} while(isRoman(roman_num)): sum = 0 for i in range(len(roman_num)): value = nums[roman_num[i]] if i+1 < len(roman_num) and nums[roman_num[i+1]] > value: sum -= value else: sum += value return sum #sort roman numbers in an array def sortRoman(inputArray): intValue = [] intdict = {} for roman in inputArray: integer = romanToint(roman) intdict[integer] = roman print intdict od = collections.OrderedDict(sorted(intdict.items())) print od #inputArray = ["MMMDCCCLXXXVIII","IV","VII","X","CCD"] inputArray = ["CDXXI", "X", "VIII", "XIII"] sortRoman(inputArray) #result = isRoman('vii') #print result
false
e74b7b82043936edfa7582bc2b3b2f213b958a8e
sai-varshith/Hacktoberfest21-letshack
/Python Programs/print_calendar.py
201
4.375
4
#This program helps you to print the calendar using python code import calendar year=2021 month=4 year=int(input("enter a year:")) month=int(input("enter a month:")) print(calendar.month(year,month))
true
e9e9e28501267d69fdd66526ce73db33bcfa8758
anatolykobzisty/algorithms
/06-Sorting/Quadratic_sorting/bubble_sort.py
943
4.21875
4
''' Сортировка списка A методом пузырька теория https://youtu.be/NLq7nB9bV0M?t=2054 практика https://youtu.be/NLq7nB9bV0M?t=4084 ''' def bubble_sort(A): N =len(A) for bypass in range(1, N): for k in range(0, N-bypass): if A[k] > A[k+1]: A[k], A[k+1] = A[k+1], A[k] def test_sort(sort_algorithm): print("testcase #1: ", end="") A = [4, 2, 5, 1, 3] A_sorted = [1, 2, 3, 4, 5] sort_algorithm(A) print("Ok" if A == A_sorted else "Fail") print("testcase #2: ", end="") A = list(range(10, 20)) + list(range(0, 10)) A_sorted = list(range(20)) sort_algorithm(A) print("Ok" if A == A_sorted else "Fail") print("testcase #3: ", end="") A = [4, 2, 4, 2, 1] A_sorted = [1, 2, 2, 4, 4] sort_algorithm(A) print("Ok" if A == A_sorted else "Fail") test_sort(bubble_sort)
false
02070a516e86d88d3fe9db6a862ef44cf89ccd3c
lawfets/codewars
/K7_EvenOrOddWhichIsGreater.py
338
4.34375
4
def even_or_odd(s): even = 0 odd = 0 for i in s: i = int(i) if i % 2 == 0: even += i else: odd += i if even == odd: return "Even and Odd are the same" elif even > odd: return "Even is greater than Odd" else: return "Odd is greater than Even"
false
41f28360dd75fd3a0f2203833269e33220d5fadf
agolla0440/my_python_workbook
/complex_numbers_demo.py
466
4.25
4
# Python code to demonstrate the working of # complex(), real() and imag() # importing "cmath" for complex number operations import cmath # Initializing real numbers x = 5 y = 3 # converting x and y into complex number z = complex(x, y); s = 5 + 3j # printing real and imaginary part of complex number print("The real part of complex number is : ", end="") print(z.real) print("The imaginary part of complex number is : ", end="") print(z.imag) print(z) print(s)
true
d47f81d16206f30d9b27525f323de478255c7921
SageTheGreat2001/MyRepo
/Math_Program.py
399
4.1875
4
first_num = int(input('Enter in your first number: ')) second_num = int(input('Enter in your second number: ')) sum_one = first_num + second_num diff = first_num - second_num product = first_num * second_num divide = first_num / second_num print('the sum is: ' + str(sum_one)) print('the difference is: ' + str(diff)) print('The product is: ' + str(product)) print('The quotient is: ' + str(divide))
true
78363453569e6fae8413cf6d473a0cea26e0df3a
mylittlecat/python_prac
/编码练习.py
419
4.40625
4
#!/usr/bin/env python ''' An example of reading and writing Unicode string:Writes a Unicode string to a file in utf-8 and reads it back in. ''' CODEC='utf-8' FILE='unicode.txt' hello_out=u"Hello world\n" bytes_out=hello_out#.encode(CODEC) #不用编成UTF-8格式也没问题 f=open(FILE,"w") f.write(bytes_out) f.close() f=open(FILE,"r") bytes_in=f.read() f.close() hello_in=bytes_in#.decode(CODEC) print hello_in,
true
f4e998c9a5564684a7daa6864fdcf5ab73ea4c7b
DiR081/CodiPy-Prof
/listas/eliminar.py
505
4.21875
4
# Listas """ 7.2.1. Eliminar el último elemento de la lista Método: pop() Retorna: el elemento eliminado. 7.2.2. Eliminar un elemento por su índice Método: pop(índice) Retorna: el elemento eliminado. 7.2.3. Eliminar un elemento por su valor Método: remove("valor") """ lista = ["uno" , "dos", "tres", "dos", "cuatro"] print("Lista Original", lista) respuesta = lista.pop() print(respuesta) print(lista) respuesta = lista.pop(2) print(respuesta) print(lista) lista.remove("dos") print(lista)
false
b05b3d230abc27ba9d71db4df5bb781f1d947070
taiannlai/Pythonlearn
/CH3/CH3_15.py
446
4.15625
4
num1 = 111 num2 = 222 num3 = num1 + num2 print("以下是數值相加") print(num3) numstr1 = "222" numstr2 = "333" numstr3 = numstr1 + numstr2 print("以下是由數值組成的字串相加") print(numstr3) numstr4 = numstr1 + " " + numstr3 print("以下是由數值組成的字串相加,同時中間加上一空格") print(numstr4) str1 = "DeepStone " str2 = "Deep Learning" str3 = str1 + str2 print("以下是一般字串相間") print(str3)
false
4219fa85f67a4669e77108a06ca5bc9dd46fe524
FedericoPaini/Python
/fizzBuzzChallenge.py
307
4.1875
4
#!/usr/bin/python def FizzBuzz(number): for x in xrange(1, number+1): if (x % 3) == 0 and (x % 5) == 0: print "FizzBuzz!" elif (x % 3) == 0: print "Fizz" elif (x % 5) == 0: print "Buzz" else: print x number = int(raw_input("Number Range for FizzBuzz Challenge? ")) FizzBuzz(number)
false
e883384bc67411eb11ddd5efcf067d50af35780b
sp-95/Cipher-Techniques
/caesar.py
2,268
4.15625
4
""" Caesar Cipher ============= Input: 1. String of characters consisting of lowercase and uppercase characters 2. Shift key for lowercase characters 3. Shift key for uppercase characters Output: Encrypted and decrypted strings using Caesar Cipher with the given shift keys """ import __future__ __author__ = 'Shashanka Prajapati' class Caesar: def __init__(self): """initialize with no keys""" self.__k1 = 0 self.__k2 = 0 def __encryptLetter(self, c): """Encrypt a single letter""" if c.islower(): return chr((ord(c) - ord('a') + self.__k1) % 26 + ord('a')) elif c.isupper(): return chr((ord(c) - ord('A') + self.__k2) % 26 + ord('A')) else: return c def __decryptLetter(self, c): """Decrypt a single letter""" if c.islower(): return chr((ord(c) - ord('a') - self.__k1) % 26 + ord('a')) elif c.isupper(): return chr((ord(c) - ord('A') - self.__k2) % 26 + ord('A')) else: return c def encrypt(self, input): """Encrypt the input string""" return ''.join([self.__encryptLetter(c) for c in input]) def decrypt(self, input): """Decrypt the input string""" return ''.join([self.__decryptLetter(c) for c in input]) def setLowerKey(self, key): """Set the key value for lowercase letters""" self.__k1 = key def getLowerKey(self, key): """Get the key value for lowercase letters""" return self.__k1 def setUpperKey(self, key): """Set the key value for uppercase letters""" self.__k2 = key def getUpperKey(self, key): """Get the key value for uppercase letters""" return self.__k2 if __name__ == '__main__': # if this file is being executed and not imported message = raw_input("Enter your message: ") k1 = int(raw_input("Enter key for lowercase characters: ")) k2 = int(raw_input("Enter key for uppercase characters: ")) myObj = Caesar() myObj.setLowerKey(k1) myObj.setUpperKey(k2) cipher = myObj.encrypt(message) print("Cipher Text: {}".format(cipher)) plain = myObj.decrypt(cipher) print("Plain Text: {}".format(plain))
true
7e61d5a46b93ca0c58b38189008019829733f5a3
mbledkowski/HelloRube
/Python/inputworld.py
1,232
4.40625
4
#! python3 # helloinputworld.py - Takes user input and gives the impression that calculations are preformed to turn it into "Hello World" import time #ask for user input that will appear to convert to hello world answer = "" while answer == "": answer = input("Type in any word or phrase:") answer = answer.split() #take their input and show status messages that give the impression that input is being adjusted if len(answer) < 2: for i in answer: print("Converting " + i + " to Hello") time.sleep(.5) print("Converted") time.sleep(.5) print("Adding World! to answer") time.sleep(.5) print("Added!") time.sleep(.5) answer = "Hello World!" else: for i,c in enumerate(answer): if i < 1: print("Converting " + c + " to Hello") time.sleep(.5) print("Converted") time.sleep(.5) elif i == 1: print("Converting " + c + " to World!") time.sleep(.5) print("Converted") time.sleep(.5) else: print("Deleting " + c) time.sleep(.5) answer = "Hello World" time.sleep(.5) print("Your new answer is " + answer)
true