blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
701af849fc555f9c802f3d3f60c16569455d8bd6
Vantom16/security_system
/security.py
1,058
4.21875
4
#Creating our Security System # Code output is displayed in command line #First we create a list of known users known_users = ["Alice", "Jane", "David", "Paul", "Eli", "Isme"] while True: print("Hi! My name is Joe") name =input("What is your name?: ").strip().capitalize() #Computer will compare name given and ones in our database. if name in known_users: print("Hello {}".format(name)) # If our users wants to be removed from the system remove = input("Would you like to be removed from the system (y/n)?").strip().lower() if remove == "y": known_users.remove(name) elif remove == "n": print("No problem. I didn't want you to leave anyway! ") else: print("Hmmm I don't think I have met you yet {}".format(name)) add_me =input("Would you like to be added to our system (y/n)?: ").strip().lower() if add_me == "y": known_users.append(name) elif add_me == "n": print("No worries. See you around!")
true
031291a9602fdc584e02649768b0ef0d9fa3d1c4
valievav/Python_programs
/Practice_exercises/training/mini_tasks.py
2,730
4.1875
4
# Related read # https://realpython.com/python-coding-interview-tips/#select-the-right-built-in-function-for-the-job # https://docs.python.org/3/library/functions.html#built-in-functions section_sep = '' # EVEN numbers x = [11,1,3,4,5,6,8,9,10,1,3] even_only = [i for i in x if i %2==0] print(even_only) print(section_sep) ################################## # get COUNT of particular element in list one_cnt = x.count(1) print(one_cnt) # get COUNT of ALL elements in a list list_elem_cnt = {i: x.count(i) for i in x} print(list_elem_cnt, type(list_elem_cnt)) # COUNT number of each letter in a word from collections import Counter word = "tomatoes, potatoes, brokkoli" print({i: word.count(i) for i in word}) print(Counter(word)) # COUNT words in sentence sentence = "It was a really great trip" print(len(sentence.split())) print(section_sep) ################################### # FIND DUPES in array from collections import Counter dupes = [k for k, v in Counter(x).items() if v > 1] print(dupes) dupes = [k for k, v in list_elem_cnt.items() if v > 1] print(dupes) # REMOVE DUPES deduped = list(set(x)) print(deduped) # REMOVE DUPES option for ordered list print(list(dict.fromkeys(x))) print(section_sep) ##################################### # SORT list char = ['d', 'K', 'd', 'c', 'a'] char.sort(key=str.lower) # in-place print(char) print(sorted(char, key=str.lower)) # copy and sort print(section_sep) ##################################### # REVERSE list order with slicing l = [1,2,3,4,5,6,7] print(l[::-1]) # REVERSE list order with reverse iter print(list(reversed(l))) # REVERSE list order with reverse method l.reverse() print(l, ) print(section_sep) ###################################### # get LENGTH for each element in a list words = ['asd', 'zxcvb', 'a', 'qwerty'] print(list(map(len, words))) print(section_sep) ####################################### # UPDATE each element of a list to upper print(list(map(lambda x: x.upper(), words))) # ADD 2 lists x1 = [1,2,3,4,5] x2 = [6,7,8,9,10] print(list(map(lambda x,y: x+y, x1, x2))) print(section_sep) ####################################### # get EVERY 2nd element in a list x = [1,2,3,4,5,6] print(x[::2]) print(section_sep) print(section_sep) #################################### # Generate every possible COMBINATION between elements of a list (order doesn't matter) import itertools people = ['Mary', 'Jake', 'Sandy', 'Becca', 'Robin'] print(list(itertools.combinations(people, r=4))) print(section_sep) ################################## # Generate every possible PERMUTATIONS between elements of a list (order does matter) print(list(itertools.permutations(people, r=2))) print(section_sep) ##################################
true
9717caa2c2fccc161cd400a18bad6574237374be
valievav/Python_programs
/Practice_exercises/reverse_word_order.py
917
4.375
4
# https://www.practicepython.org/exercise/2014/05/21/15-reverse-word-order.html # Write a program that asks the user for a long string containing multiple words. # Print back to the user the same string, except with the words in backwards order. # For example 'My name is Michele' -> 'Michele is name My' def reverse_with_reverse_method(sentence: str) -> str: words = sentence.split() words.reverse() return ' '.join(words) def reverse_with_slicing(sentence: str) -> str: words = sentence.split() return ' '.join(words[::-1]) # [start: end: step] def reverse_with_reversed_iterator(sentence: str) -> str: words = sentence.split() return ' '.join(list(reversed(words))) # yields elements user_input = input('Please enter a sentence.\n') solutions = [ reverse_with_reverse_method, reverse_with_slicing, reverse_with_reversed_iterator, ] print(solutions[0](user_input))
true
893b5f5f5268d728a7b3474e0289bcd57961e512
adonis-lau/Python3Demo
/bid/adonis/lau/one/def.py
2,743
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x > 0: return x else: return -x print(my_abs(-99)) a = abs print(a(-88)) # 如果什么也不想坐,可以使用pass def my_pass(): pass import math # 函数返回多个值 def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny x, y = move(100, 100, 60, math.pi / 6) print(x, y) print(math.pi) r = move(100, 100, 60, math.pi / 6) print(r) # 计算x的n次方 def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s print(power(5, 2)) print(power(5)) # 默认参数带来的坑 def add_end(L=[]): L.append('END') return L # 正常调用 print(add_end([1, 2, 3])) # 非正常调用 print(add_end()) print(add_end()) print(add_end()) # Python函数在定义的时候,默认参数L的值就被计算出来了,即[],因为默认参数L也是一个变量,它指向对象[], # 每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。 # 所以,定义默认参数要牢记一点:默认参数必须指向不变对象! # 要修改上面的例子,我们可以用None这个不变对象来实现: def add_end(L=None): if L is None: L = [] L.append('END') return L # 正常调用 print(add_end([1, 2, 3])) # 非正常调用 print(add_end()) print(add_end()) print(add_end()) # 不可变参数 def cacl(number): sum = 0 for n in number: sum = sum + n * n return sum # 不可变参数的函数调用,多参数需要先组装list或者是tuple print(cacl([1, 2, 3])) print(cacl((1, 2, 3, 4))) # 可变参数 def cacl(*number): sum = 0 for n in number: sum = sum + n * n return sum # 可变参数调用 print(cacl(1, 2, 3)) print(cacl(1, 2, 3, 4)) # 如果已经有了list或者是tuple nums = [1, 2, 3, 4] print(cacl(nums[0], nums[1], nums[2])) print(cacl(*nums)) # 关键字参数 def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) # 关键字参数调用 person('adonis', 22) person('adonis', 22, city='Shanghai', job='coder') # 如果已有dict extra = {'city': 'city', 'job': 'job'} person('name', '11', **extra) # 命名关键字参数 # 如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city和job作为关键字参数。这种方式定义的函数如下: def person(name, age, *, city, job): print(name, age, city, job) person('adonis', 22, city='Shanghai', job='Coder')
false
70808716d0d3ae632945a34ffc58c57326666ce6
tmetz/ITP195
/notes/ch4.py
2,233
4.1875
4
import math import string #my_utf = ord("h") # Returns integer (ordinal) UTF-8 value of char #my_utf_ch = chr(121) # Returns UTF-8 char #print(my_utf, my_utf_ch) my_str = "This is a test of a string" #print(my_str[:8]) # Print from beginning to 7th char. Does not print the 8th character!!! # Extended slicing: # [start:finish:countBy] #print(my_str[0:11:2]) # prints every other letter (count by 2) # reversing a string: reverse_my_str = my_str[::-1] #print(reverse_my_str) #print(my_str*5) #print(my_str.upper().find('S')) # chaining #my_str = my_str.upper() #print(my_str) # print("TEST" in my_str) # print(len(my_str)) # print(my_str.find('T')) # Assume start looking from 0 # print(my_str.find('T',11)) # Start looking from character 11 # # # Nested methods: # print(my_str.find('T', my_str.find('T')+1)) # Find the second 'T' #print("This is a {:_>15} test of {}".format("not", "something cool.")) # for i in range(5): # print("{:10d} --> {:4d}".format(i,i**2)) # # print("Pi is {:.10f}".format(math.pi)) # pi to 10 decimal places # river = "Mississippi" # target = input("Input a character to find: ") # for index in range(len(river)): # if river[index].lower() == target.lower(): # print("Letter \"{}\" found at index: {}".format(target, index)) # break # else: # print("Letter \"{}\" not found in \"{}\"".format(target, river)) # river = "Mississippi" # target = input("Input a character to find: ") # for index,letter in enumerate(river): # if letter.lower() == target.lower(): # print("Letter \"{}\" found at index: {}".format(target, index)) # break # else: # print("Letter \"{}\" not found in \"{}\"".format(target, river)) new_str = "This is a test string to split" new_list = new_str.split(" ") print(new_list) name_str = "Tamara Leah Metz" first_name, middle_name, last_name = name_str.split(" ") print(middle_name) pal_str = "Madam, I'm Adam" modified_str = pal_str.lower() bad_chars = string.whitespace + string.punctuation for char in modified_str: if char in bad_chars: modified_str = modified_str.replace(char,"") if modified_str == modified_str[::-1]: print(\ "The original string is {}\n") # Need to finish copying this!!!!!
true
28b8a10bc86eb1393dfb88d0d0192c4c4a2a2e18
tmetz/ITP195
/Homework/stack.py
1,332
4.25
4
""" Tammy Metz ITP 195 - Topics In Python HW 4 - due April 9, 2018 Create a python module called "stack" that has methods for popping, pushing, and returning the top of the stack """ class Stack(object): def __init__(self, stack_as_list): self.stack = stack_as_list def is_empty(self): if len(self.stack) == 0: return True else: return False def top(self): return self.stack[-1] def push(self, item_to_add): self.stack.append(item_to_add) def pop(self): popped_item = self.stack.pop() return (popped_item) def __str__(self): return_string = "" self.stack.reverse() # Reversing order so we can print FILO order for item in self.stack: return_string = return_string + str(item) + "\n" self.stack.reverse() # Put it back in order return(return_string) def main(): list1 = [9, "Bob", 5.8] stack1 = Stack(list1) for i in range(10): stack1.push("Extra item "+str(i)) print("") print("The top of the stack is {} \n".format(stack1.top())) print("Printing the stack object: ") print(stack1) print("Popping items....") while not stack1.is_empty(): print("Popping {}".format(stack1.pop())) if __name__ == "__main__": main()
true
ed02008cb439f9c84cbbc1aa022fa87f9465e1e4
Spookyturbo/PythonCourse
/Week2/Lab3/guessNumber-ariedlinger.py
855
4.28125
4
#Guess My Number #Andrew Riedlinger #January 24th, 2019 # #The computer picks a random number between 1 and 100 #The player tries to guess it and the computer lets #the player know if the guess is too high, too low #or right on the money import random print("\tWelcome to 'Guess My Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") #set the initial values theNumber = random.randint(1, 100) guess = int(input("Take a guess: ")) tries = 1 #guessing loop while(guess != theNumber): if(guess > theNumber): print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 #Congratulations print("You guessd it! The number was", theNumber) print("And it only took you", tries, "tries!\n") input("\n\nPress the enter key to exit.")
true
6072136ab86ea5de52eaaf5ae8c75e2af47f3d20
tgoel5884/twoc-python
/Day6/Program5.py
605
4.1875
4
import math def isPerfectSquare(x): s = int(math.sqrt(x)) if s*s == x: return True def isFibonacci(n): # n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both return isPerfectSquare(5 * (n*n) + 4) or isPerfectSquare(5 * (n*n) - 4) n = int(input("Enter length: ")) arr = [] for i in range(n): d = int(input("Enter element : ")) arr.append(d) sum1=0 for i in range(n): sum1=sum1+arr[i] if isFibonacci(sum1) == True: print("Sum is a fibonacci number") else: print("Sum is not a fibonacci number") # This code is contributed by Tanmay Goel.
false
94d88ae01f38050fa8f03842be24da5a3f860ab1
tgoel5884/twoc-python
/Day4/program2.py
542
4.3125
4
a = int(input("Enter the no of tuples you want to add in the list: ")) b = int(input("Enter the no of elements you want to add in each tuple: ")) List = [] for i in range(a): print("Enter the elements in Tuple", i + 1) Tuple = [] for j in range(b): Tuple.append(int(input("Enter the element: "))) List.append(tuple(Tuple)) N = int(input("Enter index about which you want to sort the list: ")) List.sort(key = lambda x : x[N]) print("After sorting tuple List by Nth index sort:",List) # Code by Tanmay Goel
true
ba9e575719e21c20983bbb2a9ef8187246cdb3fd
a-abramow/MDawsonlessons
/lessons/Chapter 06/6_08.py
1,520
4.28125
4
# Доступ отовсюду # Демонстрирует работу с глобальным переменными def read_global(): print("В области видимости функции read_global() значение value равно", value) def shadow_global(): value = -10 print("В области видимости функции shadow_global() значение value равно", value) def change_global(): global value value = -10 print("В области видимости функции change_global() значение value равно", value) # Основная часть # value - глобальная переменная, потому что сейчас мы находимся в глобальной области видимости value = 10 print("В глобальной области видимости значение переменной value сейчас стало равным", value, "\n") read_global() print("Вернемся в глобальную область видимости. Здесь value по-прежнему равно", value, "\n") shadow_global() print("Вернемся в глобальную область видимости. Здесь value по-прежнему равно", value, "\n") change_global() print("Вернемся в глобальную область видимости. Значение value измнилось на", value, "\n") input("\n\nНажмите Enter, чтобы выйти.")
false
48bd30e53c5ccd161965c7133d4a378de01e80d1
a-abramow/MDawsonlessons
/lessons/Chapter 05/Homework_01.py
512
4.34375
4
# Создайте программу, которая будет выводить список слов в случайном порядке.На экране должны печататься без # повторений все слова из представленного списка. import random words = ["run", "fast", "bill", "apple", "dog", "cat"] print('Эти слова в случайном порядке:') while words: word = random.choice(words) print(word) words.remove(word)
false
036a2c05ee302c3bb0dd70f6445c8b4f7f2fec6b
kaukas14/python-shit
/ex32.py
1,073
4.46875
4
the_count = [1, 2, 3, 4, 5] fruits = ['apples','oranges','pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for loop goes throught a list for number in the_count: print(f"This is count {number}") # same as above for fruit in fruits: print(f"A fruit of type: {fruit}") #also we can go throught mixed list too #notice we have to use {} since we dont know whats in it for i in change: print(f"I got {i}") # we can also build lists, first start with an emply one elements = list(range(5)) # range(5) nuo 0 iki 4 for i in elements: print(f"Elements with range: {i}") # then use the range function to do 0 to 5 counts for i in range(0, 6): #range pirmas itraukiamas o antras ne print(f"Adding {i} to the list") # append is a function that listts understand appent prideda i esama nebutinai tuscia elements.append(i) # now we can print them out too for i in elements: print(f"Element was: {i}") sarasioks = [[1,2,3],[4,5,6]] # array toks labiau for i in sarasioks: print(f"narys: {i[1]}")
false
9cfc335ffe0c53f298a637da72223abb916829c6
Fin-Syn/Python-Beginings
/first_list.py
1,249
4.59375
5
days_of_week = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'] print (days_of_week [2]) #Changes element in the list days_of_week [0] = 'Sunday' print (days_of_week) #Slices the list, but formats is as stated in the list print (days_of_week [2:5]) #Example nested list, when printing needs to call list, then item within list child1 = ['Pat', 5, 6.5] family = [child1] print (family [0] [1]) kevin_list = [] #Adding single values to a list kevin_list.append ('kevin') kevin_list.append ('wolf') print (kevin_list) #Adding multiple values to a list in one line of code kevin_list.extend (['july 26', 29]) print (kevin_list) #Second way of adding multiple lines to a list kevin_list = kevin_list + [1991, 'learning python'] #Insert a value in the selected spot kevin_list.insert (3, 'age') print (kevin_list) #Removes only the first instance of selected vaule kevin_list.remove ('age') print (kevin_list) #(max () ) prints highest value in list number = [16, 8, 15, 42, 23, 4] print (max(number)) #Automatically sorts list based on pythons defualt, sort can be configured number.sort() print (number) #Reverses the order of the list kevin_list.reverse() print (kevin_list)
true
c92c03f694a6c07a2b699102edd11edeb7e49ec2
ZhangJiaQ/everything
/Python/Algorithm/LintCode/30. Insert Interval.py
1,944
4.21875
4
""" Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end 30. Insert Interval 中文English Given a non-overlapping interval list which is sorted by start point. Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary). Example Example 1: Input: (2, 5) into [(1,2), (5,9)] Output: [(1,9)] Example 2: Input: (3, 4) into [(1,2), (5,9)] Output: [(1,2), (3,4), (5,9)] """ class Solution: """ @param intervals: Sorted interval list. @param newInterval: new interval. @return: A new interval list. """ def insert(self, intervals, newInterval): # write your code here """ 1. 加入到一个数组内,按起始值进行排序 2. 设置result数组,存入第一个区间元素 3. for 循环剩余区间元素 3.1 判断result数组最后一个区间元素的末尾值与for循环数组的第一个起始值 如果for循环数组的第一个起始值 <= result 数组最后一个区间元素末尾值 则证明有重叠 将result数组最后一个区间元素末尾值改为两者较大的值 3.2 如果 > 则区间无重叠,正常append """ intervals.append(newInterval) intervals.sort(key=lambda x: x.start) result = [intervals[0]] for d in range(1, len(intervals)): len_num = len(result) if result[len_num-1].end >= intervals[d].start: # 执行重叠元素相加操作 result[len_num-1].end = max(result[len_num-1].end, intervals[d].end) else: result.append(intervals[d]) return result
false
edc76b2b6c2a2926e3a4f9529829661fe5eb2669
Stashare/Bc13_Day2
/missingnumber.py
558
4.21875
4
"""MissingNumber""" def find_missing(a,b): temparr=[] #an array that stores missing numbers temporarily during the loop #and it is assigned to outputarr. outputarr=[0] #output the final result #loop to check whether there is missing numbers for i in b: if i not in a: temparr.append(i) outputarr=temparr print outputarr find_missing([], [])#A call to the find_missing function,passing arrays as parameters #the output should be [0]
true
cf8a2e180a9866c3a980ebfec8424562bb0ab65f
santosh2alp/hellow-world
/exp.py
1,091
4.21875
4
#!/usr/bin/python3 # First python program def printMassage(): print("The Quick Brown Fox Jumps Over The Lazy Dog!") if __name__ == "__main__": printMassage() # Arithemetic Oprators ''' num1 = 10 num2 = 20 print ("Num1 + Num2 =",num1+num2) print ("Num1 - Num2 =",num1-num2) print ("Num1 * Num2 =",num1*num2) print ("Num1 / Num2 =",num1/num2) print ("Num1 // Num2 =",num1//num2) print ("Num1 ^ Num2 =",num1**num2) # Assignment Oprators num3 = num1 + num2 #print(num3) num3+=num2 # num3 = num3 + num2 #print(num3) # Comparison Operators print("Is num 3 > num 2 ?",num3 > num2) print("Is num 2 = num 3 ?",num2==num3) print("Is num1 != num 2 ?",num1!=num2) ''' # Logical Operators # x = True # y = False # print("x and Y",x and y) # print("x or y", x or y) # print("not if x",not x) #Bitwise Operators ''' num4 = 6 #110 num5 = 2 #010 print('Bitwise and =',num4 & num5) print('Bitwise or =',num4 | num5) print('Bitwise xor =', num4 ^ num5) print("num4 rightshift by 2", num4 >> 2) print("num5 left shift by 2", num5 << 2) ''' #Identity Operators #Membership Operators
false
2d5778d4a29476d3da4731d3b4bf523c16ed842e
cglima/maratona-data-science
/semana01/laboratorio/ex2.7/ex2.7c.py
862
4.34375
4
"""Programa que escolhe o mais barato dentre 5 produtos Faça um programa que pergunte o preço de 5 produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato. 3. Uma lista bidimensional com preço e nome """ #pergunte o preço de 5 produtos produtos = [ ["computador", 0 ], ["smartphone", 0 ], ["videogame", 0 ], ["cama", 0 ], ["miojo", 0], ] for indice in range(5): preco_produto = float(input(f"Qual o preço do {produtos[indice][0]}? ")) produtos[indice][1] = preco_produto print(produtos) # escolha o mais barato posicao_menor = 0 for posicao_atual in range(5): if (produtos[posicao_atual][1] < produtos[posicao_menor][1]): posicao_menor = posicao_atual print(f"O produto mais barato é o {produtos[posicao_menor][0]} com o preço de R${produtos[posicao_menor][1]}")
false
5387a36e27d9425e0699db07d3d5aa6d3d3d205a
juffaz/module4
/task10.py
1,002
4.21875
4
print('Задача 10. Максимальное число (по желанию)') # Пользователь вводит три числа. # Напишите программу, # которая выводит на экран максимальное из этих трёх чисел (все числа разные). # Можно использовать дополнительные переменные, если нужно first_dig = int(input("Введите первое число: ")) second_dig = int(input("Введите второе число: ")) third_dig = int(input("Введите третье число: ")) ### Решение номер 1 #temp_dig = first_dig #if temp_dig < second_dig: # temp_dig = second_dig #if temp_dig < third_dig: # temp_dig = third_dig #print("Максимальное число", temp_dig) ### Решение номер 2 l=[] l.append(first_dig) #print(l) l.append(second_dig) #print(l) l.append(third_dig) #print(l) print(max(l))
false
5307cc0e8ef1eef508357f5217d98d5e1dce0fb6
katiavega/CS1100_S03
/Ejercicio05.py
2,121
4.15625
4
print ("Ingrese fecha de nacimiento:") dia = int(input("Ingrese dia:")) mes = int(input("Ingrese mes:")) anio = int(input("Ingrese año:")) if anio % 2 == 0: # Es año PAR
 if mes>=1 and mes<=3: # Ene,Feb ó Mar
 if dia % 2 ==0: #Día PAR
 print("Tu piedra preciosa es: ", "Rubí") else: #Día IMPAR
 print("Tu piedra preciosa es: ", "Zafiro") elif mes>=4 and mes<=6: # Abr, May, Jun
 if dia % 2 ==0: #Día PAR
 print("Tu piedra preciosa es: ", "Diamante") else: # Día IMPAR
 print("Tu piedra preciosa es: Turmalina") elif mes>=7 and mes<=9:# Jul, Ago, Set
 if dia % 2 == 0: #Día PAR
 print("Tu piedra preciosa es: ", "Turquesa") else: #Día IMPAR
 print("Tu piedra preciosa es: ", "Hematita") elif mes>=10 and mes<=12: # Oct, Nov, Dic
 if dia % 2 ==0: #Día PAR
 print("Tu piedra preciosa es: ", "Esmeralda") else: #Día IMPAR
 print("Tu piedra preciosa es: ", "Opalo") else: # Es año IMPAR

 if mes>=1 and mes<=3: # Ene,Feb ó Mar
 if dia % 2 ==0: #Día PAR
 print("Tu piedra preciosa es: ", "Lapizlázuri") else: #Día IMPAR
 print("Tu piedra preciosa es: ", "Topacio") elif mes>=4 and mes<=6: # Abr, May, Jun
 if dia % 2 ==0: #Día PAR
 print("Tu piedra preciosa es: ", "Aguamarina") else: #Día IMPAR
 print("Tu piedra preciosa es: ", "Rodocrosita") elif mes>=7 and mes<=9: # Jul, Ago, Set
 if dia % 2 ==0: #Día PAR
 print("Tu piedra preciosa es: ", "Amatista") else: #Día IMPAR
 print("Tu piedra preciosa es: ", "Peridoto") elif mes>=10 and mes<=12: # Oct, Nov, Dic
 if dia % 2 ==0: #Día PAR
 print("Tu piedra preciosa es: ", "Ambar") else: #Día IMPAR
 print("Tu piedra preciosa es: ", "Jade") print("...Fin del Programa...")
false
c8b0db36c366681ec0245f0441a2ab8e25d59e82
chelseacx/CP1404
/Practicals/workshop 4/calculating_bmi.py
587
4.15625
4
def get_float_value(variable_name, measurement_unit): while True: try: float_value = float(input("Please enter your {} in {}: ".format(variable_name, measurement_unit))) break except ValueError: print("Invalid value!") return float_value print("Body-mass-index calculator, for CP1404") weight = get_float_value("weight", "kgs") """ function that gets the float value""" height = get_float_value("height", "m") bmi = weight / (height * height) print("Therefore, your BMI value is: {:.2f}".format(bmi)) print("Thank you!")
true
30584f415728ad4df70f03004cff68c03823dd9f
ElielLaynes/Curso_Python3_Mundo1_Fundamentos
/Mundo1_Fundamentos/Aula07_Operadores_Aritméticos/DESAFIOS/desafio009.py
721
4.15625
4
# Faça um programa que leia um número inteiro qualquer e mostre na tela a sua tabuada. num = int(input('Digite um Número: ')) print('=' * 30) print('A Tabuada de {} é:'.format(num)) print('=' * 30) print('{} x 0 = {:^5}'.format(num, num * 0)) print('{} x 1 = {:^5}'.format(num, num * 1)) print('{} x 2 = {:^5}'.format(num, num * 2)) print('{} x 3 = {:^5}'.format(num, num * 3)) print('{} x 4 = {:^5}'.format(num, num * 4)) print('{} x 5 = {:^5}'.format(num, num * 5)) print('{} x 6 = {:^5}'.format(num, num * 6)) print('{} x 7 = {:^5}'.format(num, num * 7)) print('{} x 8 = {:^5}'.format(num, num * 8)) print('{} x 9 = {:^5}'.format(num, num * 9)) print('{} x 10 = {:^5}'.format(num, num * 10))
false
e8bf766cb61490a70fbc298c790b0aadcaf2b1de
Mrklata/Junior
/tuples.py
766
4.15625
4
def tuple_checker(a, b): unique_a = set(a) - set(b) unique_b = set(b) - set(a) if a == b: return 'tuples are equal' if unique_b != unique_a: return f'tuples are not equal and the unique values are a: {unique_a}, b: {unique_b}' else: return 'tuples are not equal but have the same values' def test_tuple(): same_tuples = tuple_checker((1, 2, 3), (1, 2, 3)) same_values_tuple = tuple_checker((1, 2, 3), (3, 2, 1)) different_tuples = tuple_checker((1, 2, 3), (2, 3, 5, 7, 5, 4)) assert same_tuples == "tuples are equal" assert same_values_tuple == "tuples are not equal but have the same values" assert different_tuples == "tuples are not equal and the unique values are a: {1}, b: {4, 5, 7}"
true
a8df3d657504d3ab7c0c7e69ffbc484702bab7d2
wenzhifeifeidetutu/pythonWork
/pythonCrashcourseExerciseAnswer/p179.py
435
4.125
4
#p179 try: number1 = int(input("please input first number ")) number2 = int(input("please input second number ")) except ValueError: print("you should input number !") else: print(str(number1 + number2) ) while True: try: number1 = int(input("please input first number ")) number2 = int(input("please input second number ")) except ValueError: print("you should input number !") else: print(str(number1 + number2) )
false
63ee2a4321f54f09e2c06cccb689b017ad090a6a
MythiliPriyaVL/PySelenium
/venv/ProgramCode/34-ModuleItertools.py
573
4.46875
4
""" Define a function even_or_odd, which takes an integer as input and returns the string even and odd, if the given number is even and odd respectively. Categorise the numbers of list n = [10, 14, 16, 22, 9, 3 , 37] into two groups namely even and odd based on above defined function. Hint : Use groupby method of itertools module. Iterate over the obtained groupby object and print it's group name and list of elements associated with a group. """ def even_or_odd(inputI): if(inputI%2==0): return "Even" else: return "Odd" n=[10,14,16,22,9,3,37]
true
a81870d539a8fd5de0f7c7514a04bcfd87532f6f
MythiliPriyaVL/PySelenium
/venv/ProgramCode/31.2-TimeDelta.py
1,244
4.28125
4
#Example file for timedelta from datetime import datetime from datetime import date from datetime import time from datetime import timedelta def main(): # basic timedelta print(timedelta(days=365, hours=5, minutes=1)) #Today's date now = datetime.now() print("Today is: ", str(now)) #Today's date one year from now print("One year from now, it will be: ", str(now+timedelta(365))) # timedelta with more argument print("In 2 days and 3 weeks, it will be: ", str(now + timedelta(days=2, weeks=3))) #Calculate Date 1 week ago, formatted as a String t= datetime.now() - timedelta(weeks=1) s = t.strftime("%A %B %d, %Y") print("One week ago it was: ", s) #How many days until April fool's day today = date.today() afd = date(today.year, 4, 1) #2020-04-01 #Check if the April Fool's day already went by if afd < today: print("April fool's day already went by %d days ago" %((today-afd).days)) afd = afd.replace(year = today.year+1) time_to_afd = afd-today print("It's just ", time_to_afd.days," days until April Fool's day") print(timedelta.max) print(timedelta.min) print(timedelta.resolution) if __name__ =="__main__": main();
true
6505d7aa96966839827ac72822be80332f018413
MythiliPriyaVL/PySelenium
/venv/ProgramCode/11-PrimeNumbers.py
668
4.25
4
#5. Print prime numbers below a given number. #Get input from the User and print whether the value is Prime or Not numberInput = int(input("Enter any number, I can print the Prime Numbers below that :")) #Validating the Input value if (numberInput == 1 or numberInput == 2 ): print("There is no Prime Number below " + str(numberInput)) else: print("Prime numbers below " + str(numberInput) + " are: ") print("2") x = 1 for num in range(3, numberInput,2): for i in range(2, num): if (num % i) == 0: break else: x = x + 1 print(num) print("Total number of prime numbers are: ", x)
true
9c76c25e8e7d552cf7a53ce4dc4ee341963dd20d
MythiliPriyaVL/PySelenium
/venv/ProgramCode/31.1-DateTimeFormatting.py
817
4.375
4
#Example file for Date Formatting from datetime import datetime def main(): now=datetime.now() ### DATE FORMATTING ### print(now.strftime("Current year is: %Y")) #Current year is: 2020 # %y/%Y - Year, %a/%A - Weekday, %b/%B - month, %d - day of month print(now.strftime("%a, %d %B, %y")) #Thu, 27 February, 20 # %c - Local date and time, %x - local date, %X - local time print(now.strftime("Local date and time: %c")) #Local date and time: Thu Feb 27 18:33:35 2020 print(now.strftime("Local date: %x")) print(now.strftime("Local time: %X")) ### TIME FORMATTING ### # %I/%H - 12/24 Hour, %M - minute, %S - second, %p - Local AM/PM print(now.strftime("Current time: %I:%M:%S %p")) print(now.strftime("24-hour time: %H:%M")) if __name__ =="__main__": main();
false
a6c3a5848f1f16bddcf0f65e0927b6cc7d396eb3
MythiliPriyaVL/PySelenium
/venv/ProgramCode/05-LoginCheck.py
740
4.15625
4
""" Login Testing: 1. User Name and Password are hardcoded in the program 2. User should enter right combination of values to login 3. User can try upto 3 times and the program stops after that. """ #Hardcoded User Name and Password values uN1 = "newUser" uP1 = "09876" #Looping for 3 maximum attempts for x in range(3): #User Input for User Name and Password uName = input("Enter the User Name: ") uPassword = input("Enter the Password: ") if(uN1 == uName and uP1 == uPassword): print("User login Successful.") print("Access granted") break else: print("User login Unsuccessful.") print("Access Denied") else: print("Maximum attempts reached. Try after sometime.")
true
1deb4d6cf623e49cff90450de4087c1c5433b18a
demetredevidze/edge-final-project
/final.py
1,377
4.28125
4
# day_1_game.py # [Demetre Devidze] import random rules = "Rules are simple! You get 5 chances to guess a random integer between 0 and 30. " hint1 = "PS, 5 tries is definitely enough! If you play smart you will be able to win the game every single time!" hint2 = "Think about the powers of 2. Two to the power of five is 32, so you have enough number of tries." user_name = input("Hey, what's your name? \n") print("Hi " + user_name + ", would you like to play a game on guessing random numbers?") play_game = input() if play_game == "yes" or "Yes" or "YES" or "yeah" or "YEAH" or "Yeah" or "Sure" or "sure" or "SURE" or "lets do it": print("Great decision " + user_name + "! " + rules + " Good luck!") print(hint1) answer = random.randint(0, 30) for guess_number in range(5): guess = input("what is your guess:") if int(guess) == answer: print("Well done " + user_name + "! You got it right!") break elif int(guess) > answer: print("Too big " + user_name + "! Try again!") elif int(guess) < answer: print("Too small " + user_name + "! Try again!") else: print("Sorry " + user_name + "! You are out of guesses!") print("But I will give you a hint! " + hint2 + " Play smarter next time!") else: print("Okay " + user_name + "! No hard feelings, have a nice day!")
true
26c9f7e383cce71cde211cd35562d951f7c64c54
RAJARANJITH1999/Python-Programs
/even.py
214
4.1875
4
value=int(input("enter the value to check whether even or odd")) if(value%2==0): print(value,"is a even number") else: print(value,"is odd number") print("vaule have been checked successfully")
true
9285ac69e4170b19d8cf59a5e202d3368933d978
RAJARANJITH1999/Python-Programs
/bitodec.py
474
4.15625
4
n=int(input("enter the binary number (1's and 0's)")) base=1 decimal=0 binary=n while(n>0): rem=n%10 decimal=decimal+rem*base n=n//10 base=base*2 n1=int(input("enter the decimal number to convert into binary")) base2=1 bi=0 dec=n1 while(n1>0): rem1=n1%2 bi=bi+rem1*base2 n1=n1//2 base2=base2*10 print(" binary number =",binary) print("decimal number =",decimal) print("decimal number =",dec) print("binary number =",bi)
false
2d2147a5e19328d03bb6105bc77f569881ccfced
RAJARANJITH1999/Python-Programs
/shirt.py
880
4.125
4
white=['M','L'] blue=['M','S'] available=False print("*****search for your color shirt and size it*****") color=input("enter your shirt color") if(color.lower()=='white'): size=input("enter your size") if((size.upper() in white)): print("available") available=True else: print("unavailable") elif( color.lower()=='blue'): size=input("enter your size") if(size.upper() in blue): print("available") available=True else: print("unavailable") else: print("unvailable") if(available==True): name=input("enter your name ") address=input("enter the addres to place order") mobile=int(input("enter your mobile number")) print("********order confirmation*******") print("name:",name) print("address:",address) print("mobile:",mobile) print("***ordered shirt***\n","color:",color,"\nsize:",size.upper())
true
7346df8393977718803fbe9c33ab377afb56a2c9
wengellen/cs36
/searchRotatedSortedArray.py
554
4.1875
4
# Given an integer array nums sorted in ascending order, and an integer target. # # Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # # You should search for target in nums and if found return its index, otherwise return -1. # # Example 1: # Input: nums = [6,7,0,1,2,3,4,5], target = 0 # Output: 2 # # Example 2: # Input: nums = [6,7,0,1,2,3,4,5], target = 3 # Output: 5 # # Example 3: # Input: nums = [1], target = 0 # Output: -1 def csSearchRotatedSortedArray(nums, target):
true
0d7662fc3a197bb8d5fb992726c99597bd2a410c
wengellen/cs36
/linkedListPatterns.py
859
4.125
4
class LinkedListNode: def __init__(self, value): self.value = value self.next = None self.prev = None x = LinkedListNode('X') y = LinkedListNode('Y') z = LinkedListNode('Z') x.next = y y.next = z y.prev = x z.prev = y def print_ll_reverse(tail): current = tail while current is not None: # print(current.value) current = current.prev # traverse a linked list and print value of each node def print_ll(head): # init a new variable to refer to the node we have # access to current = head # use while loop to keep traversing until our # `current` variable falls off the tail of the ll while current is not None: print(current.value) # update our `current` variable to refer to the # next node in the ll current = current.next print_ll_reverse(z)
true
b743ffa0b4a76bceb5b53afb58b2e3b2106652e9
tsoutonglang/gwc-summer-2017
/your-grave.py
2,059
4.1875
4
start = ''' You wake up strapped to a chair at the bottom of a grave. Your arms are tied behind your back, and your feet are tied to the chair. You look up and see the Riddler standing over you with a shovel in his hand. "You have to play my games to live. It's game over once you get a riddle wrong. Get all three right then everyone lives! If you get the first two right, you and one other person dies. If you only get the first one wrong then you and three people die. It's game over for you and five innocents if you get them all wrong! He stabbed the shovel into the ground and rubbed his hands together. 'Let's begin" ''' print(start) print("People endangered: 5") print("'What is the beginning of eternity, the end of time and space, the beginning of every end, and every race?''") user_input = input() if user_input == "e": print("'Congrats, you just saved yourself and two others...''") print("People endangered: 3") print("'What starts with the letter 'e,' ends with 'e,' but only has one letter?''") user_input = input() if user_input == "eye": print("'Congrats, you saved two more people. Ready for the final round?''") print("People endangered: 1") print("'What belongs to you, but is used by others?'") user_input = input() if user_input == "your name": print("'Congradulations young Gothamite, you saved your butt and 5 people'") print("The Riddler walks away from the grave leaving you tied to the chair six feet below the ground.") else: print("'You little idiot.' He takes the shovel and buries you in dirt. 'I hope your guilty conscience can deal with killing someone... Oh wait, you're gonna be dead too!'") print("People killed: 1") else: print("'WHY DO YOU DO THIS?!' He angrily grabs the shovel and knocks you out with it. He begins to bury you alive.") print("People killed: 3") else: print("The Riddler shakes his head and grabs his shovel to bury you alive.") print("People killed: 5")
true
8d57d7804f802324d3a2a23bda49bb553f82b463
manas-mukherjee/MLTools
/src/tutorials/fluentpython/2-Vector.py
816
4.28125
4
#Example 1-2 is a Vector class implementing the operations just described, through the use of the special methods __repr__, __abs__, __add__ and __mul__. from math import hypot class Vector: """docstring for Vector.""" def __init__(self, x=0, y=0): self.x = x self.y = y def __repr__(self): return 'Vector(%r, %r)' % (self.x, self.y) def __abs__(self): return hypot(self.x, self.y) def __bool__(self): return bool(abs(self)) def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x,y) def __mul__(arg): x = self.x * other.x y = self.y * other.y return Vector(x,y) print(Vector(3,4)) #print(Vector('3','4')) print(bool(Vector(3,4))) print(Vector(1,2) + Vector(3,4) )
false
1c30b6fff4469000460b9518314899e67004f706
manas-mukherjee/MLTools
/src/tutorials/fluentpython/function_as_objects/TestFunction.py
2,833
4.15625
4
############################################## # Treating a Function Like an Object # ############################################## # Example 5-1 print('\nExample 5-1\n------------\n') def factorial(n): '''Returns n factorial''' return 1 if n<2 else n * factorial(n-1) print(factorial(42)) print(factorial.__doc__) print(type(factorial)) print(help(factorial)) # Example 5-2 print('\nExample 5-2\n------------\n') fact = factorial print(fact(6)) print(list(map(fact, range(10)))) # Example 5-3 print('\nExample 5-3\n------------\n') # Higher order functions # Imp: map, filter, and reduce fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits, key=len, reverse=True)) # Example 5-4 print('\nExample 5-4\n------------\n') def reverse(word): return word[::-1] print(sorted(map(reverse, fruits), key=len)) # Example 5-5 print('\nExample 5-5\n------------\n') # A listcomp or a genexp does the job of map and filter combined, but is more readable. #Old way using list - Build a list of factorials from 0! to 5!. print(list(map(fact, range(6)))) #New way using list comprehension. print([fact(num) for num in range(6)]) #Old way using list - List of factorials of odd numbers up to 5!, using both map and filter.. print(list(map(fact, filter(lambda n : n%2, range(6))))) #New way using list comprehension. print([fact(num) for num in range(6) if num % 2]) # Example 5-6 print('\nExample 5-6\n------------\n') #Starting with Python 3.0, reduce is not a built-in. from functools import reduce from operator import add print(reduce(add, range(100))) print(sum(range(100))) l = [n for n in range(25) if n % 2 == 0] print(l) print(all(l[1:])) print(any([1,0,0,0])) ############################################## # Anonymous Functions # ############################################## # Example 5-7 print('\nExample 5-6\n------------\n') fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits, key=reverse)) print(sorted(fruits, key = lambda x : x[::-1])) ############################################## # User-Defined Callable Types # ############################################## # Example 5-8 print('\nExample 5-8\n------------\n') import random class BingoCage: def __init__(self, items): self._items = list(items) random.shuffle(self._items) def pick(self): try: return self._items.pop() except IndexError: raise LookupError('pick from empty BignoCase') def __call__(self, *args, **kwargs): return self.pick() bingo = BingoCage(range(3)) print("direct - " , bingo()) for i in range(2): p = bingo.pick() print(p) # for l in dir(factorial): # print(l) print(factorial.__dict__) import bobo
true
19f26e9acaab20e6ca4c43ab04797cafa9fb6f0f
Sciencethebird/Python
/Numpy/arrange and linspace.py
686
4.125
4
import matplotlib.pyplot as plt import numpy as np import math # arange and linespace both output np array # arange: x1 form [0, 10) increase by 1 x1 = np.arange(0,10,0.1) print(x1) # linespace: x2 belongs to [10, 2] with twenty dots x2 = np.linspace(10,2,50) print('numpy array is converted to a python list \n', list(x2)) y1 = np.sin(x1) y2 = np.cos(x2) #1. math functions do not take np array #2. math functions do not take list (one in one out) #y3 = math.tan(list(x1)) #Visualization using matplotlib plt.plot(x1, y1, label = 'arrange') plt.plot(x2, y2, label = 'linspace') plt.xlabel = 'x' plt.ylabel = 'y' plt.title = 'arrange vs linespace' plt.legend() plt.show()
true
3ec05fbcb0a83872f6dc2454482e07aca2e52229
zanda8893/Student-Robotics
/.unused/code.py
2,586
4.1875
4
import time import random """ this is a rough first attempt which shouldn't work """ class move(): """ the general movement methods for the robot they are programmed here for easy access and to make it easier when implementing new ideas # TODO: add proper moter commands for starting and stoping to robit code branch """ """ this class is working on the assumption that we dont have any sensors updating the position once we have sensors, we can update this to get more accurete movement """ def forward(self, distance): #move forward code print("Forward class") print("moving",distance) sleep = distance / 2.2 #convert the distance into time s = d / t if sleep < 0: #time.sleep doent work with negative numbers so this make the numbers positive sleep = 0 - sleep moters = True #power the moters time.sleep(sleep) moters = False #stop the moters print("moved",distance) def backward(self, distance): #might not need this. we could use a negative number in the move.forward() function print("Backwards class") print("moving",distance) sleep = distance / 2.2 #convert the distance into time s = d / t (number=filler) if sleep < 0: #time.sleep doent work with negative numbers so this make the numbers positive sleep = 0 - sleep moters = True #power the moters in reverse time.sleep(sleep) moters = False #stop the moters print("moved",distance) def right(self, angle): print("right class") print("turning", angle, "clockwise") sleep = angle / 2.2 #convert the angle into time using, s = d / t (filler number) if sleep < 0: #time.sleep doent work with negative numbers so this make the numbers positive sleep = 0 - sleep left_moters = True #rurns right right_moters = False time.sleep(sleep) left_moters = False #stop the moters right_moters = False print("turned",angle , "clockwise") def left(self, angle): print("left class") print("turning", angle, "counterclockwise") sleep = angle / 2.2 #convert the angle into time using, s = d / t(numberr=filler) if sleep < 0: #time.sleep doent work with negative numbers so this make the numbers positive sleep = 0 - sleep left_moters = False #turns left right_moters = True time.sleep(sleep) left_moters = False #stop the moters right_moters = False print("turned",angle , "counterclockwise") class sensor(): """ docstring for Sensors. """ def camara(self, arg): pass move = move() test = 6 move.forward(test) move.right(test) #move.forward(input())
true
3b05334d87578f06dbdae53128873bf77f512ef4
ccbrantley/Python_3.30
/Decision Structures and Boolean Logic/Brantley_U3_14.py
645
4.21875
4
weight = 0 height = 0 print('This progam will calculatey your BMI(Body Mass Index).') weight = int(input('Please enter in your weight using a measurement of pounds.')) height = int(input('Please enter in your height using a measurement of inches.')) BMI = weight * 703/height**2 if 18.5 <= BMI <= 25: print('Your BMI is ', format(BMI, ',.2f'), ' and is classified as optimal.', sep='') elif BMI > 25: print('Your BMI is ', format(BMI, ',.2f'), ' and is classified as overweight.', sep='') elif BMI < 18.5: print('Your BMI is ', format(BMI, ',.2f'), ' and is classified as underweight.', sep='') else: print('NULL')
true
5f5b691d7740a9bb38c7a28cbda880cc6ed2aed6
ccbrantley/Python_3.30
/Repetition Structure/Brantley_U4_8.py
285
4.375
4
number = 0 number_sum = 0 print('Enter positive numbers to sum them together and enter a negative number to stop.') while number >= 0: number = float(input('Enter number: ')) if number >= 0: number_sum += number print('The sum is:', format(number_sum, ',.2f'))
true
7edaaf88bdc2d0df04c503d28f817a286775bd25
Mike1514/python_project
/max num, min num, etc.py
631
4.1875
4
#Напишите программу, которая получает на вход три целых числа, по одному числу в строке, # и выводит на консоль в три строки сначала максимальное, потом минимальное, после чего оставшееся число. f = int (input()) s = int (input()) t = int (input()) a = max(f, s, t) b = min(f, s, t) print(a) print(b) if a == f and b == s or a == s and b == f: print(t) elif a == t and b == f or a == f and b == t: print(s) elif a == s and b == t or a == t and b == s: print(f)
false
7f395f81d1c25a4eb0a5ca406328745dff758ded
whereislima/python-syntax
/words.py
373
4.40625
4
def print_upper_words(words, first_letter): """ print out each word in all uppercase only print words that start with h or y """ for word in words: if word[0] == "h" or word[0] == "y": print(word.upper()) # this should print "HELLO", "HEY", "YO", and "YES" print_upper_words(["hello", "hey", "goodbye", "yo", "yes"], {"h", "y"})
false
2bb3801d508611d068f14d575a80a368c7252c3c
Jeremyljm/new
/05-高级数据类型/hm_20_字符串切片演练.py
593
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- num_str = "abcdefghi" # 截取2-5位置的字符串 print(num_str[2:6]) # 截取2-末尾位置的字符串 print(num_str[2:]) # 截取从开始-5位置的字符串 print(num_str[0:6]) # 截取完整的字符串 print(num_str[:]) # 从开始位置,每隔一个字符截取字符串 print(num_str[::2]) # 从索引1开始,每隔一个取一个 print(num_str[1::2]) # 截取从2-末尾 -1的字符串 print(num_str[2:-1]) # 截取字符串末尾两个字符 print(num_str[-2:]) # 字符串的逆序(面试题) print(num_str[::-1])
false
449f7ce26696cd4804d5e7796a5d724d9b9c34b8
ashishaaron346/MONTHLY_TASKS_PROJECT
/March_2019_Task2/Beginner_Python_Projects_2/proj13DiceRoll.py
1,520
4.125
4
#!/usr/bin/env python3 # proj13DiceRoll.py - r/BeginnerProjects #13 # https://www.reddit.com/r/beginnerprojects/comments/1j50e7/project_dice_rolling_simulator/ import random, time # Loop until keyboard interrupt while True: try: # Prompt until a positive integer is input for num of sides while True: try: sides = int(input("How many sides does the die have?")) except ValueError: print("I need an integer!") continue if not sides > 0: print("I need a positive integer!") else: break # Prompt until a positive integer is input for num of rolls while True: try: rolls = int(input("How many times should it be rolled?")) except ValueError: print("I need an integer!") continue if not rolls > 0: print("I need a positive integer!") else: break # Initialize variables results = [] resultsDict = {} # Random rolls for i in range(rolls): results.append(random.randint(1, sides)) # Count appearance of each side of the die for i in results: if i in resultsDict: resultsDict[i] += 1 else: resultsDict.setdefault(i, 1) # Print results and their percentages for k in resultsDict: print(str(k) + " appeared " + str(resultsDict[k]) + " times, or " + str(round(resultsDict[k]/rolls*100, 2)) + "% of the time.") # Pause, allowing time for keyboard interrupt, then begin again time.sleep(3) print("\nLet's go again!\n") # Break out of program except KeyboardInterrupt: print("This was fun.") break
true
72a2dea947e7c91504ad5fa81a035c5c34454128
ashishaaron346/MONTHLY_TASKS_PROJECT
/March_2019_Task1/Beginner_Python_Projects_1/proj02Magic8Ball.py
1,135
4.15625
4
#!/usr/bin/env python3 # proj02Magic8Ball.py - r/BeginnerProjects #2 # https://www.reddit.com/r/beginnerprojects/comments/29aqox/project_magic_8_ball/ import time, random responses = ["Nah.", "Get out of here.", "Could be, who knows man.", "Yes", "Technically your odds aren't zero, but realistically...", "Maybe.", "You're wasting everyone's time, ask me a real question.", "Totally", "I'm optimistic", "The future is cloudy"] # Takes a question from user and, after a pause, returns a random response def mainevent(): # "Takes" a question from user but doesn't do anything with it input("Ask me a question") # Tells user it is thinking, waits for 3 seconds print("Let me think about that...") time.sleep(3) # Prints a random response from list above result = responses[random.randint(0,len(responses)-1)] print(result) # Loop until user opts to quit program while True: # Run 8 ball function mainevent() # Pause while user reads the 8 ball response time.sleep(3) # Give user the option to continue or quit prompt = input("Press anything to go again or enter QUIT\n") if prompt == "QUIT": break
true
04bb9b3d91d0f91b5c9f8b66a9ff301af2983553
daorejuela1/holbertonschool-higher_level_programming
/0x06-python-classes/100-singly_linked_list.py
2,165
4.15625
4
#!/usr/bin/python3 """linked list docstrings. This module demonstrates how to use a linked list with classes. """ class Node(): """This class defines a memory space""" def __init__(self, data, next_node=None): """ corroboares data is int and next node is valid""" if type(data) is not int: raise TypeError("data must be an integer") self.__data = data if type(next_node) is not Node and next_node is not None: raise TypeError("next_node must be a Node object") self.__next_node = next_node @property def data(self): """get data value""" return self.__data @property def next_node(self): """get next node value""" return self.__next_node @next_node.setter def next_node(self, value): """set next node value""" if type(value) is not Node and value is not None: raise TypeError("next_node must be a Node object") self.__next_node = value class SinglyLinkedList(Node): """defines a single linked list structure""" def __init__(self): """head initialization""" self.__head = None def __str__(self): """in case of printing""" final_str = "" while(self.__head is not None): final_str += str(self.__head.data) if (self.__head.next_node is not None): final_str += "\n" self.__head = self.__head.next_node return(final_str) def sorted_insert(self, value): """insert the node in order""" if (self.__head is None): self.__head = Node(value) return if (value <= self.__head.data): self.__head = Node(value, self.__head) return origin = self.__head while (self.__head.next_node is not None): if (self.__head.next_node.data > value): self.__head.next_node = Node(value, self.__head.next_node) self.__head = origin return self.__head = self.__head.next_node self.__head.next_node = Node(value) self.__head = origin
true
99b2b7fa1180a5ed800908c4e3e925d19c1f502e
xx-m-h-u-xx/Scientific-Computing-with-AI-TensorFlow-Keras
/GuessNumber.py
562
4.125
4
# Guess the number game. # GuessNumber.py import random num_guesses = 0 user_name = input("Hi: What is your name? ") number = random.randint(1,20) print("Welcome, {}! Guess number between 1 and 20.".format(user_name)) while num_guesses < 6: guess = int(input("Take a guess?")) num_guesses += 1 if guess < number: print("Number too low") if guess > number: print("Number too high") if guess == number: break if guess == number: print("Woopee!") else: print("Loser!!!")
true
e666d86c38fda89d2434f80db29c44a386020118
fanzou2020/Parsing
/driver.py
1,106
4.25
4
import parser import truth_table inputStr = input('Please enter the proposition:\n') result = parser.parse(inputStr) variables = result["variables"] case = input('1. Given the truth value of variables.\n2. Generate truth table\n') if case == '1': print("The variables are: ", end='') print(variables) s = input('please input the truth value of variables, using "true", "false", "T", or "F"\n') variableTokens = s.split(" ") # print(variableTokens) assignment = [] for x in variableTokens: if x == 'true' or x == 'T': assignment.append(True) elif x == 'false' or x == 'F': assignment.append(False) print(assignment) ast = result["ast"].evaluate(assignment) print("The Value of this proposition is: ", end='') print(ast) elif case == '2': print("The truth table of " + '"' + inputStr + '"') truth_table.generateTruthTable(result) # variables = result["variables"] # # print(ast) # print(variables) # # print() # # print("The truth table of " + '"' + inputStr + '"') # truth_table.generateTruthTable(result)
true
40b995a19b4b4b77e16f9b248dd7e0079514b5cf
JordonZ90/LeapYear
/LeapYear.py
242
4.28125
4
def leap_year(): year = int(input("Please enter the year ")) if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): print(f"{year} is a leap year") else: print(f"{year} is not a leap year") leap_year()
false
ab534206a4e2293ccf0d1d774aa6d698ddabc870
andersonLoyola/python-repo
/book/exerciseOne.py
634
4.25
4
# Write a program that asks the user to enter a integer and prints two integers, root and pwr, such that 0 < pwr < 6 amd root**pwr is equals to the integer entered by the user number = int(input("Write some number: ")) auxNumber = 1 found = False while auxNumber < number and found == False: auxPower=0 while auxNumber**auxPower <= number and auxPower < number and found == False: if auxNumber**auxPower == number: found = True else: auxPower+=1 print(auxNumber, "-", auxPower) if(not found): auxNumber+=1 if found == True: print("number", auxNumber, "power", auxPower) else: print("not found")
true
6f1f06ca37ee63633a8b568afd7c15571a019222
marjorienorm/learning_python
/words.py
1,414
4.21875
4
"""Retrieve and print words for a url. usage: python words.py <URL> """ import sys from urllib.request import urlopen def fetch_words(url): """Fetch a list of words form a url. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document. """ story = urlopen(url) story_words = [] for line in story: #line_words = line.split() line_words = line.decode('utf8').split() for word in line_words: story_words.append( word ) story.close() return story_words def print_items( items ): """Print items oer line from a list of items. Args: items: An iterable series of printable items. Returns: Nothing is returned from this function. """ for item in items: print( item ) def main(url = None): """Print each word from a text document from a URL. Args: url: The URL of a UTF-8 text document. Returns: Nothing is returned from this function. """ if url is None: url = "http://sixty-north.com/c/t.txt" words = fetch_words(url) print_items( words ) #def main(): # words = fetch_words( "http://sixty-north.com/c/t.txt" ) # print_items( words ) if __name__ == '__main__': if len(sys.argv) > 1: main( sys.argv[1] ) else: main()
true
01a55d99f9fbf4b98ec18322393f396480d59f34
Saberg118/CS100
/Tuition_calculator.py
397
4.125
4
# This program will display the projected semester tuition for the next 5 # years if tuition increases by 3% # Initialize tuition = 8000 # Make a table print('Years \t\t Tuition') print('___________________________') #for loop for year in range(1,6): # Calculate tuition tuition *= 1.03 # Display table print(format(year, '.2f'),'\t\t',format(tuition,'.2f'))
true
404845e4a4a0225a1c712014a3a2730f378e287e
Saberg118/CS100
/budget_calculator_using for loop.py
1,082
4.28125
4
# This program keeps the running total of the expenses of the user # and it will give the feedback wither or not the user stayed on # their proposed budget or if they were over or under it. total = 0.0 # initialize the accumulator # Get the budget amount from the user budget = float(input('Enter your budget for the month. ')) number = int(input('How may expenses do you have?')) # Get the total amount of expenses from the user for expense in range(number): expense = float(input("""Enter how much you have spent""")) # Added to the total total += expense # determine wither he is under or over or at their budget # and display the result print('Budget: $', format(budget,".2f")) print('Expense: $', format(total,".2f")) if budget > total: difference = budget - total print('You are $', format(difference, ".2f"),\ 'under your budget') elif budget < total: difference = total - budget print('You are $', format(difference, ".2f"),\ 'over your budget') else: print('You have stayed on budget')
true
8ec079ba4cb5f0388a539f1963ad8f6b6e039a79
Saberg118/CS100
/Ocean_level.py
312
4.3125
4
# This program displays the Ocean level # through years 0 through 25 print('Years \t\t Ocean levels') print('___________________________') Ocean_level = 0 for year in range(1,26,1): Ocean_level += 1.6 print(format(year, '.2f'),'\t\t',format(Ocean_level,'.2f'), 'millimeters')
false
71b3cd139efaa07ca2bd48ed3e81ffbafb2af00b
Saberg118/CS100
/classroom_percentage.py
858
4.1875
4
# This program calculate the percentage of males and females # in a given class. # Get the number of girl in the class. girls = int(input('How many females are in the class? ')) # Get the number of boys in the class. boys = int(input('How many males are in the class? ')) # Calculate the number of students in the class students = boys + girls # Calculate the percentage of girls in the class. percentage_of_girls = (girls / students) * 100 # Calculate the percentage of boys in the class. percentage_of_boys = (boys / students) * 100 # Display the percentage of females in the class print('The percentage or females in the class is', \ format(percentage_of_girls, '.2f'),'%') # Display the percentage of males in the class print('The percentage or males in the class is', \ format(percentage_of_boys, '.2f'),'%')
true
6e11cba06075706d9d8eae9678aaafe941fdb039
cifpfbmoll/practica-3-python-AlfonsLorente
/src/Ex7.py
1,336
4.46875
4
#!/usr/bin/env python3 #encoding: windows-1252 #Pida al usuario tres nmero que sern el da, mes y ao. Comprueba que la fecha introducida es vlida. Por ejemplo: #32/01/2017->Fecha incorrecta #29/02/2017->Fecha incorrecta #30/09/2017->Fecha correcta. import sys if __name__ == "__main__": #declare the variables day = int(input("Insert the day: ")) month = int(input("Insert the month: ")) year = int(input("Insert the year: ")) #if days are greater than 31 in the 31-days month, show incorrect if day > 31 and (month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12): print(day, '/', month, '/', year, "-> incorrect date") #if days are greater than 30 in the 30-days month, show incorrect elif day > 30 and (month == 4 or month == 6 or month == 9 or month == 11): print(day, '/', month, '/', year, "-> incorrect date") #if the days are greater than 28 in february elif day > 28 and month == 2: print(day, '/', month, '/', year, "-> incorrect date") #Other errors that could happen elif(day < 0 or month < 1 or month > 12): print(day, '/', month, '/', year, "-> incorrect date") #the date is correct, print is correct else: print(day, '/', month, '/', year, "-> correct date")
true
68436256894092a0eae4cb852624edd04e53baa5
avholloway/100DaysOfCode
/day9.py
2,573
4.28125
4
programming_dictionary = { "Bug": "An error in a program that prevents the program from running as expected.", "Function": "A piece of code that you can easily call over and over again." } # 9.1 - grading # ----------------------------------------------------------- def one(): student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } # 🚨 Don't change the code above 👆 #TODO-1: Create an empty dictionary called student_grades. student_grades = {} #TODO-2: Write your code below to add the grades to student_grades.👇 for student in student_scores: score = student_scores[student] if score <= 70: grade = "Fail" elif score <= 80: grade = "Acceptable" elif score <= 90: grade = "Exceeds Expectations" else: grade = "Outstanding" student_grades[student] = grade # 🚨 Don't change the code below 👇 print(student_grades) # 9.2 - travel log # ----------------------------------------------------------- def two(): travel_log = [ { "country": "France", "visits": 12, "cities": ["Paris", "Lille", "Dijon"] }, { "country": "Germany", "visits": 5, "cities": ["Berlin", "Hamburg", "Stuttgart"] }, ] #🚨 Do NOT change the code above #TODO: Write the function that will allow new countries #to be added to the travel_log. 👇 def add_new_country(country, visits, cities): travel_log.append({ "country": country, "visits": visits, "cities": cities }) #🚨 Do not change the code below add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"]) print(travel_log) # final - auction # ----------------------------------------------------------- from replit import clear from auctionart import logo #HINT: You can call clear() to clear the output in the console. print(logo) print("Welcome to the secret auction program!") print() bids = {} def collect_bidder_info(): name = input("Name: ") bid = int(input("Bid: $")) bids[name] = bid collect_bidder_info() while input("Another (yes/no): ") == "yes": clear() collect_bidder_info() winning = { "name": "no one", "bid": 0 } for name in bids: this_bid = bids[name] if this_bid > winning["bid"]: winning["name"] = name winning["bid"] = this_bid clear() print(f"The winner is {winning['name']} with a bid of {winning['bid']}")
true
3ae0882b38387b25a66b1cf72c98595d2c539b54
dinphy/python-base-case
/03_函数编程_上/04_返回值.py
1,136
4.5625
5
""" 返回值: 函数执行之后. 会给调用方一个结果. 这个结果就是返回值 关于return: 函数只要执行到了return. 函数就会立即停止并返回内容. 函数内的return的后续的代码不会执行 1. 如果函数内没有return , 此时外界收到的是None 2. 如果写了return 1. 只写了return, 后面不跟数据, 此时接收到的依然是None -> 相当于break 2. return 值 , 此时表示函数有一个返回值, 外界能够收到一个数据 -> 用的最多 3. return 值1, 值2, 值3....., 此时函数有多个返回值, 外界收到的是元组, 并且, 该元组内存放所有的返回值 """ # def func(a, b): # # print(a + b) # return a + b # # # ret = func(10, 20) # print(ret * 3) # def func(): # pass # # return None # # ret = func() # # print(ret) # def func(): # print(123) # return # 会让程序停止. 后续代码不会继续执行. 有点儿像循环里面的break # print(456) # # ret = func() # print(ret) def func(): return 1, 2, 3, 4 ret = func() print(ret)
false
794fb4af68bf0683eab6ce717a4de1cf955f007b
russunazar/-.-1-
/number 3.py
459
4.21875
4
x = float(input("перша цифра: ")) y = float(input("друга цифра: ")) operation = input("Operation: ") result = None if operation == "+": result = x + y if operation == "-": result = x - y if operation == "*": result = x * y if operation == "/": result = x / y else: print("unsupported operation") if result is not None: print("Result: ", result)
true
8e4f94063b10e42d4877fcf11afaaccc00217437
itsmehaanh/nguyenhaanh-c4e34
/Session4/homework/bai4.py
987
4.25
4
print ('''If x = 8, then what is 4(x+3)? 1. 35 2.36 3.40 4.44''') question = { "If x = 8, then what is 4(x+3)?" : { "1" : 35, "2" : 36, "3" : 40, "4" : 44,} } answer = input("Your code:") if answer == "3": print("Bingo!") else: print(":(") print('''Estimate this answer (exact calculation not needed): Jack scored these marks in 5 math tests: 49, 81, 72, 66 and 52. What is the mean? 1. About 55 2. About 65 3. About 75 4. About 85''' ) question2 = { "Estimate this answer (exact calculation not needed)": { "1":"About 55", "2": "About 65", "3": "About 75", "4": "About 85",} } answer_2 = input("Your code:") if answer_2 == "2": print("Bingo!") else: print(":(") if answer == "3" and answer_2 == "2": print("You correctly answer both questions") elif answer != "3" and answer_2 != "2": print("You got both answers incorrect") else: print("You correctly answer 1 out of 2 questions")
true
5df4cabafe46b6606f8712dcd94f62a9bd08c680
hakim-DJZ/HF-Python
/Chapter2/nester/hakim_nester.py
688
4.5
4
"""Example module from chapter 2, Head First Python. The module allows you to print nested lists, by use of recursion. It's named the nester.py module, which provides the print_lol() frunction to print nested lists.""" def print_lol(the_list, indent = False, level=0): """For each item, check if it's a list; if so, keeping calling myself until not a list, then print to standard output""" for each_item in the_list: if isinstance(each_item,list): print_lol(each_item, indent, level+1) else: if indent != False: for tab_stop in range(level): print("\t", end ='') print(each_item)
true
b68dbecaada6712ac96438e48a88e462196ceee8
in-tandem/matplotlib_leaning
/simple_graph.py
484
4.125
4
## i am going to plot using simple lists of data ## i am going to label x and y axis ## i am going to add color ## i am adding title to the graph import matplotlib.pyplot as plot print('i am going to draw a simple graph') x_axis = [10, 20, 30, 40, 66, 89] y_axis = [2.2, 1.1, 0, 3, -9, 99] plot.plot(x_axis,y_axis, color="blue") plot.xlabel("Number of Routers") plot.ylabel("Distances from Master Router( -ve means inner circle) ") plot.title("some graph silly silly") plot.show()
true
b59d922c989315e331dc682a37a9d48f8bd41ef0
odeyale2016/Pirple_assignment
/card2.py
1,038
4.1875
4
from random import randint, choice def jack_chooses_a_card(suits: dict): """ Program for Card Game """ print(str(randint(1,13)) + " of " + str(choice(suits))) def check_help(): # Instructions for the help multiline_str = """Welcome to Pick a Card Game. To play the game, follow the instruction below. 1. Enter your name at the begining of the program. 2. press Enter to continue... 3. Pick a Card.""" print("Game Instruction: \n" + multiline_str) if __name__ == "__main__": suits = ["Spades", "Hearts", "Diamonds", "Clubs"] player_name= input(str("Enter your name: " )) print("It's "+player_name+"'s turn") print("Just press [ENTER] to get started") user_input = input("") if(user_input == '--help'): check_help() print("Just type [--resume] to Resume the Game") while user_input == "": jack_chooses_a_card(suits) user_input = input("\nTo run again press [ENTER] key, entering anything else would terminate the program\n")
true
801d9ab6b31011ff1783ec489e3d150c5c79f44a
rlowrance/re-local-linear
/x.py
2,216
4.15625
4
'''examples for numpy and pandas''' import numpy as np import pandas as pd # 1D numpy arrays v = np.array([1, 2, 3], dtype=np.float64) # also: np.int64 v.shape # tuple of array dimensions v.ndim # number of dimensions v.size # number of elements for elem in np.nditer(v): # read-only iteration pass for elem in np.nditer(v, op_flags='readwrite'): # mutation iteration elem[...] = abs(elem) # elipses is required for elems in np.nditer(v, flags=['external_loop']): # iterate i chunks print elems # elems is a 1D vector # basic indexing (using a slice or integer) ALWAYS generates a view v[0:v.size:1] # start:stop:step v[10] v[...] # advanced indexing (using an ndarray) ALWAYS generates a copy # advanced indexes are always broadcast v[np.array([1, 2])] # return new 1D with 2 elements v[~np.isnan(v)] # return new 1D with v.size elements # pd.Index # data: aray-like 1D of hashable items # dtype: np.dtype # copy: bool default ? # name: obj, documentation # tupleize_cols: bool, default True; if True, attempt to create MultiIndex i = pd.Index(data, dtype, copy, name, tupleize_cols) i.shape i.ndim i.size i.values # underlying data as ndarray # generally don't apply methods directly to Index objects # pd.Series # data: array-like, dict, scalar # index: array-like, index # dtype: numpy.dtype # copy: default False (True forces a copy of data) s = pd.Series(data, index, dtype, name, copy) s.values # return ndarray s.shape s.ndim s.size # indexing and iteration s.get(key[,default]) # key: label s.loc[key] # key: single label, list or array of labels, slice with labels, bool array s.iloc[key] # key: int, list or array of int, slice with ints, boolean array s.iteritems() # iterate over (index, value) pairs # pd.DataFrame: # data: numpy ndarray, dict, DataFrame # index: index or array-like # columns: index or array-like # dtype: nparray dtype # copy: boolean default False df = pd.DataFrame(data, index, columns, dtype, copy) df.shape df.ndim df.size df.as_matrix([columns]) # convert to numpy array df.loc[key] # key: single lable, list or array of labels, slice of labels, bool array df.iloc[key] # key: int, list or array of int, slice of int, bool array
true
b5df893cc27a870952f800153e355c44610c2cca
jemg2030/Retos-Python-CheckIO
/INITIATION/IsEven.py
1,082
4.34375
4
''' Check if the given number is even or not. Your function should return True if the number is even, and False if the number is odd. Input: An integer. Output: Bool. Example: assert is_even(2) == True assert is_even(5) == False assert is_even(0) == True How it’s used: (math is used everywhere) Precondition: given int should be between -1000 and 1000 ---------- ---------- Registra si el número dado es par o no. Su función debe devolver True si el número es par, y False si el número es impar. Entrada: Un número entero. Salida: Bool. Ejemplo: assert es_par(2) == Verdadero assert es_par(5) == Falso assert es_par(0) == Verdadero Cómo se usa: (las matemáticas se usan en todas partes) Precondición: el int dado debe estar entre -1000 y 1000 ''' def is_even(num: int) -> bool: # your code here return num % 2 == 0 print("Example:") print(is_even(2)) # These "asserts" are used for self-checking assert is_even(2) == True assert is_even(5) == False assert is_even(0) == True print("The mission is done! Click 'Check Solution' to earn rewards!")
false
72e53cf5497ee8a69bde468b3d2ad05374978e4a
jemg2030/Retos-Python-CheckIO
/INCINERATOR/OOP4AddingMethods.py
2,031
4.4375
4
""" 4.1. Add the working_engine class attribute inside the Car class and assign it a value of False. 4.2. Add a start_engine method to the Car class, that displays the message "Engine has started" and changes the working_engine value of the instance of class to True. 4.3. Add a stop_engine method to the Car class, that displays the message "Engine has stopped" and changes the working_engine value of the instance of class to False. 4.4. Call the start_engine method for both instances some_car1, some_car2. ---------- ---------- 4.1. Añade el atributo de clase working_engine dentro de la clase Car y asígnale el valor False. 4.2. Añade un método start_engine a la clase Car, que muestre el mensaje "Engine has started" y cambie el valor de working_engine de la instancia de la clase a True. 4.3. Añadir un método stop_engine a la clase Car, que muestre el mensaje "Engine has stopped" y cambie el valor de working_engine de la instancia de la clase a False. 4.4. Llama al método arrancar_motor para ambas instancias algún_coche1, algún_coche2. """ # Taken from mission OOP 3: Initializing # Taken from mission OOP 2: Class Attributes # Taken from mission OOP 1: First Look at Class and Object # show me some OOP magic here class Car: wheels = "four" doors = 4 working_engine = False def __init__(self, brand="", model=""): self.brand = brand self.model = model def start_engine(self): print("Engine has started") self.working_engine = True def stop_engine(self): print("Engine has stopped") self.working_engine = False # Creating a Car object without passing any additional arguments (using default values) my_car = Car() # Creating two new Car objects with specific arguments some_car1 = Car(brand="Ford", model="Mustang") some_car2 = Car(model="Camaro") # Calling start_engine method for some_car1 and some_car2 some_car1.start_engine() # Output: "Engine has started" some_car2.start_engine() # Output: "Engine has started"
false
758aea129a19502aeacd16c4a89319a1da897513
jemg2030/Retos-Python-CheckIO
/HOME/EvenTheLast.py
2,110
4.125
4
''' You are given an array of integers. You should find the sum of the integers with even indexes (0th, 2nd, 4th...). Then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0. For an empty array, the result will always be 0 (zero). Input: A list of integers. Output: The number as an integer. Example: assert checkio([0, 1, 2, 3, 4, 5]) == 30 assert checkio([1, 3, 5]) == 30 assert checkio([6]) == 36 assert checkio([]) == 0 How it is used: Indexes and slices are important elements of coding. This will come in handy down the road! Precondition: 0 ≤ len(array) ≤ 20 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) --------- --------- Se te da un arreglo de enteros. Deberías encontrar la suma de los elementos con índices pares (0, 2do, 4to... ) luego multiplicar ese resultado con el elmento final del arreglo. No olvides que el primer elemento tiene el índice 0. Para un arreglo vacio, el resultado siempre será 0 (cero). Entrada: Una lista de enteros. Salida: El número como un entero. Ejemplo: assert checkio([0, 1, 2, 3, 4, 5]) == 30 assert checkio([1, 3, 5]) == 30 assert checkio([6]) == 36 assert checkio([]) == 0 Cómo se usa: Índices y fragmentos son elementos importantes de la programación en python y otros lenguajes. Esto se volverá útil en el camino más adelante! Precondición: 0 ≤ len(array) ≤ 20 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) ''' def checkio(array: list[int]) -> int: # your code here if not array: return 0 even_index_sum = sum(array[i] for i in range(0, len(array), 2)) return even_index_sum * array[-1] # These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': print("Example:") print(checkio([0, 1, 2, 3, 4, 5])) assert checkio([0, 1, 2, 3, 4, 5]) == 30 assert checkio([1, 3, 5]) == 30 assert checkio([6]) == 36 assert checkio([]) == 0 print("The mission is done! Click 'Check Solution' to earn rewards!")
true
2614ae144faef13ad3271bf311531cbd671b395e
jemg2030/Retos-Python-CheckIO
/SCIENTIFIC_EXPEDITION/AbsoluteSorting.py
2,639
4.78125
5
''' Let's try some sorting. Here is an array with the specific rules. The array (a list) has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (-20, -5, 10, 15) will be sorted like so: (-5, 10, 15, -20). Your function should return the sorted list or tuple. Precondition: The numbers in the array are unique by their absolute values. Input: An array of numbers , a tuple.. Output: The list or tuple (but not a generator) sorted by absolute values in ascending order. Addition: The results of your function will be shown as a list in the tests explanation panel. Example: assert checkio([-20, -5, 10, 15]) == [-5, 10, 15, -20] assert checkio([1, 2, 3, 0]) == [0, 1, 2, 3] assert checkio([-1, -2, -3, 0]) == [0, -1, -2, -3] How it is used: Sorting is a part of many tasks, so it will be useful to know how to use it. Precondition: len(set(abs(x) for x in array)) == len(array) 0 < len(array) < 100 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) ---------- ---------- Vamos a experimentar con ordenamiento (clasificación). Aquí hay una matriz con normas específicas. El vector (una list) tiene varios números. Debes ordenarla por valor absoluto en orden ascendente. Por ejemplo, la secuencia (-20, -5, 10, 15), queda ordenada de la siguiente forma: (-5, 10, 15, -20). Tu función debe devolver la lista (o tupla) ordenada. Condiciones: Los números de la matriz son únicos por sus valores absolutos. Datos de Entrada: Un conjunto de números, una tupla. Salida: La lista o tupla (pero no un generador) ordenados por valores absolutos en orden ascendente. Adicional: Los resultados de tu función serán presentados como una lista en panel de explicación de pruebas. Ejemplo: assert checkio([-20, -5, 10, 15]) == [-5, 10, 15, -20] assert checkio([1, 2, 3, 0]) == [0, 1, 2, 3] assert checkio([-1, -2, -3, 0]) == [0, -1, -2, -3] ¿Cómo se usa?: La clasificación /ordenamiento es una parte de muchas tareas, por lo que es bastante útil saber cómo se usa. Condiciones: len(set(abs(x) for x in array)) == len(array) 0 < len(array) < 100 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) ''' def checkio(values: list) -> list: # your code here return sorted(values, key=abs) print("Example:") print(checkio([-20, -5, 10, 15])) # These "asserts" are used for self-checking assert checkio([-20, -5, 10, 15]) == [-5, 10, 15, -20] assert checkio([1, 2, 3, 0]) == [0, 1, 2, 3] assert checkio([-1, -2, -3, 0]) == [0, -1, -2, -3] print("The mission is done! Click 'Check Solution' to earn rewards!")
true
ba08876c2201f7ad0783e6df4cc5f16999370969
jemg2030/Retos-Python-CheckIO
/ICE_BASE/NotInOrder.py
1,885
4.28125
4
""" You are given a list of integers. Your function should return the number of elements, which are not at their places as if the list would be sorted ascending. For example, for the sequence [1, 1, 4, 2, 1, 3] the result is 3, since elements at indexes 2, 4, 5 (remember about 0-based indexing in Python) are not at their places as in the same sequence sorted ascending - [1, 1, 1, 2, 3, 4]. Input: List of integers (int). Output: Integer (int). Examples: assert not_order([1, 1, 4, 2, 1, 3]) == 3 assert not_order([]) == 0 assert not_order([1, 1, 1, 1, 1]) == 0 assert not_order([1, 2, 3, 4, 5]) == 0 ---------- ---------- Se le da una lista de enteros. Tu función debe devolver el número de elementos que no están en su lugar como si la lista estuviera ordenada de forma ascendente. Por ejemplo, para la secuencia [1, 1, 4, 2, 1, 3] el resultado es 3, ya que los elementos en los índices 2, 4, 5 (recuerde acerca de la indexación basada en 0 en Python) no están en sus lugares como en la misma secuencia ordenada ascendentemente - [1, 1, 1, 2, 3, 4]. Entrada: Lista de enteros (int). Salida: Entero (int). Ejemplos: assert no_orden([1, 1, 4, 2, 1, 3]) == 3 assert not_order([]) == 0 assert not_order([1, 1, 1, 1, 1]) == 0 assert not_order([1, 2, 3, 4, 5]) == 0 """ def not_order(data: list[int]) -> int: # your code here if not data: return 0 sorted_nums = sorted(data) misplaced_count = 0 for i in range(len(data)): if data[i] != sorted_nums[i]: misplaced_count += 1 return misplaced_count print("Example:") print(not_order([1, 1, 4, 2, 1, 3])) # These "asserts" are used for self-checking assert not_order([1, 1, 4, 2, 1, 3]) == 3 assert not_order([]) == 0 assert not_order([1, 1, 1, 1, 1]) == 0 assert not_order([1, 2, 3, 4, 5]) == 0 print("The mission is done! Click 'Check Solution' to earn rewards!")
false
0b1e36b6d8953235cd853e1827a28ebbc62f5883
jemg2030/Retos-Python-CheckIO
/O_REILLY/SumOfDigits.py
1,522
4.3125
4
''' The task in this mission is as follows: You are given an integer. If it consists of one digit, simply return its value. If it consists of two or more digits - add them until the number contains only one digit and return it. Input: A int. Output: A int. Example: assert sum_digits(38) == 2 assert sum_digits(0) == 0 assert sum_digits(10) == 1 assert sum_digits(132) == 6 --------- --------- La tarea de esta misión es la siguiente: Se le da un número entero. Si consta de un dígito, simplemente devuelva su valor. Si consta de dos o más dígitos, súmelos hasta que el número contenga un solo dígito y devuélvalo. Entrada: Un int. Salida: Un int. Ejemplo: assert suma_dígitos(38) == 2 assert suma_dígitos(0) == 0 assert suma_dígitos(10) == 1 assert suma_dígitos(132) == 6 ''' def sum_digits(num: int) -> int: # your code here # If the num has only one digit, return it if num < 10: return num # If the num has two or more digits, keep adding them until we get a single digit while num >= 10: # Compute the sum of the digits digit_sum = 0 for digit in str(num): digit_sum += int(digit) num = digit_sum return num print("Example:") print(sum_digits(38)) assert sum_digits(38) == 2 assert sum_digits(0) == 0 assert sum_digits(10) == 1 assert sum_digits(132) == 6 assert sum_digits(232) == 7 assert sum_digits(811) == 1 assert sum_digits(702) == 9 print("The mission is done! Click 'Check Solution' to earn rewards!")
false
5f47280efff7921b548de8f213f7e6a07b4138b1
jemg2030/Retos-Python-CheckIO
/HOME/BiggerPrice.py
2,824
4.40625
4
''' You have a list with all available products in a store. The data is represented as a list of dicts Your mission here is to find the most expensive products in the list. The number of products we are looking for will be given as the first argument and the list of all products as the second argument. Input: int and list of dicts. Each dict has the two keys "name" and "price" Output: The same format as the second input argument. Example: assert bigger_price( 2, [ {"name": "bread", "price": 100}, {"name": "wine", "price": 138}, {"name": "meat", "price": 15}, {"name": "water", "price": 1}, ], ) == [{"name": "wine", "price": 138}, {"name": "bread", "price": 100}] assert bigger_price( 1, [{"name": "pen", "price": 5}, {"name": "whiteboard", "price": 170}] ) == [{"name": "whiteboard", "price": 170}] ---------- ---------- Se tiene una lista con todos los productos disponibles en una tienda. Los datos se representan como una lista de dicts Tu misión aquí es encontrar los productos más caros de la lista. El número de productos que buscamos se dará como primer argumento y la lista de todos los productos como segundo argumento. Entrada: int y lista de dicts. Cada dict tiene las dos claves "nombre" y "precio" Salida: El mismo formato que el segundo argumento de entrada. Ejemplo: assert mayor_precio( 2, [ {"nombre": "pan", "precio": 100}, {"nombre": "vino", "precio": 138}, {"nombre": "carne", "precio": 15}, {"nombre": "agua", "precio": 1}, ], ) == [{"nombre": "vino", "precio": 138}, {"nombre": "pan", "precio": 100}] assert mayor_precio( 1, [{"nombre": "bolígrafo", "precio": 5}, {"nombre": "pizarra", "precio": 170}] ) == [{"nombre": "pizarra", "precio": 170}] Traducción realizada con la versión gratuita del traductor www.DeepL.com/Translator ''' def bigger_price(limit: int, data: list[dict]) -> list[dict]: """ TOP most expensive goods """ # your code here return sorted(data, key=lambda x: x['price'], reverse=True)[:limit] print("Example:") print( bigger_price( 2, [ {"name": "bread", "price": 100}, {"name": "wine", "price": 138}, {"name": "meat", "price": 15}, {"name": "water", "price": 1}, ], ) ) assert bigger_price( 2, [ {"name": "bread", "price": 100}, {"name": "wine", "price": 138}, {"name": "meat", "price": 15}, {"name": "water", "price": 1}, ], ) == [{"name": "wine", "price": 138}, {"name": "bread", "price": 100}] assert bigger_price( 1, [{"name": "pen", "price": 5}, {"name": "whiteboard", "price": 170}] ) == [{"name": "whiteboard", "price": 170}] print("The mission is done! Click 'Check Solution' to earn rewards!")
true
483f162dabdd2310a400cadb2abc8ad26faeac62
Chi10ya/UDEMY_SeleniumWithPython
/Sec8_ClassesObjectOrientedPrg.py
2,934
4.8125
5
""" 8: Classes - Object Oriented Programming 45: Understanding objects / classes 46: Create your own object 47: Create your own methods 48: Inheritance 49: Method Overriding 50: Practice exercise with solution """ # 45: Understanding objects / classes # 46: Create your own object class myClass(object): # Inherting the inbuilt object class def __init__(self, make): # __init__ method is used to initialize all the objects which are created to the specific class self.make = make print(self.make) def myName(self, name): print(name) def myCountry(self, countryName): print(countryName) mc = myClass("Puegot") mc.myName("Chaitanya Ambica Yashvir Dhiyanshi") mc.myCountry("IRELAND") # 47: Create your own methods class Car(object): wheels = 4 def __init__(self, make, model): self.make = make self.model = model def info(self): print("Make of the car : "+self.make) print("Model of the car : "+self.model) c1 = Car('Puegot', '880') print(c1.make) print(c1.model) print(Car.wheels) print(c1.wheels) # 48: Inheritance class Cars(object): def __init__(self): print("You just created the car instance") def drive(self): print("Car started") def stop(self): print("Car stopped") class BMW(Cars): def __init__(self): Cars.__init__(self) print("You just create the BMW instance") def headsUpFeature(self): print("Having an headsp feature") c2 = Cars() c2.drive() c2.stop() b1 = BMW() b1.drive() b1.stop() b1.headsUpFeature() # 49: Method Overriding class MyCars(object): print('$'*50) def __init__(self): print("You just created the car instance. It is MyCars class and in __init__") def start(self): print("Car started.... in MyCars class") def stop(self): print("Car stopped.... in MyCars class") class BMW(MyCars): def __init__(self): print("You just create the BMW instance. It is BMW class and in __init__") MyCars.__init__(self) def headsUpFeature(self): print("Having an headsup feature.. in BMW class") def start(self): super().start() print("Hi..Chaitanya, Welcome.. Today you are driving BMW car. It is in BMW class") super().stop() c2 = MyCars() c2.start() c2.stop() b1 = BMW() b1.start() b1.stop() b1.headsUpFeature() b1.start() # 50: Practice exercise with solution #************************************************* # My Practice of Classes & Objects class empInfo(object): def set_emp_details(self, empno, ename): self.empNo = empno self.empName = ename def get_emp_details(self): return self.empNo, self.empName objEmp = empInfo() objEmp.set_emp_details(7224, "Chaitanya") empNo, empName = objEmp.get_emp_details() print("Employee Number : "+str(empNo)) print("Employee Name : "+empName)
true
4bf52edd8b443fde14901d5522921ac8f599679f
stanisbilly/misc_coding_challenges
/decompress.py
1,981
4.1875
4
''' Decompress a compressed string, formatted as <number>[<string>]. The decompressed string should be <string> written <number> times. Example input: 3[abc]4[ab]c Example output: abcabcabcababababc Number can have more than one digit. For example, 10[a] is allowed, and just means aaaaaaaaaa One repetition can occur inside another. For example, 2[3[a]b] decompresses into aaabaaab Characters allowed as input include digits, small English letters and brackets [ ]. Digits are only to represent amount of repetitions. Letters are just letters. Brackets are only part of syntax of writing repeated substring. Input is always valid, so no need to check its validity. source: https://techdevguide.withgoogle.com/resources/compress-decompression/ ''' import re pattern = r'\d+\[[a-zA-Z]*\]' pattern_with_group = r'(\d+)\[([a-zA-Z]*)\]' # same as above, but grouped def repeatstr(strin): m = re.match(pattern_with_group, strin) return int(m.groups()[0]) * m.groups()[1] def decompress(strin): matches = re.findall(pattern, strin) while len(matches) > 0: for m in matches: strin = re.sub(m.replace('[','\\[').replace(']','\\]'), repeatstr(m), strin, 1) matches = re.findall(pattern, strin) return strin def run_tests(): tests = [ ('abc', 'abc'), ('3[a]', 'aaa'), ('a3[b]', 'abbb'), ('xyz3[]2[b]', 'xyzbb'), ('3[a]2[b]1[c]0[d]', 'aaabbc'), ('xyz3[a]2[b]1[c]', 'xyzaaabbc'), ('xyz3[a]2[b]zzz', 'xyzaaabbzzz'), ('3[2[a]c]', 'aacaacaac'), ('3[2[a]2[b]c]', 'aabbcaabbcaabbc'), ('z3[2[a]c]z', 'zaacaacaacz'), ('1[1[1[1[1[a]]]]]', 'a'), ('x1[1[1[1[1[a]]]]2[b]]x', 'xabbx'), ('a100[50[]]2[bxyz]10000[]c', 'abxyzbxyzc'), ('10[a]0[b]100[c]', 10*'a'+ 0*'b' + 100*'c') ] for t in tests: td = decompress(t[0]) print(td == t[1], ',', t[0],'-->', td) if __name__ == '__main__': run_tests()
true
b26f56ad13ac9c603fe51fe969c4ee54b81b4687
bermec/challenges
/challenges_complete/challenge182_easydev10.py
2,146
4.4375
4
''' (Easy): The Column Conundrum Text formatting is big business. Every day we read information in one of several formats. Scientific publications often have their text split into two columns, like this. Websites are often bearing one major column and a sidebar column, such as Reddit itself. Newspapers very often have three to five columns. You've been commisioned by some bloke you met in Asda to write a program which, given some input text and some numbers, will split the data into the appropriate number of columns. Formal Inputs and Outputs Input Description To start, you will be given 3 numbers on one line: <number of columns> <column width> <space width> number of columns: The number of columns to collect the text into. column width: The width, in characters, of each column. space width: The width, in spaces, of the space between each column. After that first line, the rest of the input will be the text to format. Output Description You will print the text formatted into the appropriate style. You do not need to account for words and spaces. If you wish, cut a word into two, so as to keep the column width constant. Sample Inputs and Outputs Sample Input Input file is available here. (NB: I promise this input actually works this time, haha.) Sample Output Outout, according to my solution, is available here. I completed the Extension challenge too - you do not have to account for longer words if you don't want to, or don't know how. ''' if __name__ == "__main__": import re format_style = [4, 25, 1] lst = [] with open('loren_ipsum.txt', 'r') as f: for line in f: line = line.rstrip() lst.append(line) lsts = re.findall('.{25}', lst[0]) #print(lsts) x = 0 y = x while y < 10: temp = lsts[x] print('{0}{1:<26}'.format(x, lsts[x]), end='') x += 10 print('{0}{1:<26}'.format(x, lsts[x]), end='') x += 10 print('{0}{1:<26}'.format(x, lsts[x]), end='') x += 10 print('{0}{1:<26}'.format(x, lsts[x]), end='') print('\n') y += 1 x = y
true
bbc20d6705ef01287e574deca25e2e6c1497b87e
bermec/challenges
/challenge75_easy.py
2,182
4.125
4
''' Everyone on this subreddit is probably somewhat familiar with the C programming language. Today, all of our challenges are C themed! Don't worry, that doesn't mean that you have to solve the challenge in C, you can use whatever language you want. You are going to write a home-work helper tool for high-school students who are learning C for the first time. These students are in the advanced placement math course, but do not know anything about programming or formal languages of any kind. However, they do know about functions and variables! They have been given an 'input guide' that tells them to write simple pure mathematical functions like they are used to from their homework with a simple subset grammar, like this: f(x)=x*x big(x,y)=sqrt(x+y)*10 They are allowed to use sqrt,abs,sin,cos,tan,exp,log, and the mathematical arithmetic operators +*/-, they can name their functions and variables any lower-case alphanumeric name and functions can have between 0 and 15 arguments. In the this challenge, your job is to write a program that can take in their "simple format" mathematical function and output the correct C syntax for that function. All arguments should be single precision, and all functions will only return one float. As an example, the input L0(x,y)=abs(x)+abs(y) should output float L0(float x,float y) { return fabsf(x)+fabsf(y); } Bonus points if you support exponentiation with "^", as in "f(x)=x^2" ''' import re def math_to_c(inpstr): (f, body) = inpstr.split('=') for op in ['exp', 'log','sqrt','abs','sin','cos','tan']: body = body.replace(op, op+"f") body = body.replace("absf", "fabsf") for m in re.compile(".*(([\w+])\^([\d+])).*").finditer(body): body = body.replace(m.group(1), "expf(" + m.group(2) + "," + m.group(3) + ")") (name, args) = f.split('(') sig = name + "(" argsplit = args.strip().split(',') for i in range(len(argsplit)): sig += "float " + argsplit[i] if i != len(argsplit) - 1: sig += ", " return "float " + sig + " {\n return " + body + ";\n}" if __name__ == "__main__": print(math_to_c("L0(x,y)=abs(x)+abs(y)+x^2"))
true
f40424fe68b14466ea96ab54d934bf3795c312a1
nnicha123/Python-tutorial
/cofee/coffee1.py
266
4.125
4
print('Write how many cups of coffee you will need:') cups = input() print(f'For {cups} cups of coffee you will need:') water = 200 * int(cups) milk = 50 * int(cups) beans = 15 * int(cups) print(f'''{water} ml of water {milk} ml of milk {beans} g of coffee beans''')
false
f11d708155799e063007143742985ddc376c4d01
AvneetHD/little_projects
/Time Converter.py
524
4.28125
4
def minutes_to_seconds(x): x = int(x) x = x * 60 print('{} seconds.'.format(x)) def hours_to_seconds(x): x = int(x) x = (x * 60) * 60 print('{} seconds'.format(x)) direction = input('Do you want to convert hours to seconds. Y/N.') direction2 = input('Do you want to convert minutes to seconds. Y/N.') if direction == 'Y' or direction == 'yes': hours = input('') hours_to_seconds(hours) if direction2 == 'Y' or direction == 'yes': minutes = input('') minutes_to_seconds(minutes)
true
7c7c402f239d4aa58c9f0359fc9e0150d6dd49cd
melbinmathew425/Core_Python
/advpython/oop/quantifiers/rule5.py
213
4.15625
4
import re x="a{1,3}"#its print the group or individualy, when its no of 'a' is in between {1,3} r="aaa abc aaaa cga" matcher=re.finditer(x,r) for match in matcher: print(match.start()) print(match.group())
true
94a0d3a42611f0bc9ca677c2e70cdfcadd6e2daf
tabrezi/SBLC
/Exp12.py
385
4.25
4
''' Program to demonstrate series and dataframe in Pandas ''' import pandas as pd #Series ''' Theory about Series ''' s = pd.Series([10,20,30,40,50]) print(s) print(s[0]) #some slicing, indexing, other features of Series #Dataframe ''' Theory about Dataframe ''' #some slicing, indexing, other features of Dataframe #Dataframe operations using csv dataset
false
89f0c05070f4b6f6fe4485376461e8b309289a4c
Turjo7/Python-Revision
/car_game.py
688
4.15625
4
command = "" started = False # while command != "quit": while True: command = input("> ").lower() if command == "start": if started: print("The Car Already Started: ") else: started = True print("The Car Started") elif command == "stop": if not started: print("The Car Already Stoped: ") else: started= False print("The Car Stopped") elif command == "help": print(f''' start- to start the car stop- to stop the car help- to see help ''') elif command == "quit": break else: print("Can not understand: ")
true
30cd1ebf47edc12c42c6383e4d84c35326dee8fd
sdmgill/python
/Learning/range_into_list.py
312
4.21875
4
#putting a range into a list print("Here is my range placed into a list:") numbers = list(range(1,6)) print(numbers) #putting a range into a list and grab only even numbers print("\nHere is my even list / range:") even_numbers=list(range(2,11,2)) #start with 2, go to 11(10), increment by 2 print(even_numbers)
true
6afa0ebf1d665a64a0a4a7277b18f1ce442c92cf
sdmgill/python
/Learning/7.1-Input.py
894
4.375
4
message = input("Tell me something and I will repeat it back to you: ") print(message) name = input("Please enter your name: ") print("Hello " + name.title()) # building a prompt over several lines prompt = "This is going to be a very long way of asking " prompt += "you what you name is. So..................." prompt += "waht's your name?" name = input(prompt) print("Hello " +name.title()) # input returns everything as a string so we need to convert when evaluating numbers height = input("How tall are you in inches?") height = int(height) if height > 36: print("\nYou are tall enough to ride!") else: print("You are a small fucker!") # Modulo number = input("Enter a number and I will tell you if it is even or odd:") number = int(number) if number % 2 == 0: print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " is odd.")
true
def46f78814c9ca4e28e153774d8a9d668f78463
fander2468/week2_day2_HW
/lesser_then.py
443
4.34375
4
# Given a list as a parameter,write a function that returns a list of numbers that are less than ten # For example: Say your input parameter to the function is [1,11,14,5,8,9]...Your output should [1,5,8,9] my_list = [1,2,12,14,5,6,77,8,22,3,10,13] def lesser_than_ten(numbers): new_list = [] for number in numbers: if number < 10: new_list.append(number) return new_list print(lesser_than_ten(my_list))
true
ed8f4819a364d77fdda527f9f6ad69bc45e7b8dd
tyler7771/learning_python
/recursion.py
2,625
4.21875
4
# Write a recursive method, range, that takes a start and an end # and returns an list of all numbers between. If end < start, # you can return the empty list. def range(start, end): if end < start: return [] result = range(start, end - 1) result.insert(len(result), end) return result # print range(1,100) # Write both a recursive and iterative version of sum of an list. def sum_iter(list): sum = 0 for num in list: sum += num return sum # print sum_iter([1,2,3,4,5]) def sum_rec(list): if len(list) == 0: return 0 num = list.pop() result = sum_rec(list) + num return result # print sum_rec([1,2,3,4,5]) # Write a recursive and an iterative Fibonacci method. The method should # take in an integer n and return the first n Fibonacci numbers in an list. # You shouldn't have to pass any lists between methods; you should be # able to do this just passing a single argument for the number of Fibonacci # numbers requested. def fib_iter(n): if n == 0: return [] elif n == 1: return [1] else: result = [1, 1] while len(result) < n: result.append(result[-2] + result[-1]) return result # print fib_iter(1) # print fib_iter(2) # print fib_iter(3) # print fib_iter(4) # print fib_iter(5) def fib_rec(n): if n == 0: return [] elif n == 1: return [1] elif n == 2: return [1, 1] result = fib_rec(n - 1) result.insert(len(result), (result[-2] + result[-1])) return result # print fib_rec(1) # print fib_rec(2) # print fib_rec(3) # print fib_rec(4) # print fib_rec(5) # Write a recursive binary search: bsearch(array, target). Note that binary # search only works on sorted arrays. Make sure to return the location of the # found object (or nil if not found!). Hint: you will probably want to use # subarrays. def bsearch(list, target): if len(list) == 0: return None mid = len(list) / 2 if list[mid] == target: return mid elif list[mid] > target: return bsearch(list[0:mid], target) elif list[mid] < target: result = bsearch(list[(mid + 1):(len(list))], target) if result == None: result = None else: result += (mid + 1) return result # print bsearch([1, 2, 3], 1) # => 0 # print bsearch([2, 3, 4, 5], 3) # => 1 # print bsearch([2, 4, 6, 8, 10], 6) # => 2 # print bsearch([1, 3, 4, 5, 9], 5) # => 3 # print bsearch([1, 2, 3, 4, 5, 6], 6) # => 5 # print bsearch([1, 2, 3, 4, 5, 6], 0) # => nil # print bsearch([1, 2, 3, 4, 5, 7], 6) # => nil
true
1df55414bfbee7b20e79850c101f4a18bbdc91b5
abhinavnarra/python
/Python program to remove to every third element until list becomes empty.py
646
4.375
4
# Python program to remove to every third element until list becomes empty def removeThirdNumber(int_list): # list starts with 0 index pos = 3 - 1 index = 0 len_list = (len(int_list)) # breaks out once the list becomes empty while len_list > 0: index = (pos + index) % len_list#for first iteration 2%3 remainder 2 so element in 2nd index will be deleted and it will be continued untill the list become empty. # removes and prints the required element print(int_list.pop(index)) len_list -= 1 nums = [1, 2, 3, 4] removeThirdNumber(nums)
true
018618289d9e3c9d984aef740fa362be4af586c7
abhinavnarra/python
/Demonstrate python program to input ‘n’ employee number and name and to display all employee’s information in ascending order based upon their number - dictionary method.py
716
4.5625
5
#Demonstrate python program to input ‘n’ employee number and name and to display all employee’s information in ascending order based upon their number - dictionary method. dict1={} dict2={} No_of_employees=int(input("Enter No of Employees:"))#enter number of employees to be sorted for i in range(1,No_of_employees+1): emp_id=input("Enter id:") name=input("Enter name:") dict1[emp_id]=name#storing the elements in a dictionary print(dict1)#unsorted dictionary for i in sorted(dict1.keys()):#printing the employee number and name and to display all employee’s information in ascending order based upon their number . dict2[i]=dict1[str(i)] print(dict2)#sorted dictionary
true
2f9607ab1c2e61d71cc16ec72e5caaf03fb25de3
szeitlin/interviewprep
/make_anagrams.py
824
4.3125
4
#!/bin/python3 import os # Complete the makeAnagram function below. def make_anagram(a:str, b:str) -> int: """ Count number of characters to delete to make the strings anagrams :param a: a string :param b: another string :return: integer number of characters to delete """ b_list = [y for y in b] overlap, extra = [], [] for i,char in enumerate(a): if char in b_list: overlap.append(char) b_list.remove(char) else: extra.append(char) print("overlap:{}".format(overlap)) print("extra:{}".format(extra)) return len(extra + b_list) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') a = input() b = input() res = make_anagram(a, b) fptr.write(str(res) + '\n') fptr.close()
true
81c57b9e4c681f24c467d8657548fc002739c647
nikointhehood/unix-101
/lesson-1/subject/exercises/exercise-0/biggest.py
820
4.3125
4
#! /usr/bin/python3 import sys # This import allows us to interact with the command line arguments # First, we declare a function which will do the comparison job def biggest(int1, int2): if int1 > int2: print(int1) elif int2 > int1: print(int2) else: print("The integers are equal") # Let's try get the command line arguments try: if len(sys.argv) != 3: # Actually, the target value is 3 because the first element of argv is always the name of the script print("Usage: ./biggest.py integer1 integer2") else: first_int = int(sys.argv[1]) second_int = int(sys.argv[2]) # Now, call the function with the arguments previously retrieved biggest(first_int, second_int) except ValueError: print("Usage: ./biggest.py integer1 integer2")
true
03075897173f9640dc3e56e7545f65d7e7ae04b7
utkarshpal11/w3resource_python__class_solutions
/09.power.py
273
4.25
4
# Write a Python class to implement pow(x, n). class Power: def power(self, x, n): return print("power {x} to {n} is {output}".format(x=x, n=n, output=x**n)) p = Power() p.power(7, 3) p.power(7, -3) p.power(7, 0) p.power(7, 10) p.power(-6, 3)
false
38a378e9ccfc27479b43a229088ff02031a9bad3
bsk17/PYTHONTRAINING1
/databasepack/dbClientdemo.py
2,901
4.4375
4
import sqlite3 # create connection to the db conn = sqlite3.connect("mydb") # for server side programming we have change the connection # line and we have to mention the varchar(size) mycursor = conn.cursor() # function to create the table def createTable(): print("*" * 40) sql = '''create table if not exists student(name varchar, email varchar primary key, mobile varchar , password varchar )''' try: mycursor.execute(sql) print("Table Created") except: print("Something went wrong") # function to insert data def insertData(): print("*" * 40) name = input("Enter name - ") email = input("Enter email - ") mobile = input("Enter mobile - ") password = input("Enter password - ") sql = "insert into student values('" + name + "', '" + email + "', '" + mobile + "', '" + password + "')" try: mycursor.execute(sql) print("Data inserted") except: print("something went wrong") # function to update data def updateData(): print("*" * 40) email = input("Enter email - ") newmobile = input("Enter New mobile - ") sql = "update student set mobile ='" + newmobile + "' where email='" + email + "'" try: mycursor.execute(sql) print("Mobile updated succesfully") except: print("Something went wrong") # function to show the data def showData(): sql = "select * from student" mycursor.execute(sql) for row in mycursor.fetchall(): print(row[0], row[1], row[2], row[3]) # function to delete the data def deleteData(): print("*" * 40) email = input("Enter email - ") sql = "delete from student where email='" + email + "'" try: mycursor.execute(sql) print("Data deleted") except: print("Data deleted succesfully") # function to login def login(): print("*" * 40) email = input("Enter email - ") password = input("Enter password - ") sql = "select * from student where email='" + email + "' and password='" + password + "'" mycursor.execute(sql) if len(mycursor.fetchall()) == 0: print("Could not login") else: print("Login Succesful") sql = "select * from student where email='" + email + "'" mycursor.execute(sql) for row in mycursor.fetchall(): print(row[0], row[1], row[2], row[3]) while True: print("1. Create Table\n2. Insert Data\n3. Update Data\n4. Delete Data\n5. Show Data\n6. Login\n7. Exit") ch = eval(input("Enter Your Choice")) if ch == 1: createTable() elif ch == 2: insertData() elif ch == 3: updateData() elif ch == 4: deleteData() elif ch == 5: showData() elif ch == 6: login() elif ch == 7: conn.close() exit() else: print("Wrong choice") conn.commit()
true
a361f51e6cda567cf1bf3705c2f831bc099e5c50
CCedricYoung/bitesofpy
/263/islands.py
1,293
4.28125
4
def count_islands(grid): """ Input: 2D matrix, each item is [x, y] -> row, col. Output: number of islands, or 0 if found none. Notes: island is denoted by 1, ocean by 0 islands is counted by continuously connected vertically or horizontally by '1's. It's also preferred to check/mark the visited islands: - eg. using the helper function - mark_islands(). """ islands = 0 # var. for the counts queue = {(i,j) for i in range(len(grid)) for j in range(len(grid[0]))} while len(queue) > 0: i, j = queue.pop() if grid[i][j] != 1: continue mark_islands(i, j, grid, queue) islands += 1 return islands def mark_islands(i, j, grid, queue): """ Input: the row, column, grid and queue Output: None. Side-effects: Grid marked with visited islands. Visited paths removed from queue. """ grid[i][j] = '#' DIRECTIONS = [(1, 0), (-1, 0), (0,1), (0,-1)] paths = [(i + d[0], j + d[1]) for d in DIRECTIONS] for path in paths: if path not in queue or grid[path[0]][path[1]] == 0: continue queue.remove(path) grid[path[0]][path[1]] = '#' mark_islands(*path, grid, queue)
true
d76a5bd18aba73166c47dafdc06d5bdede28118b
sumitbatwani/python-basics
/conditions.py
791
4.28125
4
# - if-elif-else - # is_hot = True # is_cold = False # if is_hot: # print("It is a hot day") # elif is_cold: # print("It is a cold day") # else: # print("It is a good day") # Another example # price = 1000000 # has_good_credit = False # if has_good_credit: # print(f"Down Payment ${price * (10 / 100)}") # else: # print(f"Down Payment ${price * (20 / 100)}") # - Comparison Operator - # name = "Sumit" # if len(name) < 3: # print("Name is less than valid input") # elif len(name) > 10: # print("Name is more than valid input") # else: # print("Name looks perfect!") # - WHILE loop - # i = 1 # while i < 5: # print(i) # i = i + 1 # print("Done") # - Another Example (Pattern Problem) - # i = 1 # while i < 5: # print("*" * i) # i = i + 1
false
be7a281f69933d5a719d3ea23cfa64e2c07786ed
sumitbatwani/python-basics
/lists.py
879
4.25
4
# - List - # names = ["John", "Sarah", "Aman"] # print(names[1:2]) # names[start: exclusion_end] # - Largest number in a list - # numbers = [5, 1, 2, 4, 3] # largest_number = numbers[0] # for item in numbers: # if item > largest_number: # largest_number = item # print(f"largest number = {largest_number}") # 2D List # ''' # matrix = [ # [1, 2, 3], # [4, 5, 6], # [7, 8, 9] # ] # ''' # matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # for row in matrix: # for item in row: # print(item) # Remove duplicate from a list # list_of_numbers = [1, 2, 3, 4, 5, 5, 1] # for number in list_of_numbers: # if list_of_numbers.count(number) > 1: # list_of_numbers.remove(number) # print(list_of_numbers) # or # uniques = [] # for number in list_of_numbers: # if number not in uniques: # uniques.append(number) # print(uniques)
true
bea8ea16bf04b705c4558705e2333bfb2ec8f840
avengerweb/gb-ml
/lesson7/task_1.py
916
4.28125
4
# 1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, заданный случайными числами на # промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Сортировка должна быть реализована в # виде функции. По возможности доработайте алгоритм (сделайте его умнее). import random def bubble_sort_reverse(array): n = 1 while n < len(array): for i in range(len(array) - n): if array[i] < array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] n += 1 return array array = [random.randint(-100, 100) for _ in range(10)] print(array) bubble_sort_reverse(array) print(array)
false
d5db81ef1b7b4886f39d93a916c9c85d23a148ba
Ali-Fani/Theory
/2/assignment2-n-gon.py
623
4.28125
4
import turtle from math import pi, sin, cos t = turtle.Turtle() t.speed(2) t.shape("turtle") t.penup() def draw(side: int, radius: int): for num in range(side + 1): angel = num * 360 / side print(f"slide angle is {angel}") if num: t.pendown() y = sin(angel * pi / 180) * radius x = cos(angel * pi / 180) * radius t.setheading(t.towards(x, y)) t.setpos(x, y) m = 30 scope = 0 for i in range(3, m): print(f"index is {i}") scope = i * 10 + scope * .4 print(f"scope is {scope}") draw(i, scope) t.penup() t.Screen().exitonclick()
false
bc016336933f66d8ec6af96eb078859b7640ac85
lindaspellman/CSE111
/W10 Handling Exceptions/class_notes.py
821
4.125
4
import math def main(): ## program driver - GOAL: Keep lean ## prompt user for how many circles they have numberOfCircles = int(input("How many circles are we working with? ")) areasList = loopForCircles(numberOfCircles) displayAreas(areasList) ## display each area: separate print statements or a list? def displayAreas(areasList): areasList = [round(i, 2) for i in areasList] print(areasList) def loopForCircles(numberOfCircles): circleAreas = [] ## loop x times: compute area for each circle for _ in range(numberOfCircles): ## get radius for each circle r = float(input("Please enter the radius: ")) circleAreas.append(computeCircleArea(r)) return circleAreas def computeCircleArea(radius): ## compute and return circle area return math.pi * radius**2 if __name__ == '__main__': main()
true
8fc705fb1acb9075ed389a6d979a4f7435e5595f
lindaspellman/CSE111
/W12 Using Objects/team_asgmt/number_entry.py
2,887
4.28125
4
"""This module contains two classes, IntEntry and FloatEntry, that allow a user to enter an integer or a floating point number. """ import tkinter as tk class IntEntry(tk.Entry): """An Entry widget that accepts only integers between a lower and upper bound. """ def __init__(self, parent, lower_bound, upper_bound, **kwargs): super().__init__(parent) if lower_bound > 1: lower_bound = 1 if upper_bound < -1: upper_bound = -1 self.lower_bound = lower_bound self.upper_bound = upper_bound if "justify" not in kwargs: kwargs["justify"] = "right" if "width" not in kwargs: kwargs["width"] = max(len(str(lower_bound)), len(str(upper_bound))) kwargs["validate"] = "key" kwargs["validatecommand"] = (parent.register(self.validate), "%P") self.config(**kwargs) def validate(self, value_if_allowed): valid = False try: i = int(value_if_allowed) valid = (str(i) == value_if_allowed and self.lower_bound <= i and i <= self.upper_bound) except: valid = (len(value_if_allowed) == 0 or (self.lower_bound < 0 and value_if_allowed == "-")) return valid def get(self): """Return the integer that the user entered.""" return int(super().get()) def set(self, n): """Display the integer n for the user to see.""" self.delete(0, tk.END) self.insert(0, str(int(n))) class FloatEntry(tk.Entry): """An Entry widget that accepts only numbers between a lower and upper bound. """ def __init__(self, parent, lower_bound, upper_bound, **kwargs): super().__init__(parent) if lower_bound > 0: lower_bound = 0 if upper_bound < 0: upper_bound = 0 self.lower_bound = lower_bound self.upper_bound = upper_bound vcmd = (parent.register(self.validate), "%P") if not "justify" in kwargs: kwargs["justify"] = "right" if not "width" in kwargs: kwargs["width"] = max(len(str(lower_bound)), len(str(upper_bound))) self.config(validate="key", validatecommand=vcmd, **kwargs) def validate(self, value_if_allowed): valid = False try: i = float(value_if_allowed) valid = (self.lower_bound <= i and i <= self.upper_bound) except: valid = (len(value_if_allowed) == 0 or (self.lower_bound < 0 and value_if_allowed == "-")) return valid def get(self): """Return the number that the user entered.""" return float(super().get()) def set(self, n): """Display the number n for the user to see.""" self.delete(0, tk.END) self.insert(0, str(float(n)))
false
186d3639f0c8109d68ad43f442bc6bc49338550a
Techbanerg/TB-learn-Python
/10_MachineLearning/example_numpy.py
2,359
4.34375
4
# NumPy is the fundamental Python package for scientific computing. It adds the capabilities of N-dimensional arrays, element-by-element operations (broadcasting), core # mathematical operations like linear algebra, and the ability to wrap C/C++/Fortran code.We will cover most of these aspects in this chapter by first covering # The NumPy package enables users to overcome the shortcomings of the Python lists by providing a data storage object called ndarray. The ndarray is similar to lists, # but rather than being highly flexible by storing different types of objects in one list, only the same type of element can be stored in each column. For example, # with a Python list, you could make the first element a list and the second another list or dictionary. With NumPy arrays, you can only store the same type of # element, e.g., all elements must be floats, integers, or strings. Despite this limitation, ndarray wins hands down when it comes to operation times, as the # operations are sped up significantly. Using the time's magic command in IPython, we compare the power of NumPy ndarray versus Python lists in terms of speed. #!/usr/bin/Python3 import numpy as np #array1 = np.arange(1e7) #array2 = array1.tolist() #print(array1, array2) arr1 = np.arange(15).reshape(3, 5) arr2 = [[0,1,2],[4,5,6]] # The ndarray operation is ∼ 25 faster than the Python loop in this example. Are you convinced that the NumPy ndarray is the way to go? From this point on, we will be # working with the array objects instead of lists when possible. Should we need linear algebra operations, we can use the matrix object, which does not # use the default broadcast operation from ndarray. For example, when youmultiply two equally sized ndarrays, which we will denote as A and B, the ni, j element of A is only # multiplied by the ni, j element of B. When multiplying arr4 = np.zeros((2,2)) matrix_arr = np.matrix(arr4) arr3 = np.arange(1000) # Matrix Multiplication arr5 = np.arange(100).reshape(10, 10) arr6 = np.arange(200).reshape(10, 20) result = arr5.dot(arr6) # creating 5x5x5 cube of 1's cube_array = np.ones((5,5,5)).astype(np.float16) print("{} \n {} \n {} \n {} \n {}".format(arr1, arr2, cube_array, matrix_arr, result)) print(" shape : {0} dimension: {1} type: {2} itemsize: {3}".format(arr1.shape, arr1.ndim, arr1.dtype, arr1.itemsize ))
true
f944c425973b7e81855743e7804ab96189e84a3a
Techbanerg/TB-learn-Python
/00_Printing/printing.py
1,708
4.34375
4
# This exercise we are going to print single line and multi line comments # The following examples will help you understand the different ways of # printing import pprint from tabulate import tabulate from prettytable import PrettyTable print ("Mary had a little lamb") print ("Its Fleece was white as %s ." % 'snow') print('Mercury', 'Venus', 'Earth', sep=', ', end=', ') print('Mars', 'Jupiter', 'Saturn', sep=', ', end=', ') print('Uranus', 'Neptune', 'Pluto', sep=', ') # Using Newline Character with extra padding print('Printing in a Nutshell', end='\n * ') print('Calling Print', end='\n * ') print('Separating Multiple Arguments', end='\n * ') print('Preventing Line Breaks') pp =pprint.PrettyPrinter(indent=4, depth=2, width=80) grocery = ['eggs', 'bread', 'milk'] pp.pprint(grocery) print(pprint.isreadable(grocery)) print(tabulate([['Arindam', 50000], ['Shaun', 30000]], headers=['Name', 'Salary'], tablefmt='orgtbl')) table = PrettyTable(['Name', 'PhNo']) table.add_row(['Sourav', 979136789]) table.add_row(['Sachin', 8792798890]) print(table) # String formatting is attractively designing your string using formatting techniques # provided by the particular programming language. We have different string formatting # techniques in Python. We are now going to explore the new f-string formatting technique. # f-string evaluates at runtime of the program. It's swift compared to the previous methods. # f-string having an easy syntax compared to previous string formatting techniques of Python. # We will explore every bit of this formatting using different examples Company = "Wipro" Incentive = "Nothing" print(F"Company {Company} is giving {Incentive} as incentive for year 2020")
true