blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a024445ad40df6cda322c6bb7aa1b2efafbd9cd3
AngelValAngelov/Python-Advanced-Exercises
/Lists as Stacks and Queues - Lab/01. Reverse Strings.py
247
4.34375
4
def reversed_string(text): s = list() for letter in text: s.append(letter) new_s = list() while s: char = s.pop() new_s.append(char) return "".join(new_s) print(reversed_string(input()))
false
96ed6feaf59796961f8f5228a5402dcc7c70698b
Asilva-01/PythonEstudos
/Aulas_Modulo_Magico_6_2.py
301
4.15625
4
def main(): numero_escolhido = 3 numero_magico = int(input("Valor escolhido pelo magico: ")) if numero_magico > numero_escolhido: print("Diminua o chute") elif numero_magico < numero_escolhido: print("Aumente o chute") else: print("Você acertou") main()
false
f2b94660239c6fa96843a0d999ffe0c40b13bfa4
shadiqurrahaman/python_DS
/tree/basic_tree.py
1,644
4.15625
4
from queue import Queue class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Tree: def __init__(self): self.root = None self.queue = Queue() def push_tree(self,data): new_node = Node(data) if self.root is None: self.root = new_node self.queue.put(self.root) else: recent_node = self.queue.get() if recent_node.left and recent_node.right is not None: recent_node = self.queue.get() if recent_node.left is None: recent_node.left = new_node self.queue.put(recent_node) self.queue.put(recent_node.left) elif recent_node.right is None: self.queue.put(recent_node) recent_node.right = new_node self.queue.put(recent_node.right) def print_tree(self): self.q = Queue() self.q.put(self.root) while(self.q.qsize()!=0): temp = self.q.get() print(temp.data) if temp.left != None: self.q.put(temp.left) if temp.right != None: self.q.put(temp.right) def print_hudai(self): temp = self.root print(temp.left.left.data) if __name__ == "__main__": tree = Tree() tree.push_tree(10) tree.push_tree(11) tree.push_tree(9) tree.push_tree(7) tree.push_tree(15) tree.push_tree(8) tree.print_tree() tree.print_hudai()
true
80ccc65227fafa80fc7c89c31b1030ed7bf6ace7
jetli123/python_files
/廖雪峰-python/廖雪峰-getattr()、setattr()和hasattr().py
1,675
4.375
4
# -*- coding: utf-8 -*- """仅仅把属性和方法列出来是不够的,配合 getattr()、setattr()以及 hasattr(),我们可以直接操作一个对象的状态:""" class MyDog(object): def __init__(self, x, y): self.x = x self.y = y def power(self): print self.x * self.y obj = MyDog(9, 2) obj.power() """紧接着,可以测试该对象的属性""" print hasattr(obj, 'y') # 有属性 'y' 吗? setattr(obj, 'z', 10) # 设置一个属性 'z' print hasattr(obj, 'z') # 有属性 'z' 吗? print getattr(obj, 'y') # 获取属性 'y' # print obj.z # 获取属性 'z' """可以传入一个 default 参数,如果属性不存在,就返回默认值:""" print getattr(obj, 'a', 404) # 获取属性 'a',如果不存在,返回默认值 404 """也可以获得对象的方法:""" print hasattr(obj, 'power') # 有属性 'power' 吗? print getattr(obj, 'power') # 获取属性 'power' # 小结: """通过内置的一系列函数,我们可以对任意一个 Python 对象进行剖析, 拿到其内部的数据。要注意的是,只有在不知道对象信息的时候,我们才会去获取对象信息。如果可以直接写: sum = obj.x + obj.y 就不要写: sum = getattr(obj, 'x') + getattr(obj, 'y')""" su = obj.x + obj.y print 'SU:', su """如果想用hasattr:""" def ReadImage(fp): if hasattr(fp, 'read'): return readData(fp) return None """假设我们希望从文件流 fp 中读取图像,我们首先要判断该 fp 对象是否 存在 read 方法,如果存在,则该对象是一个流,如果不存在,则无法读 取。hasattr()就派上了用场。"""
false
b5bc70ffb388b8e022763e404187d7d60b56db0e
jetli123/python_files
/廖雪峰-python/廖雪峰-面向对象之定制类-__str__.py
1,815
4.21875
4
# -*- coding: utf-8 -*- __author__ = 'JetLi' # -*- __str__ -*- class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name: %s)' % self.name __repr__ = __str__ # 直接显示变量调用的不是__str__(),而是__repr__(),两者的 # 区别是__str__()返回用户看到的字符串,而__repr__()返回程序开发者 # 看到的字符串,也就是说, __repr__()是为调试服务的。 # 这样打印出来的实例,不但好看,而且容易看出实例内部重要的数据 print (Student('Michael')) # 直接显示变量调用的 __str__() s = Student('Michael') # 直接显示变量调用的 __repr__() print s ################################################# # -*- __iter__ -*- ########### """如果一个类想被用于 for ... in 循环,类似 list 或 tuple 那样,就必须实 现一个__iter__()方法,该方法返回一个迭代对象,然后, Python 的 for 循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值, 直到遇到 StopIteration 错误时退出循环。""" # 我们以斐波那契数列为例,写一个 Fib 类,可以作用于 for 循环 class Fib(object): def __init__(self): self.a, self.b = 0, 1 # 初始化两个计数器 a, b def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 def next(self): # python 3.0 以上版本 用 __next__ 方法 self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 1000: # 退出循环条件 raise StopIteration return self.a # 返回下一个值 for n in Fib(): assert isinstance(n, object) print n
false
123c032edcf3c3f86b49ee8c9dba5fd2afffa631
jetli123/python_files
/廖雪峰-python/廖雪峰-面向对象之类的继承和多态.py
1,539
4.4375
4
# -*- coding: utf-8 -*- """在 OOP 程序设计中,当我们定义一个 class 的时候,可以从某个现有的 class 继承,新的 class 称为子类(Subclass),而被继承的 class 称为基 类、父类或超类(Base class、 Super class)。""" class Animal(object): # Animal 是两个子类 dog 和 cat 的父类 def runs(self): print('Animal is running...') """当子类和父类都存在相同的 runs()方法时,我们说,子类的 runs()覆盖了 父类的 runs(),在代码运行的时候,总是会调用子类的 runs()。这样,我 们就获得了继承的另一个好处:多态。""" # 也可以对子类增加一些方法,比如 Dog 类: class dog(Animal): # 子类 dog 继承了 父类Animal 的方法 runs() def runs(self): print('Dog is running...') class cat(Animal): # 子类 cat 继承了 父类Animal 的方法 runs() def runs(self): print('Cat is running...') d = dog() d.runs() c = cat() c.runs() """多态""" """当我们定义 一个 class 的时候,我们实际上就定义了一种数据类型。我们定义的数 据类型和 Python 自带的数据类型,比如 str、 list、 dict 没什么两样:""" a = list() print isinstance(a, list) # True b = Animal() print isinstance(b, Animal) # True print isinstance(d, dog) # True """在继承关系中,如果一个实例的数据类型是某个子类,那它的数 据类型也可以被看做是父类。""" print isinstance(c, cat) # True print isinstance(c, Animal)
false
91a29c4d16ea8e3459bf94a3303e090dd67617e3
jetli123/python_files
/廖雪峰-python/廖雪峰-面向对象之调用不存在的属性__getattr__()方法.py
1,549
4.15625
4
# -*- coding: utf-8 -*- """当调用不存在的属性时,比如 score, Python 解释器会试图调用 __getattr__( self, 'score')来尝试获得属性,这样,我们就有机会返回 score 的值""" """注意,只有在没有找到属性的情况下,才调用__getattr__,已有的属性, 比如 name,不会在__getattr__中查找。""" class Student(object): def __init__(self): self.name = 'Michael' def __getattr__(self, attr): if attr == 'score': return 99 s = Student() print s.name # Michael print s.score # 99 # 返回函数也是完全可以的: class Stu(object): def __getattr__(self, attr): if attr == 'age': return lambda: 25 b = Stu() print b.age() # 25 print b.name # None """此外,注意到任意调用如 s.abc 都会返回 None,这是因为我们定义的 __getattr__默认返回就是 None。要让 class 只响应特定的几个属性,我 们就要按照约定,抛出 AttributeError 的错误:""" class Students(object): def __getattr__(self, attr): if attr == 'ages': return lambda: 22 raise AttributeError('\'Students \' object has no attribute \'%s\'' % attr) c = Students() print c.ages() # 22 print c.name() class Chain(object): def __init__(self, path=''): self.path = path def __getattr__(self, path): return Chain('%s/%s' % (self._path, path)) def __str__(self): return self._path __repr__ = __str__ Chain().stauts.user.timeline.list
false
2699742da7500f56858626be9c6369a58c96f0ed
jyoshnalakshmi/python_examples
/file_handling/file_write.py
691
4.25
4
#-------------------------------------------------------------------- #Description : Writing into the file #Used Function : write() #Mode : 'w' #-------------------------------------------------------------------- with open('file1.py','w') as f: print("write(This is write function using 'w')"); f.write("Hey this the write function"); #-------------------------------------------------------------------- #Description : Adding data into the file #Used Function : write() #Mode : 'a' #-------------------------------------------------------------------- with open('file1.py','a') as f: print("write(writing data using append it at the end)"); f.write("--Adding this line --");
true
10b02c26c2f09f703ce16eab5d8a0183677d8fb2
dhiraj1996-bot/Code-a-Thon
/list.py
502
4.125
4
#Question 2 list1 = ["aman","raj","ayush","gracie"] list2 = ["akshay","rakesh","raj","ram"] #creating a function to check for duplicate values and then removing them #and creating list without the duplicate values def find_common(list1,list2): for x in list1: for y in list2: if x == y : list2.remove(x) list1.remove(y) print(" list1:",list1) print(" list2:",list2) print(" new_list:",list1+list2) find_common(list1,list2)
true
dd52c000cd4d5d7a021449a7451de4fa84047042
nkuhta/Python-Data-Structures
/2. Files/average_spam_confidence.py
938
4.125
4
############################################################## ######### compute the average spam ############ ############################################################## # X-DSPAM-Confidence:0.8475 # Prompt for user input filename then search for the number and average fname=input('Enter filename: ') try: fhand = open(fname) except: print("file does not exist") exit() # line iteration variable count=0 # spam value iteration variable that will be summed over num=0 # extract the spam confidence values and average them for line in fhand: if line.startswith("X-DSPAM-Confidence"): # index value for the ":" chararcter ival = line.find(":") # numline is the number after the ":" numline = float(line[ival+1:].lstrip()) count = count+1 num = num + numline avg = num/count print('count = ',count) print('average spam confidence = ',avg)
true
17601497f9bb20611bbca1bec0f8dcd40767db54
nitschmann/python-lessons
/07_dictionaries/exc_47.py
616
4.25
4
# dictionaries - exercise 47 country_rivers = { "China": "Yangtze", "China": "Yangtze", "China": "Ob-Irtysh", "Germany": "Elbe", "Germany": "Oder", "Germany": "Rhine", "USA": "Missouri", "USA": "Yukon", "USA": "Colorado" } country_river_list = {} for country, river in country_rivers.items(): if country not in country_river_list: country_river_list[country] = [] country_river_list[country].append(river) for country, rivers in country_river_list.items(): print("Rivers in {}: {}".format(country, set(rivers)))
false
b4846a2a1d6db0d4cbc3bb5a9097c509af4484a5
nitschmann/python-lessons
/04_list_manipulations/exc_18.py
374
4.25
4
# list manipulations - exercise 18 cities = ["St. Petersburg", "Moscow", "Buenos Aires", "New York", "Stockholm", "Amsterdam"] print(cities) print(sorted(cities)) print(cities) print(sorted(cities, reverse = True)) print(cities) cities.reverse() print(cities) cities.reverse() print(cities) cities.sort() print(cities) cities.sort(reverse = True) print(cities)
true
058596c252eaf726187130550b12f9a293035d6f
nitschmann/python-lessons
/05_working_with_lists/exc_30.py
335
4.53125
5
# working with lists - exercise 30 my_pizzas = ["mista", "salami", "pepperoni"] friend_pizzas = my_pizzas[:] my_pizzas.append("parma") friend_pizzas.append("magaritha") print("My favorite pizzas are:") for pizza in my_pizzas: print(pizza) print("\nMy friends' favorite pizzas are:") for pizza in friend_pizzas: print(pizza)
false
176a4b1c9ae3026deef18b839ce5c1744cba351b
Ntims/Nt_Python
/실습20190419-20194082-김민규/P0601-1.py
274
4.3125
4
for letter in "Python": print("Current letter :",letter) print() fruits = ["banana", "apple", "mango"] for fruit in fruits: print("Current fruit:",fruit) print("Using Index") for index in range(len(fruits)): print("Current fruit:", fruits[index])
false
2259528e78ea92e3b074f54438e62b0ca30c4b97
rodrigojgrande/python-mundo
/desafios/desafio-037.py
1,020
4.3125
4
#Exercício Python 37: Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. numero = int(input('Digite um número inteiro:')) print('Escolha uma das bases para conversão:') print('[ \033[1;33m1\033[m ] Converter para Binário') print('[ \033[1;33m2\033[m ] Converter para Octal') print('[ \033[1;33m3\033[m ] Converter para Hexadecimal') escolha = int(input('Sua opção:')) if escolha == 1: resultado = bin(numero)[2:] print('\033[1;32m{} convertido para Binário é igual a {}.\033[m'.format(numero, resultado)) elif escolha == 2: resultado = oct(numero)[2:] print('\033[1;312{} convertido para Octal é igual a {}.\033[m'.format(numero, resultado)) elif escolha == 3: resultado = hex(numero)[2:] print('\033[1;32m{} convertido para Hexadecimal é igual a {}.\033[m'.format(numero, resultado)) else: print('\033[1;31mComando inválido!\033[m')
false
0273bfcd36fb3155e3affb97bac7ac18345b3fa5
rodrigojgrande/python-mundo
/desafios/desafio-103.py
613
4.1875
4
#Exercício Python 103: Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente. def ficha(nome='<desconhecido>', gols=0): print(f'O jogador {nome} fez {gols} gols no campeonato.') nome = str(input('Nome do jogador: ')) gols = str(input('Número de gols: ')) if gols.isnumeric(): gols = int(gols) else: gols = 0 if nome.strip() == '': ficha(gols=gols) else: ficha(nome, gols)
false
30a64779a2aeb830ef34fdbaae0567c8a74f281d
rodrigojgrande/python-mundo
/desafios/desafio-009.py
656
4.15625
4
#Exercício Python 9: Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada. x = int (input('Digite um número para ver sua tabuada: ')) print('-' * 12) print('{} X {:2} = {:2}'. format(x, 1, x*1)) print('{} X {:2} = {:2}'. format(x, 2, x*2)) print('{} X {:2} = {:2}'. format(x, 3, x*3)) print('{} X {:2} = {:2}'. format(x, 4, x*4)) print('{} X {:2} = {:2}'. format(x, 5, x*5)) print('{} X {:2} = {:2}'. format(x, 6, x*6)) print('{} X {:2} = {:2}'. format(x, 7, x*7)) print('{} X {:2} = {:2}'. format(x, 8, x*8)) print('{} X {:2} = {:2}'. format(x, 9, x*9)) print('{} X {:2} = {:2}'. format(x, 10, x*10)) print('-' * 12)
false
25d0ab0c0367387131fa13c0167970936a056d0f
rodrigojgrande/python-mundo
/desafios/desafio-060.py
435
4.1875
4
#Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial. Exemplo: #5! = 5 x 4 x 3 x 2 x 1 = 120 from math import sqrt fatorial f = factorial(x) x = int(input('\033[1;34mDigite um número para calcular seu Fatorial:\033[m ')) print('Calculando {}! = '.format(x), end='') total = x while x > 1: print('{} x '.format(x), end='') x -= 1 total = total * x print('1 = {}'.format(total))
false
c6b204891b2357bc5773f4f8bcb519277bfb24bd
VitaliyYa/stepik-python
/1st_week/1.12-5_var-2.py
594
4.3125
4
""" task link: https://stepik.org/lesson/5047/step/5?unit=1086 Напишите программу, которая получает на вход три целых числа,по одному числу в строке, и выводит на консоль в три строки сначала максимальное, потом минимальное, после чего оставшееся число. На ввод могут подаваться и повторяющиеся числа. """ x = sorted([int(input()), int(input()), int(input())]) print(x[2], x[0], x[1], sep='\n')
false
f9aa373d5928ace3f4b80cc76fb891df82fc9efe
VitaliyYa/stepik-python
/3rd_week/3.2-7.py
368
4.15625
4
""" link task: https://stepik.org/lesson/3373/step/7?unit=956 """ # Считайте, что функция f(x) уже определена выше. Определять её отдельно не требуется. n = int(input()) dic = {} for n in range(0, n): n = int(input()) if dic.get(n) == None: dic.setdefault(n, f(n)) print(dic[n])
false
ba3feed540cb189ed77fdf8266f2a639e76fb149
RAKUZ4N/HelloPython_1
/1.occupation/hellopython_1.4.py
1,490
4.28125
4
#Создайте 4 условия: #1. Число А больше В но меньше С. #2. Результат деления по модулю числа 7 на 3 умножить на 4.8. #3. Создать два разных выражения которые равны друг другу. #4. Создать 2 выражения которые не равны друг другу. #Первое задание: print("1. Число А больше В но меньше С.") A = 50 print("A = 50") B = 33 print("B = 33") C = 79 print("C = 79") print("50 > 33:", A > B) print("50 < 79:", A < C) #Второе задание: print("2. Результат деления по модулю 7 на 3 умножить на 4.8.") res = 7 % 3 print("Результат деления по модулю:", res) res = res * 4.8 print("Результат:", res) #Третье задание: print("3. Создать два разных выражения которые равны друг другу.") number1 = 85 % 19 print("85 % 19 =", number1) number2 = 45 // 5 print("45 // 5 =", number2) res = number1 == number2 print("9 == 9, результат:", res) #Четвёртое задание: print("4. Создать 2 выражения которые не равны друг другу.") number1 = 127 * 9 print("127 * 9 =", number1) number2 = 6350 - 109 print("6350 - 109 =", number2) res = number1 != number2 print("1143 != 6241, результат:", res)
false
bf01b625f245b45164d8c1610ed95ab6becd4365
RAKUZ4N/HelloPython_1
/1.occupation/hellopython_1.6.py
628
4.1875
4
# PROBLEM 9: # Создать 2 переменные. # В первой год вашего рождения, Во второй # 2020 год # посчитайте сколько лет вам должно быть через 2 года/и сколько лет вам было два года назад my_birthyears = 2002 print("Я родился в", my_birthyears, "году") this_year = 2021 print("Текущий год", this_year) res = this_year + 2 - my_birthyears print("Мне через 2 года будет", res) res1 = this_year - 2 - my_birthyears print("Мне 2 года назад было", res1)
false
91d7b234c678b208c72ff61e43ddda24ee189ed0
RAKUZ4N/HelloPython_1
/4.occupation/Цикл_4.3.py
353
4.125
4
# 3. Напишите код, который берёт цифру 7, умножает саму на себя же 5 раз. number = 7 print("У нас есть число", number, "надо умножит её саму на себя 5 раз") for i in range(6): print(number) number *= 7 print("Программа завершилась!!!")
false
6efd7abb2ddb79175cc5fcf9f3cf8f3d031bcd1c
jihongeek/Algo
/baekjoon/2920.py
277
4.34375
4
inputlist = input().split() ascending = ["1","2","3","4","5","6","7","8"] descending = list(reversed(ascending)) if inputlist == ascending: print("ascending",end="") elif inputlist == descending: print("descending",end="") else: print("mixed",end="")
false
c3e5bce720be7b1d73cdc72befdaf18f9e6c27da
dipikarpawarr/TQ_Python_Programming
/PythonPracticePrograms/String/Remove_Occurrances_Of_Specific_Character.py
257
4.28125
4
# WAP to remove all occurences of given char from String strInput = input("\nEnter the string = ") charRemove = input("Which character you have to remove = ") result = strInput.replace(charRemove,"") print("\nBefore = ", strInput) print("After = ",result)
true
06970f054e1768bc231abc16a32fff9286e053f6
dipikarpawarr/TQ_Python_Programming
/PythonPracticePrograms/String/Anagram_String.py
456
4.15625
4
# WAP to accept 2 string and check whether they are anagram or not eg) MARY ARMY strInput1 = input("Enter the first string = ") strInput2 = input("Enter the second string = ") if len(strInput1) == len(strInput2): sorted1 = sorted(strInput1) s1 = "".join(sorted1) sorted2=sorted(strInput2) s2 = "".join(sorted2) if s1 == s2: print("Anagram String") else: print("Not Anagram String") else: print("Mismatch input")
true
77bd1bf62927f89fbbfc01fd300a2d5ca7677dc3
dipikarpawarr/TQ_Python_Programming
/PythonPracticePrograms/Flow Control - Loops/Count_Digits_In_Given_Number.py
247
4.28125
4
# Write a Python program to count number of digits in any number num = int(input("Enter the number = ")) numHold = num count = 0 while(num>0): digit = num %10 count += 1 num //= 10 print("Total digits in the ",numHold," is = ", count)
true
85bd50a7ef08b61082969d3a7a8b5a9a7efc04e9
dipikarpawarr/TQ_Python_Programming
/PythonPracticePrograms/Flow Control - Loops/Pallindrome_Number.py
576
4.125
4
# WAP to check given no is palindrome or not. Original =Reverse # Eg 1221, 141, 12321, etc num = input("Enter the number = ") print("\n---- Solution 1 ----") reverse = num[::-1] if num == reverse: print(num," is palindrome") else: print(num, " is not palindrome") # OR print("\n---- Solution 2 ----") num1 = int(input("Enter the number = ")) numHold1 = num1 strReverse = "" while(numHold1>0): digit = numHold1 % 10 strReverse += str(digit) numHold1 //= 10 if num == strReverse: print(num," is palindrome") else: print(num, " is not palindrome")
true
e9f6c423bded4e9cedd97c1be8029fc071484c05
sidneisilvadev/projetos
/calculadora elaborada.py
407
4.125
4
n1=int(input("digite numero :")) n2=int(input("digite numero :")) oper=input("digite soma = +,subtração = -,multiplicação = *,divisao = /:") #soma if (oper=="+"): print("resultado = ",n1+n2) #subtração if (oper=="-"): print("resultado = ",n1-n2) #multiplicação if (oper=="*"): print("resultado = ",n1*n2) #divisão if (oper=="/"): print("resultado = ",n1/n2)
false
4480bee0ef9545850813c86dc89463e0a42015a8
mdfox760/pypractice
/range.py
364
4.15625
4
for i in range(5): print(i) print('***') for x in range(5, 10): print(x) print('***') for b in range(0, 10, 3): print(b) print('***') for c in range(-10, -100, -30): print(c) a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) print(range(10)) range(0, 10) # Creates a list from iterables: list(range(5))
false
55c986710dc439d7818700236233a042e3ca1a76
jerome1232/datastruct-tut
/src/2-topic-starter.py
1,629
4.34375
4
class Queue: ''' This represents a queue implemented by a doubly linked list. ''' class Node: ''' An individual node inside a linked list ''' def __init__(self, data): '''Initialize with provided data and no links.''' self.data = data self.previous = None self.next = None def __init__(self): '''Initialize an empty linked list.''' self.head = None self.tail = None def enqueue(self, value): '''Add a node to the end of the queue''' pass def dequeue(self): '''Remove a node from the front of the queue.''' pass def proccess(self, athelete): '''Processes an atheletes information''' place = "" if athelete is None: return elif athelete[1] == 1: place = "got Gold" elif athelete[1] == 2: place = "got Silver" elif athelete[1] == 3: place = "got Bronze" elif athelete[1] == 4: place = "got honorable mention" else: place = "Did not place" print(athelete[0], place, "with score:", athelete[2]) athletes = (('Susan', 1, 100), ('Billy', 3, 300), ('Jill', 2, 500), ('Anthony', 3, 200), ('Eric', 4, 30), ('Erin', 2, 25), ('Elizabeth', 5, 32), ('Angela', 1, 22), ('Emilee', 3, 89), ('Sarah', 6, 999), ('Anna', 8, 245)) work = Queue() work_length = 0 for athelete in athletes: work.enqueue(athelete) work_length += 1 while work_length > 0: work.proccess(work.dequeue()) work_length -= 1
true
47f966adae31358284fc408907a2eea4a60f5c23
kensekense/unige-fall-2019
/metaheuristics/example_for_kevin.py
2,864
4.4375
4
''' When you're coding, you want to be doing your "actions" inside of functions. You are usually using your "global" space to put in very specific values. Here's an example. ''' import random def modifier_function (input1, input2): ''' For simplicity, I've named the inputs to this function input1 and input2 to drive home the concept that each function has inputs. You can call them whatever you want. Think of it as, the function will take whatever object you give it, and the function will refer to it as input1 (or input2 or whatever you put the name there) and that reference will only exist INSIDE the function. ''' for i in range(0, len(input1)): #iterate through each value input1 input1[i] += 1 #modify that value by increasing it by 1 while(input2): #shows you that input1 and input2 don't have to be the same type of object print("Infinite loop.") #here input2 is obviously a boolean value (True, False) return input1 #this function returns your input1. From the for loop, you should know that input1 is a list of sorts. def generator_function (input): ''' I think the idea of a generator makes sense. Take a look. ''' output = [0]*input #input here is an integer value, output here is define IN the function. for i in range(0, len(output)): #iterate through the list output. output[i] = random.randint(1,10) #think about what this does return output def observer_function (input): ''' This would be an observer function. They still "return" a value, but these are generally boolean (T/F) ''' if len(input) == 0: #can you explain what this function does? return True else: return False def observer_function_2 (input): ''' This is an example of an observer function that does not return anything. ''' if len(input) == 0: print("I had a good day") else: pass if __name__ == "__main__": #don't worry about what this means, just know that everything past this is "global" array1 = generator_function(10) #it's a generator because it takes an integer input, but your output is something new. #it "generated" (made something new) an array print("Generated array: ", array1) #you stored the array generated by the function as array1. array1 = modifier_function(array1, False) #here the modifier changes the values of the array you put in. You don't get something new as an output. #you can store this array under a new name, but I kept it the same to emphasize the idea of a "modifier." print("After modified: ", array1) obs = observer_function(array1) print(obs) observer_function_2 #do you understand why I don't save observer_function_2 to a variable name?
true
1eafc06083e85e6fff87c4a0c26b0c7a759844f9
deleks-technology/myproject
/simpleCal.py
1,493
4.21875
4
print("Welcome to our simple Calculator... ") print("====================================================================") # Prompt User for first number # to convert a string to a number with use the int()/ float() first_number = float(input("Please input your first number: ")) print("====================================================================") # Prompt User for second number second_number = float(input("Please input your second number: ")) print("====================================================================") # Math Logic # Logic for Addition print(" The Sum of ", first_number, "and", second_number, "=", (first_number + second_number)) print("====================================================================") # Logic for substraCTION print(" The Substraction of ", first_number, "and", second_number, "=", (first_number - second_number)) print("====================================================================") # Logic for division print(" The division of ", first_number, "and", second_number, "=", round(first_number / second_number, 2)) print("====================================================================") # Logic for multiplication print(" The multiple of ", first_number, "and", second_number, "=", (first_number * second_number)) print("====================================================================") # Logic for raise to power 2 print("The square of", first_number, "=", (first_number ** 2))
true
24dccadfc40fb85d20305d92ba298bc511a6ea64
niranjan2822/PythonLearn
/src/Boolean_.py
804
4.375
4
# Boolean represent one of two values : # True or False print(10 > 9) # --> True print(10 == 9) # --> False print(10 < 9) # --> False # Ex : a = 200 b = 300 if b > a: print("b is greater than a") else: print("b is not greater than a") # Output --> b is greater than a # bool() --> The bool() function allows you to evaluate any value and give you True or False in return . # Example : print(bool("Hello")) # --> True print(bool(15)) # --> True # Evaluate two variables : x = "Hello" y = 15 print(bool(x)) print(bool(y)) # Output - True # Output - True # Some values are False print(bool(False)) print(bool(None)) print(bool(0)) print(bool("")) print(bool(())) print(bool([])) print(bool({})) # Function can return a boolean def func(): return True print(func()) # True
true
223bf6f986a50959f1f6f61520204ad384e2daec
sachdevavaibhav/CFC-PYDSA-TEST01
/Test-01-Py/Ans-03.py
281
4.1875
4
# 3. Write a Python program to sum of two given integers. However, if the sum # is between 15 to 20 it will return 20. num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) ans = num1 + num2 if 15 <= ans <= 20: print(20) else: print(ans)
true
17eec4b963a4a7fb27a29279261a1df059be22e3
amaria-a/secu2002_2017
/lab03/code/hangman.py
2,022
4.15625
4
# load secret phrase from file f = open('secret_phrase.txt','r') # ignore last character as it's a newline secret_phrase = f.read()[:-1] # get letters to guess, characters to keep, initialize ones that are guessed to_guess = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' to_keep = " ,'-" guessed = [] # create version to show to user with letters turned to - shown_phrase = '' for char in secret_phrase: # want to preserve certain characters # ternary operator, could do using regular if/else as we do below char_to_add = char if char in to_keep else '_' shown_phrase = shown_phrase + char_to_add # now start interacting with users to get them to guess letters # terminate when they have guessed the phrase while shown_phrase != secret_phrase: text = 'The phrase is\n' + shown_phrase + '\nNow guess a letter: ' x = raw_input(text) # only want users to guess single letters while len(x) > 1: x = raw_input('Sorry, please guess only a single character: ') # also want them guessing only letters while x not in to_guess: x = raw_input('Sorry, please guess only letters: ') # now cast input as lowercase value to be consistent with phrase x = x.lower() # if the user has guessed letter already there's no point in redoing this if x not in guessed: # log that the user has guessed the character guessed.append(x) # now replace in shown_phrase if it's in secret_phrase if x in secret_phrase: # recreate shown_phrase with replacements in guessed new_shown_phrase = '' for char in secret_phrase: if char in guessed or char in to_keep: new_shown_phrase = new_shown_phrase + char else: new_shown_phrase = new_shown_phrase + '_' # now replace shown_phrase with updated value shown_phrase = new_shown_phrase print 'Congratulations! You guessed the phrase in', len(guessed), 'tries.'
true
42e1b76389b3f6dd99e36f7d8f4d3f89fe3af8c0
mguid73/basic_stats
/basic_stats/basic_stats.py
788
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Basic stats module """ def mean(a): """ input is the list of numbers you want to take the mean """ # computing amount ctlist= [] for n in a: n=1 # changing every value in the list to 1 ctlist.append(n) # creating a new list made up of 1's count = 0 for s in ctlist: # for loop to iteratively add values in sumlist count += s # augmented assignment expression calculates count # Compute the mean of the elements in list a. listsum = 0 for n in a: # for loop to iteratively add values listsum += n # augmented assignment expression calculates sum # we have the sum and the N of the list, now lets calculate mean avg = listsum/count return avg
true
43e2dccabe35905571ca61822de501fd25906b79
AlexanderHurst/CrackingVigenereCypher
/vigenere.py
2,009
4.1875
4
from sys import argv import string_tools from sanitization import sanitize # takes a secret message and key and returns # vigenere ciphertext # note secret message and key must be a list of numbers # use string tools to convert def encrypt(secret_message, secret_key): cipher_text = [] # encrypting adds the key, if result it outside of alphabet # roll back to the beginning of the alphabet rollback = 26 # for each letter in the secret message # use the index of the key for a ceasarian cipher # and append the new letter to the cipher text for i, letter in enumerate(secret_message): # rotate the letter by the secret key index # key is repeated for cipher texts longer than key cipher_letter = ( letter + secret_key[i % len(secret_key)]) % rollback cipher_text.append(cipher_letter) return cipher_text # takes a cipher text and key and returns # decryption of that text with the key # note cipher text and key must be a list of numbers # use string tools to convert def decrypt(cipher_text, secret_key): secret_message = [] rollforward = 26 # basically performs the above operation in reverse for i, letter in enumerate(cipher_text): secret_letter = ( letter - secret_key[i % len(secret_key)]) % rollforward secret_message.append(secret_letter) return secret_message # quick validation method if __name__ == "__main__": secret_message = string_tools.string_to_num_list( sanitize(argv[1], '[^a-zA-Z]', ""), 'A') secret_key = string_tools.string_to_num_list( sanitize(argv[2], '[^a-zA-Z]', ""), 'A') cipher_text = encrypt(secret_message, secret_key) print("encrypt(", secret_message, ", ", secret_key, "):\n\t", cipher_text) print() secret_message = decrypt(cipher_text, secret_key) print("decrypt(", cipher_text, ", ", secret_key, "):\n\t", secret_message) print(string_tools.num_list_to_string(secret_message, 'A'))
true
eb8f13ba8ef2c9a7adad8dcc94081a8aa24cb93e
hsinhuibiga/Python
/insertion sort.py
1,419
4.34375
4
# sorts the list in an ascending order using insertion sort def insertion_sort(the_list): # obtain the length of the list n = len(the_list) # begin with the first item of the list # treat it as the only item in the sorted sublist for i in range(1, n): # indicate the current item to be positioned #print(i) current_item = the_list[i] #print(current_item) # find the correct position where the current item # should be placed in the sorted sublist pos = i #print(the_list[pos]) while pos > 0 and the_list[pos - 1] > current_item: # shift items in the sorted sublist that are # larger than the current item to the right the_list[pos] = the_list[pos - 1] pos -= 1 print(the_list[pos]) # place the current item at its correct position the_list[pos] = current_item return the_list the_list = [54,26,93,17,77,31,44,55,20] #the_list = [77,31,55,20] print(insertion_sort(the_list)) """ def insertionSort(alist): for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] position = position-1 alist[position]=currentvalue alist = [54,26,93,17,77,31,44,55,20] insertionSort(alist) print(alist) """
true
1f0572c27e4187c8d5c335476f8e59b5288019e2
yonghee555/Python-Study
/7_추상_데이터_타입/13_reverse_string_with_stack.py
314
4.1875
4
from stack import Stack def reverse_string_with_stack(str1): s = Stack() revStr = '' for c in str1: s.push(c) for _ in range(s.size()): revStr += s.pop() return revStr if __name__ == "__main__": str1 = "Hello!" print(str1) print(reverse_string_with_stack(str1))
false
d70613eaa55ed3f52e384a4f97e3a751d0723e87
grimmi/learnpython
/linkedlist1.py
1,132
4.125
4
''' Linked Lists - Push & BuildOneTwoThree Write push() and buildOneTwoThree() functions to easily update and initialize linked lists. Try to use the push() function within your buildOneTwoThree() function. Here's an example of push() usage: var chained = null chained = push(chained, 3) chained = push(chained, 2) chained = push(chained, 1) push(chained, 8) === 8 -> 1 -> 2 -> 3 -> null The push function accepts head and data parameters, where head is either a node object or null/None/nil. Your push implementation should be able to create a new linked list/node when head is null/None/nil. The buildOneTwoThree function should create and return a linked list with three nodes: 1 -> 2 -> 3 -> null taken from: http://www.codewars.com/kata/linked-lists-push-and-buildonetwothree/train/python ''' class Node(object): def __init__(self, data, next_node = None): self.data = data self.next = next_node def push(head, data): return Node(data, head) def build_one_two_three(): return push(push(push(None, 3), 2), 1) chain = push(None, 1) chain = push(chain, 2) chain = push(chain, 3) print(chain)
true
d3e25805b601aff974c730abd85b4368724d09d4
grimmi/learnpython
/reversebytes.py
810
4.125
4
''' A stream of data is received and needs to be reversed. Each segment is 8 bits meaning the order of these segments need to be reversed: 11111111 00000000 00001111 10101010 (byte1) (byte2) (byte3) (byte4) 10101010 00001111 00000000 11111111 (byte4) (byte3) (byte2) (byte1) Total number of bits will always be a multiple of 8. The data is given in an array as such: [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0] taken from: https://www.codewars.com/kata/569d488d61b812a0f7000015/train/python ''' def data_reverse(data): def chunk(ns, size): for x in range(0, len(ns), size): yield ns[x:x + size] chunks = reversed(list(chunk(data, 8))) return sum(chunks, []) print(data_reverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]))
true
b813a38631d35d6ccc84b871fade7dc9ccbde14c
ll0816/My-Python-Code
/decorator/decorator_maker_with_arguments.py
1,084
4.1875
4
# !/usr/bin/python # -*- coding: utf-8 -*- # decorator maker with arguments # Liu L. # 12-05-15 def decorator_maker_with_args(d_arg1, d_arg2): print "I make decorators! And I accept arguments:{} {}".format(d_arg1, d_arg2) def decorator(func): print "I am the decorator. Somehow you passed me arguments: {} {}".format(d_arg1, d_arg2) def wrapper(*args): print ("I am the wrapper around the decorated function.\n" "I can access all the variables\n" "\t- from the decorator: {0} {1}\n" "\t- from the function call: {2} {3}\n" "Then I can pass them to the decorated function" .format(d_arg1, d_arg2, *args)) return func(*args) return wrapper return decorator @decorator_maker_with_args("Leonard", "Sheldon") def decorated_func_with_args(*args): print ("I am the decorated function and only knows about my arguments: {0}" " {1}".format(*args)) if __name__ == '__main__': decorated_func_with_args("Rajesh", "Howard")
true
295ace8f90f7303eba831493003cdd7289a4c3c9
ll0816/My-Python-Code
/decorator/dive_in_decorator.py
1,094
4.21875
4
# !/usr/bin/python # -*- coding: utf-8 -*- # dive in decorator # Liu L. # 12-05-15 def decorator_maker(): print "I make decorators! I am executed only once:"+\ "when you make me create a decorator" def my_decorator(func): print "I am a decorator! I am executed"+\ "only when you decorate a function." def wrapper(): print "I am the wrapper around the decorated function. "+\ "I am called when you call the decorated function. "+\ "As the wrapper, I return the RESULT of the decorated function." return func() print "As the decorator, I return the wrapped function." return wrapper print "As a decorator maker, I return a decorator" return my_decorator if __name__ == '__main__': def decorated_func(): print "I am the decorated function" decorated_function = decorator_maker()(decorated_func) decorated_function() print "\n" @decorator_maker() def decorated_func2(): print "I am the decorated function." decorated_func2()
true
3f9963f130edfeb952f10d9197645cf7ffce7ddb
RodionLe/Dawson-Python
/7/обработаем.py
1,609
4.3125
4
# Демонстрирует обработку исключительных ситуаций try: num = float(input("Введите число ")) except: print("Похоже, это не число") try: num = float(input("\nВведите число ")) except ValueError: print("Это не число") # Обработка исключений нескоьких разных типов print() for value in (None, "Привет!"): try: print("Пытаюсь преобразовать в число:", value, "-->", end=" ") print(float(value)) except (TypeError, ValueError): print("Похоже это не число") print() for value in (None, "Привет!"): try: print("Пытаюсь преобразовать в число:", value, "-->", end=" ") print(float(value)) except TypeError: print("Я умею преобразовывать только строки и числа!") except ValueError: print("Я умею преобразовывать только строки, составленные из цифр!") # Получение аргумента try: num = float(input("\nВведите число: ")) except ValueError as e: print("Это не число! Интерпретатор как бы говорит нам: ") print(e) try: num = float(input("\nВведите число: ")) except ValueError: print("Это не число!") else: print("Вы ввели число ", num) input("Нажмите enter, чтобы выйти")
false
b8fdbfa602d0928217d6fa18a3dee3bdfaf6890d
AnanthaVamshi/PySpark_Tutorials
/code/chap02/word_count_driver_with_filter.py
2,672
4.21875
4
#!/usr/bin/python #----------------------------------------------------- # This is a word count in PySpark. # The goal is to show how "word count" works. # Here we write transformations in a shorthand! # # RULES: # # RULE-1: # Here I introduce the RDD.filter() transformation # to ignore the words if their length is less than 3. # This is implemented by: # .filter(lambda word : len(word) > 2) # RULE-2: # If the total frequency of any unique word is less # than 2, then ignore that word from the final output # This is implemented by: # .filter(lambda (k, v) : v > 1) # #------------------------------------------------------ # Input Parameters: # argv[1]: String, input path #------------------------------------------------------- # @author Mahmoud Parsian #------------------------------------------------------- from __future__ import print_function import sys from pyspark.sql import SparkSession #===================================== def debug_file(input_path): # Opening a file in python for reading is easy: f = open(input_path, 'r') # To get everything in the file, just use read() file_contents = f.read() #And to print the contents, just do: print ("file_contents = \n" + file_contents) # Don't forget to close the file when you're done. f.close() #end-def #===================================== if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: word_count_driver.py <input-path>", file=sys.stderr) exit(-1) spark = SparkSession\ .builder\ .appName("Word-Count-App")\ .getOrCreate() # sys.argv[0] is the name of the script. # sys.argv[1] is the first parameter input_path = sys.argv[1] print("input_path: {}".format(input_path)) debug_file(input_path) # create frequencies as RDD<unique-word, frequency> # Rule-1: filter(): if len(word) < 3, then # drop that word frequencies = spark.sparkContext.textFile(input_path)\ .filter(lambda line: len(line) > 0)\ .flatMap(lambda line: line.lower().split(" "))\ .filter(lambda word : len(word) > 2)\ .map(lambda word: (word, 1))\ .reduceByKey(lambda a, b: a + b) # print("frequencies.count(): ", frequencies.count()) print("frequencies.collect(): ", frequencies.collect()) # Rule-2: filter(): if frequency of a word is > 1, # then keep that word filtered = frequencies.filter(lambda (k, v) : v > 1) print("filtered.count(): ", filtered.count()) print("filtered.collect(): ", filtered.collect()) # done! spark.stop()
true
0ceacfc9a01043c67e1b717c205fbaf9460d87c7
N3CROM4NC3R/python_crash_course_exercises
/dictionarys/cities.py
215
4.28125
4
cities = { "Valle de la Pascua" : "Venezuela", "New york" : "Unite States", "Atenas" : "Greek", "Tokyo" : "Japan" } for city,country in cities.items(): print("The city "+city+" is in "+country)
false
aa60328ddf11240a19c9aa1360b49ae37777aee9
shreya-trivedi/PythonLearn
/q03lenght.py
515
4.21875
4
#!/usr/bin/python3.5 ''' Problem Statement Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.) ''' import sys def get_lenght(word): ''' Function to get lenght of a string Args: word = The only parameter. Returns: count = lenght of string. ''' count = 0 for char in word: count += 1 return count print get_lenght(sys.argv[1])
true
43ea03ea1d693d03366841964a2808e64626c414
MihaiRr/Python
/lab11/Recursion.py
1,335
4.46875
4
# The main function that prints all # combinations of size r in arr[] of # size n. This function mainly uses # combinationUtil() def printCombination(arr, n, r): # A temporary array to store # all combination one by one data = [""] * r # Print all combination using # temprary array 'data[]' combinationUtil(arr, n, r, 0, data, 0) ''' arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] ''' def combinationUtil(arr, n, r, index, data, i): # Current cobination is ready, # print it if (index == r): for j in range(r): print(data[j], end = " ") print() return # When no more elements are # there to put in data[] if (i >= n): return # current is included, put # next at next location data[index] = arr[i] combinationUtil(arr, n, r, index + 1, data, i + 1) # current is excluded, replace it # with next (Note that i+1 is passed, # but index is not changed) combinationUtil(arr, n, r, index, data, i + 1)
true
86b6be121a3af8171cf502278d6a7cd974db0533
jshubh19/pythonapps
/bankaccount.py
2,486
4.15625
4
# bank account class BankAccount: ''' this is Janta ka Bank''' def __init__(self,accountname='BankAccount',balance=20000): #for making class method we use __init__ const self.accountname=accountname self.balance=baalance def deposite (self,value): self.balance=self.balance+value print('your balance is ',self.balance) def withdraw (self,value): self.balance=self.balance-value print('your balance is ',self.balance) class currentaccount(BankAccount): def __init__(self,accountname='currentaccount',balance=20000): self.accountname=accountname self.balance=balance def withdraw(self,value): if value>1000: print('you cant withdraw that amount') else: self.balance=self.balance-value print('your currentaccount balance is',self.balance) class savingaccount(BankAccount): def __init__(self,accountname='savingaccount',balance=20000): self.accountname=accountname self.balance=balance def deposite (self,value): self.balance=self.balance+value*0.3 print('your savingaccount balance is ',self.balance) oc=currentaccount() os=savingaccount() while True: print('1.currentaccount') print('2.savingaccount') main_menu=int(input('please select your option ')) if main_menu==1: print('1.deposite') print('2.withdraw') sub_menu=int(input('please choose your option ')) if sub_menu==1: value=int(input('enter the amount to deposite ')) oc.deposite(value) elif sub_menu==2: value=int(input('enter amount to withdraw ')) oc.withdraw(value) else: print('you just choosed invalid option ') elif main_menu==2: print('1.deposite') print('2.withdraw') sub_menu=int(input('please choose your option ')) if sub_menu==1: value=int(input('enter your amount for deposite ')) os.deposite(value) elif sub_menu==2: value=int(input('enter amount to withdraw ')) os.withdraw(value) else: print('you just choosed invalid option ') else: print('you choose invalid account type ') break
true
03db8cb0753c56ea69c9e69a1c30b8dc11212cad
rfc8367/R1
/L15/Task_3.py
1,028
4.1875
4
import re def password_patterns(): while True: user_password = input('Enter your password: ') length = len(user_password) print(f'Your password length {length}') if len(user_password) <= 8: print('Password must contain at least 8 characters') continue lowerRE = re.compile(r'[a-z]') if not (lowerRE.search(user_password)): print('Password must contain lower characters') continue upperRE = re.compile(r'[A-Z]') if not (upperRE.search(user_password)): print('Password must contain upper characters') continue numberRE = re.compile(r'[0-9]') if not (numberRE.search(user_password)): print('Password must contain numbers') continue symbolRE = re.compile(r'[$#@+=-]') if not (symbolRE.search(user_password)): print('Password must contain symbols') else: print('Password is strong') password_patterns()
false
6c562dadd0b180b5357b4ce57c73b440cb7c06a3
Mariam-Hemdan/ICS3U-Unit-4-01-Python
/while_loop.py
470
4.1875
4
#!/usr/bin/env python3 # Created by : Mariam Hemdan # Created on : October 2019 # This program uses while loop def main(): # this program uses While loop sum = 0 loop_counter = 0 # input positive_integer = int(input("Enter an integer: ")) print("") # process & output while loop_counter <= positive_integer: sum = sum + loop_counter print(sum) loop_counter = loop_counter + 1 if __name__ == "__main__": main()
true
78eebbec669e95bedd57fb74714c56a8a3705178
Pyabecedarian/Algorithms-and-Data-Structures-using-Python
/Stage_1/Task5_Sorting/bubble_sort.py
729
4.28125
4
""" Bubble Sort Compare adjacent items and exchange those are out of order. Each pass through the list places the next largest value in its proper place. If not exchanges during a pass, then the list has been sorted. [5, 1, 3, 2] ---- 1st pass ----> [1, 3, 2, 5] Complexity: O(n^2) """ def bubble_sort(alist: list) -> list: exchanges = True passnum = len(alist) - 1 while passnum > 0 and exchanges: exchanges = False for i in range(passnum): if alist[i] > alist[i + 1]: alist[i], alist[i + 1] = alist[i + 1], alist[i] exchanges = True return alist if __name__ == '__main__': a = [5, 1, 3, 2] print(bubble_sort(a))
true
5e3a27d7f44acfc40517e889015a6bc778855ade
EarthBeLost/Learning.Python
/Exercise 3: Numbers and Math.py
1,051
4.59375
5
# This is the 3rd exercise! # This is to demonstrate maths within Python. # This will print out the line "I will now count my chickens:" print "I will now count my chickens:" # These 2 lines will print out their lines and the result of the maths used. print "Hens", 25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 # This will print out the line "Now I will count the eggs:" print "Now I will count the eggs:" # This prints out the value of this calculation... print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # Just prints out the line in here. print "Is it true that 3 + 2 < 5 - 7?" # This prints out true. print 3 + 2 < 5 - 7 # These 2 lines prints out the strings and the result of the maths. print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 # Just prints out another line. print "Oh, that's why it's False." # Just prints out another line. print "How about some more." # This prints out True or False for these... go Boolean! print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
true
a3ee6737bc9880a213034cfc71ffd34b3f4d1215
JakeGads/Python-tests
/Prime.py
888
4.1875
4
""" Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you. Take this opportunity to practice using functions, described below. """ def main(): run = 1 while run == 1: run = 0 num = int(input("Please enter an integer (not 0,1,2) ")) i = 1 truth = 0 while i < num: tester = num % i if tester == 0: truth += 1 i += 1 if num == 2 or num == 1 or num == 0: print("%d is not a vaild input " % num) run = 1 else: if truth > 2: print("%d is not a prime number " % num) else: print("%d is a prime number " % num) main()
true
d546a4375fabc0e79a9d7668e12a7d9de2606cc1
Monukushwaha/Python_Practice-
/conditional27.py
215
4.125
4
#Python program to print alphabet pattern 'T'. for i in range(1,8): for j in range(1,8): if (i>1 and (j==1 or j==2 or j==4 or j==5)): print(" ", end="") elif(i<8 and j<=5): print("*", end="") print()
false
54c8d3a2094f4f575acd6ea4ecac7a4dc1746ec8
green-fox-academy/wenjing-liu
/week-01/day-03/data_structure.py/product_db_2.py
1,472
4.53125
5
product_db = { 'milk': 200, 'eggs': 200, 'fish': 400, 'apples': 150, 'bread': 50, 'chicken': 550 } def search_db(db): print('Which products cost less than 201?') smaller_keys = [] for key, value in product_db.items(): if value < 201: smaller_keys.append(key) if smaller_keys: print(f"The less than 201 products: { ', '.join(smaller_keys)}") else: print('Sorry, we don\'t have.') print('Which products cost more than 150?') bigger_keys = [] for key, value in product_db.items(): if value > 150: bigger_keys.append(key) if bigger_keys: for key in bigger_keys: print(f'{key} {product_db[key]}') else: print('Sorry, we don\'t have.') search_db(product_db) """ # Product database 2 We are going to represent our products in a map where the keys are strings representing the product's name and the values are numbers representing the product's price. - Create a map with the following key-value pairs. | Product name (key) | Price (value) | |:-------------------|:--------------| | Eggs | 200 | | Milk | 200 | | Fish | 400 | | Apples | 150 | | Bread | 50 | | Chicken | 550 | - Create an application which solves the following problems. - Which products cost less than 201? (just the name) - Which products cost more than 150? (name + price) """
true
c874fd86801315b98f608f9011a54ef8299a8b54
green-fox-academy/wenjing-liu
/week-01/day-05/matrix/matrix_rotation.py
952
4.1875
4
""" # Matrix rotation Create a program that can rotate a matrix by 90 degree. Extend your program to work with any multiplication of 90 degree. """ import math def rotate_matrix(matrix, degree): rotate_times = degree//90%4 print(rotate_times) for rotate_time in range(rotate_times): tmp_matrix = [] totalRowsOfRotatedMatrix = len(matrix) totalColsOfRotatedMatrix = len(matrix[0]) for i in range(totalColsOfRotatedMatrix): tmp_matrix.append([None]*totalRowsOfRotatedMatrix) for row_num in range(totalRowsOfRotatedMatrix): for col_num in range(totalColsOfRotatedMatrix): tmp_matrix[totalColsOfRotatedMatrix - 1 - col_num][row_num] = matrix[row_num][col_num] matrix, tmp_matrix = tmp_matrix, matrix return matrix matrix_x = [[12, 7, 3], [4, 5, 6]] print(rotate_matrix(matrix_x, 90)) print(rotate_matrix(matrix_x, 180)) print(rotate_matrix(matrix_x, 270)) print(rotate_matrix(matrix_x, 360))
true
75194eb550340de1c1ab9a31adc510fec7ef771b
green-fox-academy/wenjing-liu
/week-02/day-01/encapsulation-constructor/counter.py
947
4.125
4
class Counter: def __init__(self, num = 0): self.num = int(num) self._initial_num = self.num def add(self, number = 1): if isinstance(number, (int, float)): self.num += int(number) else: raise Exception('You must input number') def get(self): return self.num def reset(self): self.num = self._initial_num """ # Counter - Create `Counter` class - which has an integer field value - when creating it should have a default value 0 or we can specify it when creating - we can `add(number)` to this counter another whole number - or we can `add()` without parameters just increasing the counter's value by one - and we can `get()` the current value - also we can `reset()` the value to the initial value - Check if everything is working fine with the proper test - Download `test_counter.py` and place it next to your solution - Run the test file as a usual python program """
true
12c1001a8ec9759c913683af89a5f8db183d87a7
green-fox-academy/wenjing-liu
/week-02/day-02/decryption/reversed_order.py
510
4.15625
4
# Create a method that decrypts reversed-order.txt def decrypt(file_name, result_file_name): try: with open(file_name, 'r') as source_file: with open(result_file_name, 'a') as result_file: line_list = source_file.readlines() result_file.write(''.join(reverse_order(line_list))) except Exception as e: print(f'Error occurs when do decrypt {file_name}: {e}') def reverse_order(line_list): return line_list[::-1] decrypt('reversed_order.txt', 'reversed_order_result.txt')
true
6f8fa5537d1c905be5afa97b890f334fb16fcd43
green-fox-academy/wenjing-liu
/week-01/day-02/loops/guess_the_number.py
634
4.21875
4
# Write a program that stores a number, and the user has to figure it out. # The user can input guesses, after each guess the program would tell one # of the following: # # The stored number is higher # The stried number is lower # You found the number: 8 magic_num = 5 print('Guess the number!') is_found = False while not(is_found) : guess_num = float(input('Please input a number(press enter to stop enter):\n')) if guess_num > magic_num: print('The stored number is lower') elif guess_num < magic_num: print('The stored number is higher') else: print(f'You found the number: {magic_num}') is_found = True
true
01e271b2fd0fbdd4b16f96d6171e294982bd0674
green-fox-academy/wenjing-liu
/week-01/day-05/matrix/transposition.py
465
4.15625
4
""" # Transposition Create a program that calculates the transposition of a matrix. """ def transposition_matrix(matrix): result = [] for col_num in range(len(matrix[0])): result.append([None]*len(matrix)) print(result) for row_num in range(len(result)): for col_num in range(len(result[row_num])): result[row_num][col_num] = matrix[col_num][row_num] return result matrix_x = [[12, 7, 3], [4, 5, 6]] print(transposition_matrix(matrix_x))
true
29031610a8bc863cea296a89d3bc058715762bf3
green-fox-academy/wenjing-liu
/week-01/day-03/functions/bubble.py
575
4.34375
4
# Create a function that takes a list of numbers as parameter # Returns a list where the elements are sorted in ascending numerical order # Make a second boolean parameter, if it's `True` sort that list descending def bubble(arr): return sorted(arr) def advanced_bubble(arr, is_descending = False): sorted_arr = sorted(arr) if is_descending: sorted_arr.reverse() return sorted_arr # Example: print(bubble([43, 12, 24, 9, 5])) # should print [5, 9, 12, 24, 34] print(advanced_bubble([43, 12, 24, 9, 5], True)) # should print [34, 24, 9, 5]
true
6eeb0463f0b42acc6fde7d5b61449e790949897b
dylan-hanna/ICS3U-Unit-5-05-Python
/address.py
816
4.125
4
#!/usr/bin/env python3 # Created by: Dylan Hanna # Created on: Nov 2019 # This program accepts user address information def mailing(name_one, address_one, city_one, province_one, postal_code_one): print(name_one) print(address_one) print(city_one, province_one, postal_code_one) def main(): while True: name = input("Enter the name of the receiver: ") address = input("Enter the address: ") city = input("Enter the city: ") province = input("Enter the province: ") postal_code = input("Enter the postal code: ") print() try: mailing(name, address, city, province, postal_code) except ValueError: print("Invalid Input") continue else: break if __name__ == "__main__": main()
true
821ad576d77ac6c4c70c4dc1371750ab272a373c
ShelbyBhai/Mini-Projects-in-Python
/Encryption/EncryptedMessage.py
456
4.4375
4
print("Enter the Given Text & Shift Value : ") _input_string = input() _shift_Value = int(input()) print(_input_string, _shift_Value) encrypted_input_string = "" for char in _input_string: if char.isupper(): encrypted_input_string += chr((ord(char)+_shift_Value-65)%26+65) elif char.islower(): encrypted_input_string += chr((ord(char)+_shift_Value-97)%26+97) print("The encrypted message is now : " + encrypted_input_string)
false
870d8536737e98f5e09e6475cea90552b8ae1aaf
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 4 - Style and Structure/73-multi-line-strings.py
2,669
4.125
4
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 4. Style & Structure > Section 3: # Multi-line strings (1/2) ''' Sometimes we end up wanting to use very long strings, and this can cause some problems. If you run pycodestyle on this, you'll get the following message: some_script.py: E501 line too long For such reasons, the Python style guide recommends keeping all lines of code to a maximum of 79 characters in length—or even 72 characters, in some cases. ''' ''' EOL stands for End Of Line. And a key thing to understand is that this is actually a character in your code editor—it's just an invisible one. In some code editors, there's an option to make these visible. ''' story = "Once upon a time there was a very long string that was \ over 100 characters long and could not all fit on the \ screen at once." print('\n' + story) # It prints, but there are a bunch of extra spaces between some of the words. # One option would be to simply remove the indentation: story = "Once upon a time there was a very long string that was \ over 100 characters long and could not all fit on the \ screen at once." print('\n' + story) # This would work, but it makes the code harder to read. We need a better # solution. # Instead of the escape character, how about if we use triple quotes? story = """Once upon a time there was a very long string that was over 100 characters long and could not all fit on the screen at once.""" print('\n' + story) # It prints the string, but there are a bunch of extra spaces between some # of the words. ''' What if we try using multiple strings, and using the + operator to concatenate them? Like this:' story = "Once upon a time there was a very long string that was " + "over 100 characters long and could not all fit on the " + "screen at once." print(story) It throws the error Invalid syntax. ''' # What if we try both concatenation and the escape character? story = "Once upon a time there was a very long string that was " + \ "over 100 characters long and could not all fit on the " + \ "screen at once." print('\n' + story) # It prints the string perfectly. # Here's something rather different: story = ("Once upon a time there was a very long string that was " "over 100 characters long and could not all fit on the " "screen at once.") print('\n' + story) # It prints the string perfectly. ''' This should be a bit surprising. Why would this work? The reason is a combination of two lesser-known Python features: Implicit line-joining and automatic string-literal concatenation. '''
true
861a628085be4eea68e5e32c6cab55f2d0f36838
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 2 - Strings and Lists, Part 1/29-f-strings.py
1,068
4.3125
4
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 2. Strings & Lists Part 1 > Section 16: f-strings # Do it in the terminal: ''' f-strings is something that was added to Python in version 3.6— so in order for this to work on your own computer, you must be sure to have Python 3.6 or later. As a reminder, you can check which version you have by going to your terminal and entering: python3 --version ''' >>> import math >>> import math 3.141592653589793 >>> f"pi is about {math.pi:.6}" pi is about 3.14159 # This is because of ':.6' inside f-strings (formatted strings) ''' Suppose that we want to get the following string: 'The aardwolf eats termites.' ''' >>> animal = "aardwolf" >>> food = "termites" >>> "The " + animal + " eats " + food + "." # Works >>> animal = "aardwolf" >>> food = "termites" >>> "The {animal} eats {food}" # Doesn't work. >>> animal = "aardwolf" >>> food = "termites" >>> f"The " {animal} " eats " {food} "." # Doesn't work. >>> animal = "aardwolf" >>> food = "termites" >>> f"The {animal} eats {food}." # Works
true
8eafc4cab7035114ead9e844e3f5a57c3c489e01
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 2 - Strings and Lists, Part 1/24-slicing-word-triangle-exercise.py
977
4.1875
4
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 2. Strings & Lists Part 1 > Section 12: Slicing(1/2) ''' Exercise: Word triangle find a partially completed for loop. Goal is to finish the loop so that it prints out the following: d de def defi defin defini definit definite definitel definitely ''' # Approach 1 print('\nApproach 1:\n') word = "definitely" length = len(word) for n in range(length): print(word[0:n + 1]) # Approach 2 print('\nApproach 2:\n') new_word = '' for ch in 'definitely': new_word += ch print(new_word) ''' Each time through the loop, n gets larger. So [0:n] is a slice expression that will start from the beginning of the string (at the character with index 0) and go up until the character at index n. Since n is growing, the string that gets printed will also grow longer each time. Notice that we have to add + 1, because n starts at 0 and goes up to 9 (but we want it to start at 1 and go up to 10). '''
true
95e54eacc1da6c8c5b8724634c686b56b1ae1e41
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 3 - Strings and Lists, Part 2/43-mutable-vs-immutable.py
905
4.3125
4
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 3. Strings & Lists Part 2 > Section 3: # Mutable vs. immutable ''' List are mutable (can be modified) Strings are immutable (cannot be modified) ''' # Exercise 1 - Mutable print('\nExercise 1 - Mutable:\n') breakfast = ['toast', 'bacon', 'eggs'] print(breakfast) # ['toast', 'bacon', 'eggs'] print(breakfast[0]) # 'toast' breakfast[0] = 'spam' print(breakfast) # ['spam', 'bacon', 'eggs'] breakfast[1] = 'spam' print(breakfast) # ['spam', 'spam', 'eggs'] breakfast[2] = 'spam' print(breakfast) # ['spam', 'spam', 'spam'] # Exercise 2 - immutable print('\nExercise 2 - immutable:\n') breakfast = 'waffles' print(breakfast) new_breakfast = breakfast + ' and strawberries' print(new_breakfast) print(breakfast) breakfast = breakfast + ' and strawberries' print(breakfast) # but here the concatenated 'breakfast' is a new string.
true
f9ca6dad8f3dc6f8363fe1b8a49072604bb770ab
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 3 - Strings and Lists, Part 2/66-convert-string-into-list.py
800
4.5625
5
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 3. Strings & Lists Part 2 > Section 17: # Find and replace (1/2) # Convert a string into a list # Approach 1 (without using split method) def list_conversion(string): list = [] for index in string: list.append(index) return list string = input('Enter a string: ') print(' Approach 1: without using split method:') print('list converted:' + str(list_conversion(string))) # Approach 2 using split method # this can be used only when the string has a specific separator print(' Approach 2: using split method:') string1 = 'Going to the work' string2 = 'mangos, stawberry, pears' string3 = 'c-a-t' # so string.split() will not work print(string1.split(' ')) print(string2.split(',')) print(string3.split('-'))
true
46b0b93e3d86c6cc425459be309bd3bd15ed3d1c
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 2 - Strings and Lists, Part 1/19-range-function.py
1,245
4.71875
5
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 2. Strings & Lists Part 1 > Section 9: # The range function, revisited ''' Earlier, we used the range function with for loops. We saw that instead of using a list like this: ''' print() for side in [0, 1, 2, 3]: print(side) print() # Range can be used like below: for n in range(4): print(n) print() ''' So we can pass range up to three arguments. what the three range parameters do: 1. The first parameter is the number to start with. 2. The second parameter is the number to stop at (or rather, to stop before, since it's excluded). 3. The third parameter is the step size (i.e., how large a step to take when counting up). Notice that start and step are optional— if you leave either (or both) out, the function will just go with the defaults— a start of 0 and a step of 1. range(5) is same as range(0, 5, 1) range(0, 5) is same as range(0, 5, 1) range(4) is same as range(0, 4, 1) range(0, 4, 1) is same as range(0, 4, 1) range(2, 5) is same as range(2, 5, 1) ''' print() for n in range(5): print(n) print() for n in range(1, 4): print(n) print() for n in range(97, 101): print(n) print() for n in range(0, 10, 2): print(n) print()
true
9580691741d7e3c606279cd91512724f8c087993
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 3 - Strings and Lists, Part 2/56-break-exercise-no-repeating-words.py
686
4.21875
4
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 3. Strings & Lists Part 2 > Section 10: # Infinite loops and breaking out # Exercise - Repeated words: ''' Write an function to store the words input by the user and exit the while loop when a word is repeated. There's another way to exit from an infinite loop. Inside a while or for loop, you can use the break statement to immediately exit the loop . ''' def no_repeating(): words = [] while True: word = input("Tell me a word: ") if word in words: print("You told me that word already!") break words.append(word) return words print(no_repeating())
true
4e4ed96929cf2fe0808c10535714fb92c2f7e6e8
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 3 - Strings and Lists, Part 2/45-augmented-assignments.py
941
4.59375
5
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 3. Strings & Lists Part 2 > Section 4: # Augmented assignments # Try them on interpreter >>> n = 1 >>> n = n + 2 >>> n = 2 >>> n = n * 3 >>> n 6 >>> n = 5 >>> n = n / 2 >>> n 2.5 >>> n = 10 >>> n = n - 6 >>> n 4 >>> s = "Hello" >>> s = s + " world!" >>> s 'Hello world!' ''' The effect of n = n + 1 and n += 1 is the same. The latter is called an augmented assignment statement, because it's an assignment statement but it augments the existing value rather than replacing it. balloon = 5 balioon += 10 # causes NameError because balloon is misspelled, this can be avoided using augmented assignments ''' >>> n = 2 >>> n *= 3 >>> n 6 >>> n = 5 >>> n /= 2 >>> n 2.5 >>> n = 10 >>> n -= 6 >>> n 4 >>> s = "Hello" >>> s += " world!" >>> s 'Hello world!' >>> dog = "woof" >>> dog *= 2 'woofwoof' ''' balloon = 'abc' balioon += 1 # will cause TypeError '''
false
612dbf123309396abbe8755f327c1e0eed8d5303
divineBayuo/NumberGuessingGameWithPython
/Number_Guessing_GameExe.py
1,959
4.125
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 3 10:52:42 2021 @author: Divine """ #putting both programs together #importing required libs import tkinter as tk import random import math root = tk.Tk() canvas1 = tk.Canvas(root, width = 300, height = 300) canvas1.pack() #making the game code a function def NumberGuessingGame (): #take the inputs from the user lowerBound = int(input("Enter lower bound:- ")) #lower bound upperBound = int(input("Enter upper bound:- ")) #upper bound #generating random figure between the lower and upper bound x = random.randint(lowerBound,upperBound) print("\n\tYou have only chances ", round(math.log(upperBound-lowerBound+1,2)), "to guess the integer!\n") #initializing the number of guesses count = 0 #min number of guesses depends on the range given while count <= round(math.log(upperBound-lowerBound+1,2)): count = count + 1 #taking the player's guess guess = int(input("Guess the number:- ")) #test a condition if x == guess: print("\nCongratulations! You did it in ",count," tries.") #once the guess is correct, the loop will break break elif x > guess: print("\nGuessed too small!") elif x < guess: print("\nGuessed too high!") #if guessing is more than the required guesses, give the following if count > round(math.log(upperBound-lowerBound+1,2)): print("\nThe number is %d" %x) print("\tBetter luck next time!") button1 = tk.Button(text='Start!',command = NumberGuessingGame, bg='green', fg='white') canvas1.create_window(150,150,window=button1) #button2 = tk.Button(text='Play Again',command = NumberGuessingGame, bg='green', fg='white') #canvas1.create_window(150,150,window=button2) root.mainloop()
true
cca6ea9561c63a741e72107d537b70054a4220c2
goateater/MyCode
/learn_python/basic_string_operations.py
785
4.5
4
#!/usr/bin/env python bso = """ Basic String Operations ---------------------- Strings are bits of text. They can be defined as anything between quotes: As you can see, the first thing you learned was printing a simple sentence. This sentence was stored by Python as a string. However, instead of immediately printing strings out, we will explore the various things you can do to them. You can also use single quotes to assing a string. However, you will face problems if the value to be assigned itself contains single quotes.For example to assign the string in these bracket(single quotes are ' ') you need to use double quotes only like this. """ astring = "Hello World!" astring2 = 'Hello World!' print astring print astring2 print "single quotes are ' '" print len(astring)
true
78b6c9150a4804af6f60d62d040fc09c9f86d0a1
nfbarrett/CCIS-1505-02
/Session11/Test2-Q28.py
549
4.21875
4
blnDone = False # sets Boolean to false while blnDone == False: # checks Boolean is still false try: # repeats this until Boolean is true num = int(input( "Enter your age" )) # asks for number, converts input into integer blnDone = True # sets Boolean to true except (ValueError): # if input is not a number will error out. print ("invalid age entered, please re-enter!") # returns error line and keeps Boolean to false and repeats print ("Your age is", num) # once Boolean is true displays this line with the number
true
ba771d7f4f312d4276781c88642d7aae08baaf7d
nfbarrett/CCIS-1505-02
/Session11/Test2-Q27.py
837
4.46875
4
def maximumValue( x, y, z ): # calls the function for maximumvalue maximum = x # if position 1 is max this will be displayed if y > maximum: # checks if position 2 is larger that position 1 maximum = y # if position 2 is larger, position 2 will be displayed if z > maximum: # checks if position 3 is larger that position 1 maximum = z # if position 3 is larger, position 3 will be displayed return maximum # displays the largest number ####Mainline#### # seperation of functions and the program a = int(input( "Enter first integer: " ) ) # asks for 1st number b = int(input( "Enter second integer: " ) ) # asks for 2nd number c = int(input( "Enter third integer: " ) ) # asks for 3rd number print ("Maximum integer is:", maximumValue( a, b, c )) # calls function maximumValue and displays the result
true
dfc321e797972f83c637e08ca943ffa9568a3496
nfbarrett/CCIS-1505-02
/Session06/p6.py
1,733
4.1875
4
# Programer: Nick Barrett # Date Written: Oct 01, 2019 # Program Name: P6.py # Company Name: HTC-CCIS1505 #step 1 print("Step 1") lstWeekDays = [] int_Counter=0 while int_Counter <= 6: strWeekDay = input("Enter day of the week: ") int_Counter += 1 # count up by 1 strWeekDay = strWeekDay.title() lstWeekDays.append(strWeekDay) print() print() #step 2 ##lstWeekDays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] print("Step 2") for lstWeek in lstWeekDays: print(lstWeek) print() print() #step 3 print("Step 3") ##lstWeekDays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] lstWeekDays.reverse() for lstRev in lstWeekDays: print(lstRev) print() print() #step 4 print("Step 4") ##lstWeekDays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] lstWeekDays.sort() for lstSort in lstWeekDays: print(lstSort) print() print() #step 5 print("Step 5") for strDay in lstWeekDays: print(strDay,"=",strDay[0:3]) print() print() #step 6 print("Step 6") for strDay in lstWeekDays: if "T" in strDay[0]: print(strDay) print() print() #step 7 print("Step 7") dctCourses = { 1000:"Intro to IS", 1301:"HTML & CSS", 1505:"Fundamentals of Programming", 2575:".NET Programming 1", 2585:".NET Programming 2", 2701:"Database Design & SQL"} print(dctCourses) print() print() #step 8 print("Step 8") lstKeys=dctCourses.keys() for strKey in lstKeys: print(strKey) print(lstKeys) print() print() #step 9 print("Step 9") lstValues=dctCourses.values() for strValue in lstValues: print(strValue) print() print() #step 10 print("Step 10") strName = dctCourses[1505] print(strName)
false
15b5733f80fddc8c8a22522ae0653f1de90546bf
liujiantao007/Perform-Object-Detection-With-YOLOv3-in-Keras
/Draw_rectangle/single_rectangle_cv2.py
911
4.3125
4
# Python program to explain cv2.rectangle() method # importing cv2 import cv2 from matplotlib import pyplot as plt path ='2.jpg' # Reading an image in default mode image = cv2.imread(path) # Window name in which image is displayed window_name = 'Image' # Start coordinate, here (5, 5) # represents the top left corner of rectangle """ <bndbox> <xmin>216</xmin> <ymin>359</ymin> <xmax>316</xmax> <ymax>464</ymax> </bndbox> """ start_point = (216,359) # Ending coordinate, here (220, 220) # represents the bottom right corner of rectangle end_point = (316,464) # Blue color in BGR color = (255, 0, 0) # Line thickness of 2 px thickness = 2 # Using cv2.rectangle() method # Draw a rectangle with blue line borders of thickness of 2 px image = cv2.rectangle(image, start_point, end_point, color, thickness) cv2.imwrite('r.jpg',image) # Displaying the image plt.imshow(image)
true
5d9b8983b5652dc449658873bfd8b237fdc57b64
jsheridanwells/Python-Intro
/7_dates.py
955
4.375
4
# # Example file for working with date information # from datetime import date from datetime import time from datetime import datetime # imports standard modules def main(): ## DATE OBJECTS # Get today's date from the simple today() method from the date class today = date.today() print('la fecha es ', today) # print out the date's individual components print('components::', today.month, today.day, today.year) # retrieve today's weekday (0=Monday, 6=Sunday) days = [ 'monda', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ] print('today\'s weekday number is', today.weekday()) # => 6 print('which is', days[today.weekday()]) ## DATETIME OBJECTS # Get today's date from the datetime class currentDate = datetime.now() print(currentDate) # Get the current time time = datetime.time(currentDate) print('la hora es', time) if __name__ == "__main__": main();
true
a1a92e7de2c597aaa4d1a6443bc2354216c9f1f5
pavan1126/python-1-09
/L3 8-09 Reverse order.py
379
4.25
4
#copying elements from one array to another array in reverse order a=[1,2,3,4,5] b=[None]*len(a) length=len(a) #logic starts here for i in range(0,length): b[i]=a[length-i-1] #printing output print("the elements of first array is") for i in range(0,length): print(a[i]) print("the elements of reversed array is",b) for i in range(0,len(b)): print(b[i])
true
48784ce85ac8a8ce79dd42790846e894523904cf
eessm01/100-days-of-code
/e_bahit/wrappers_decorators.py
1,341
4.53125
5
"""The Original Hacker. N.4. Wrappers y Decoradores. Closure. Es una función que dentro de ella contiene a otra función la cual es retornada cuando el closure es invocado. DECORADOR. Es aquel closure que cómo parámetro recibe una función (llamada función "decorada") cómo único argumento. WRAPPER. No es más que la función interna de un closure que a la vez sea de tipo decorador. LA FUNCION DECORADA deberá ser INVOCADA por el wrapper El decorador no se invoca como una función normal. Éste es llamado con una sintaxis especial: @decorador La sintaxis anterior se debe colocar en la línea anterior a la definición de la función decorada. De esta forma, el nombre de la función decorada es pasado como parámetro de forma automática sin tener que invocar nada más """ def closure(parametro1): def funcion(parametro2): print(parametro1 + parametro2) return funcion foo = closure(10) foo(200) # imprime 210 foo(500) # imprime 510 def decorador(funcion_decorada): def funcion(): pass return funcion def decorador2(funcion_decorada): def wrapper(): pass return wrapper def decorador3(fucion_decorada): def wrapper(): return fucion_decorada() return wrapper @decorador3 def funcion_decorada(): print("Soy una función decorada")
false
dd9f0ef34231d01242086ef70453cb401ef37a77
eessm01/100-days-of-code
/platzi_OOP_python/bubble_sort.py
567
4.125
4
from random import randint def bubble_sort(one_list): n = len(one_list) limit = n - 1 for i in range(n): for j in range(limit): if one_list[j] > one_list[j+1]: one_list[j], one_list[j+1] = one_list[j+1], one_list[j] limit -= 1 return one_list if __name__ == "__main__": size = int(input('De que tamaño será la lista: ')) my_list = [randint(0, 100) for i in range(size)] # my_list = [5, 3, 11, 2, 1] print(my_list) ordered_list = bubble_sort(my_list) print(ordered_list)
false
84eb0afd3ad225fc0e23eb56292b845ed1d4e4ec
eessm01/100-days-of-code
/python_for_everybody_p3/files_exercise1.py
348
4.375
4
"""Python for everybody. Exercise 1: Write a program to read through a file and print the contents of the file (line by line) all in upper case. Executing the program will look as follows: """ fname = input('Enter a file name: ') try: fhand = open(fname) except: print('File not found') exit() for line in fhand: print(line)
true
c2516b677840cbb77294f74049e04bed243b559c
eessm01/100-days-of-code
/platzi_comp_thinking/dictionaries.py
600
4.21875
4
my_dict = { 'David': 35, 'Erika': 32, 'Jaime': 50 } print(my_dict) valor = my_dict.get('Juan', 99) print(valor) valor = my_dict.get('Jaime', 30) print(valor) my_dict['Jaime'] = 20 print(my_dict) my_dict['Pedro'] = 42 print(my_dict) del my_dict['Jaime'] print(my_dict) for llave in my_dict.keys(): print(llave) for valor in my_dict.values(): print(valor) for llave, valor in my_dict.items(): print(llave, valor) esta = 'David' in my_dict print(esta) esta = 'Tom' in my_dict print(esta) # comprehension other_dict = {x: x**2 for x in (2, 4, 6)} print(other_dict)
false
b01c74c82073bf2a8cfdbbba7ac08bfd433a4560
eessm01/100-days-of-code
/platzi_OOP_python/insertion_sort.py
799
4.21875
4
from random import randint def insertion_sort(one_list): # iterate over one_list from 1 to list's length for i in range(1, len(one_list)): current_element = one_list[i] # iterate over all elements in the left side (from i-1 to 0) for j in range(i-1,-1,-1): # compare current element whith each left element if current_element < one_list[j]: # if current_element is smaller, then swap one_list[j+1] = one_list[j] one_list[j] = current_element return one_list if __name__ == "__main__": size = int(input('De que tamaño será la lista: ')) my_list = [randint(0, 100) for i in range(size)] print(my_list) ordered_list = insertion_sort(my_list) print(ordered_list)
true
3869deac3ad24925a63d2cdaeb4db9431e08a8af
eessm01/100-days-of-code
/real_python/day10_11_dear_pythonic_santa_claus.py
1,732
4.28125
4
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """ Exercises from https://realpython.com/python-thinking-recursively/ The algorithm for interative present delivery implemented in Python Now that we have some intuition about recursion, let's introduce the formal definition of a recursive function. A recursive function is a function defined in terms of itself via self-referencial expressions. This means that the function will continue to call itself and repeat its behavior until some condition is met to return a result. All recursive functions share a common structure made up of two parts: 1. base case 2. recursive case. """ houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"] def deliver_presents_iteratively(): for house in houses: print("Delivering present to", house) # deliver_presents_iteratively() # Each function call represents an elf doing his work def deliver_presents_elves_iteratively(houses): # Worker elf doing his work if len(houses) == 1: house = houses[0] print("Delivering presents to", house) # Manager elf doing his work else: mid = len(houses) // 2 first_half = houses[:mid] second_half = houses[mid:] # Divides his work among two elves deliver_presents_elves_iteratively(first_half) deliver_presents_elves_iteratively(second_half) deliver_presents_elves_iteratively(houses) # Recursive function for calculating n! implemented in Python def factorial_recursive(n): #Base case: 1! = 1 if n == 1: return 1 # Recursive case: n! = n * (n-1)! else: return n * factorial_recursive(n-1) factorial = factorial_recursive(8) print(factorial)
true
a856343bc217c4d0e4e6b4fce3212d587cef5e38
eessm01/100-days-of-code
/project_euler/5_smallest_multiple.py
592
4.21875
4
def get_smallest_multiple(max_divisor): is_find = False initial_smallest_number = 2520 while not is_find: for i in range(max_divisor, 1, -1): if initial_smallest_number % i > 0: break else: if i == 2: is_find = True return initial_smallest_number initial_smallest_number += 1 if __name__ == '__main__': max_divisor = int(input('Ingrese el número máximo:')) initial_smallest_number = get_smallest_multiple(max_divisor) print(initial_smallest_number)
false
c2cde7223eafaf4d2c98b3bdef23a6653511f93e
BitPunchZ/Leetcode-in-python-50-Algorithms-Coding-Interview-Questions
/Algorithms and data structures implementation/binary search/index.py
678
4.34375
4
def binarySearch(arr, target): left = 0 right = len(arr)-1 while left <= right: mid = (left+right)//2 # Check if x is present at mid if arr[mid] == target: return mid # If x is greater, ignore left half elif arr[mid] < target: left = mid + 1 # If x is smaller, ignore right half else: right = mid - 1 # If we reach here, then the element was not present return -1 arr = [1, 2, 3, 4, 5, 6] target = 6 result = binarySearch(arr, target) if result != -1: print("Element is present at index %d" % result) else: print("Element is not present in array")
true
2ed7c2c6e4649e464527da216f9c51a6bca47ac1
MaxFallishe/Python__web
/Basic_python/Дз1/Dz1_2.py
564
4.125
4
import math a = int(input("Введите число a:" )) b = int (input("Введите число b:")) c = int (input("Введите число c:")) D = b ** 2 - 4 * a * c print(D) if D < 0: print("Корней нет") elif D == 0: x = -b / 2 * a print ("Корень = ",x) else: x1 = (-b + math.sqrt(D)) / (2 * a) x2 = (-b - math.sqrt(D)) / (2 * a) print("Первый корень: ",x1) print("Второй корень: ",x2) #Пришлось использовать модуль 'math' и возведение в степень '**'
false
efd43f194e740f108d25a1a7a8e3fce39e208d5a
DhananjayNarayan/Programming-in-Python
/Google IT Automation with Python/01. Crash Course on Python/GuestList.py
815
4.5
4
""" The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the sentence "Guest is X years old and works as __." for each one. For example, guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")) should print out: Ken is 30 years old and works as Chef. Pat is 35 years old and works as Lawyer. Amanda is 25 years old and works as Engineer. """ def guest_list(guests): for guest in guests: name,age,profession=guest print(f"{name} is {age} years old and works as {profession}") guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")]) """ Output should match: Ken is 30 years old and works as Chef Pat is 35 years old and works as Lawyer Amanda is 25 years old and works as Engineer """
true
1bf31d944d5650e5c3c2bd35a75dbef782f24ec7
ReDi-school-Berlin/lesson-6-exercises
/6-dictionaries/dictionaries.py
1,298
4.5
4
# What are some differences between dictionaries and lists? # dict is not indexable # lists are ordered and dictionaries aren't # dictionaries cannot have duplicate keys # -------------------- # How to create an empty dictionary person = {} # -------------------- # add values for this person, like name, phone, email, address etc in the dictionary person["name"] = "Harika" person["phone"] = 125384804 person["address"] = "Berlin" # -------------------- # Check if the dictionary has a key that doesn't exist (id) print("id" in person) print("phone" in person) # ---------------- # get person's phone. Hint: there are two ways # print(person["phone"]) # print(person.get("phone")) # print(person["id"]) print(person.get("id")) # ---------------- # Get all the keys of this person dictionary print(person.keys()) # ---------------- # Get all the values of this person dictionary print(person.values()) # ---------------- # Change person's address person["address"] = "Istanbul" print(person) # ---------------- # Remove person's phone Hint: two ways to do it (pop/del) # person.pop("phone") del person["phone"] print(person) person.clear() print(person) # Find more info about python dictionaries here -> https://www.w3schools.com/python/python_dictionaries.asp
true
9dc5d49761e60130666eb29c350de8612300e18e
Scimitarr/Python-scripts
/lab2.py
1,630
4.125
4
print("------------ZADANIE-1--------------------") initialCapital = 20000 percent = 0.03 maxTimeYears = 10 year = 1 capital = initialCapital while year <= maxTimeYears: capital = capital * (1+percent) print("Capital at the end of %d year is %d" % (year, capital)) year += 1 print("Through %d years You earned %d" % (maxTimeYears, capital - initialCapital)) print("\n------------------ZADANIE-2---------------") number = 20730906 print(number) sumaCyfr = 0 iloscZnakow = len(str(number)) x = number i = 1 while i <= iloscZnakow: sumaCyfr = sumaCyfr + x % 10 x = x // 10 i += 1 print("Suma cyfr liczby %d wynosi %d" % (number, sumaCyfr)) print("\n------------------ZADANIE-3---------------") text = "United Space Alliance: This company provides major support to NASA for various projects, such as the space shuttle. One of its projects is to create Workflow Automation System (WAS), an application designed to manage NASA and other third-party projects. The setup uses a central Oracle database as a repository for information. Python was chosen over languages such as Java and C++ because it provides dynamic typing and pseudo-code–like syntax and it has an interpreter. The result is that the application is developed faster, and unit testing each piece is easier." print(text) wordLength = 6 listOfWords = text.split(" ") shortWords = 0 longWords = 0 for word in listOfWords: if len(word) > wordLength: longWords += 1 else: shortWords += 1 print("Ilosc slow dluzszych niz 6: %d, a krotszych lub rownych 6: %d" % (longWords, shortWords))
false
9a27ab3cacd389a2bd69066a4241542185256072
tomdefeo/Self_Taught_Examples
/python_ex284.py
419
4.3125
4
# I changed the variable in this example from # 
text in older versions of the book to t
 # so the example fits on smaller devices. If you have an older # version of the book, you can email me at cory@theselftaughtprogrammer.io
 # and I will send you the newest version. Thank you so much for purchasing my book! import re t = "__one__ __two__ __three__" results = re.findall("__.*?__", t) for match in results: print(match)
true
d6c7cd46e60e6aa74cdd28de4f94aa45a65eb861
GarrisonParrish/binary-calculator
/decimal_conversions.py
1,823
4.1875
4
"""Handle conversions from decimal (as integer/float) to other forms.""" # NOTE: A lot of this code is just plain bad def dec_to_bin(dec: int, N: int = 32): """Converts decimal integer to N-bit unsigned binary as a list. N defaults to 32 bits.""" # take dec, use algorithm to display as a string of 1's and 0's in 16-bit binary # 0. Check if the decimal value exceeds the maximum alotted space (whatever that is) # 1. Make an array of size N with all ints 0 # 2. Starting from leftmost bit (index bits-1): # 3. bit = dec % 2 # 4. dec = dec / 2 # 5. repeat # 6. If you run out of space early, terminate looping and leave the rest as 0 if (dec > ( 2**N + ( 2**N - 1))): print(f"Cannot represent { dec } in { N } bits.") return "" # NOTE: Now we will have to be able to handle a null string. # Either this or we will have to throw an exception instead. bits: int[N] = [0] * N # initializes list with N number of 0's # bits are either 1 or 0. Will read these into a string afterwards. dec_copy: int = dec i: int = N-1 while dec_copy > 0: bits[i] = dec_copy % 2 dec_copy = dec_copy // 2 # floor division i -= 1 return bits def dec_to_ones_compl(dec): """Converts a decimal to signed ones complement.""" # NOTE: this one is broken # If dec is negative (below 0): # Take absolute value # Convert to unsigned magnitude binary # Convert to ones complement with neg = True # If dec is positive: # Convert to unsigned magnitude binary # Convert to ones complement with neg = False (changes nothing) neg: bool = False if dec < 0: neg = True dec = abs(dec) # return bin_to_ones_compl(dec_to_bin(dec, 8), neg) return 0
true
f0d5e4afb2071cdcba9d49f6925a597a466ad245
EroshenkoD/BBP_Python_hillel
/lesson_12/task_2.py
624
4.21875
4
""" 2. Имеется строка вида: AABABBAABBBAB. Необходимо написать функцию которая заменит буквы A на B, а B, соответственно, на A. Замену можно производить ТОЛЬКО используя функцию replace(). В результате применения функции к исходной строке, функция должна вернуть строку: BBABAABBAAABA """ s = 'AABABBAABBBAB' def replace_A_and_B(stroka): return stroka.replace('A', 'b').replace('B', 'a').upper() print(replace_A_and_B(s))
false
2726d03db151046c1091b93d14a5593c2d368e52
vrillusions/python-snippets
/ip2int/ip2int_py3.py
963
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Asks for an IPv4 address and convert to integer. In Python v3.3 the ipaddress module was added so this is much simpler """ import sys import ipaddress __version__ = '0.1.0-dev' def main(argv=None): """The main function. :param list argv: List of arguments passed to command line. Default is None, which then will translate to having it set to sys.argv. :return: Optionally returns a numeric exit code. If not given then will default to 0. :rtype: int """ if argv is None: argv = sys.argv if argv[1]: ip_address = argv[1] else: ip_address = input("Enter an ipv4 dotted quad or decimal: ") if ip_address.isdigit(): # Received a decimal, convert to ip print(str(ipaddress.ip_address(int(ip_address)))) else: print(int(ipaddress.ip_address(ip_address))) if __name__ == "__main__": sys.exit(main())
true
30d6d86bbcdcfee563d26985ccfaae90c8480397
Splufic-Automation-Systems-Ltd/Python-Training-Online-Cohort-One
/Week Three/Day 2/temp.py
340
4.375
4
import math # a python program that converts temperature from Farenheit to Celcius # get the user input fahrenheit = input('Enter the temperature in degrees Fahrenheit: ') # calculate the result result = (5/9 * (int(fahrenheit) - 32)) result = math.trunc(result) # print the result print(f'The temperature in degrees Celsius is {result}')
true
d1d792d85b93fcb95cfc3183cf05541dd8579d84
rotus/the-python-bible
/tuple_examples.py
248
4.125
4
# Tuples, like lists, hold values - Except tuple data CANNOT be changed # Useful for storing data/values that never need updated or modified our_tuple = (1,2,3,"a","b") print(our_tuple) # Pull data out of individual elements print(our_tuple[3])
true
9cf228ee2b0cd2fa8899ce07b5ccc5738d729e92
rotus/the-python-bible
/dictionary_basics.py
394
4.5625
5
# Used to store values with "keys" and then can retreive values based on those keys students = {"Alice":25, "Bob":27, "Claire":17, "Dan":21, "Emma":25} print(students) # extract Dan's value from dict print(students["Dan"]) # Update Alice's age print(students["Alice"]) students["Alice"] = 26 print(students["Alice"]) print(students.items()) print(students.keys()) print(students.values())
true