blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ad7e7ce6b52740b8a0004c78186e3b20dc55dee9
guilhermemalfatti/problems
/subset.py
1,074
4.375
4
''' Subcadeia da soma maxima ---------------------------- Dado um conjunto de numeros, descobrir o subconjunto em que a soma dos elementos sao de maxima soma. Exemplo: dado o conjunto de elementos [2, -4, 6, 8, -10, 100, -6, 5] O subconjunto de soma maxima e: [2, -4, **6, 8, -10, 100**, -6, 5] Assim, o programa deve retornar a posicao do primeiro e do ultimo elemento da subcadeia. Neste exemplo, as posicoes 2 e 5, considerando a primeira posicao com indice 0. ''' def soma(indexa, indexb, list): ''' soma: function to sum a range of list ''' sum = 0 for i in range(indexa, indexb + 1): sum += list[i] return sum def main(): list = [2, -4, 6, 8, -10, 100, -6, 5] items = dict() #logic to create all possbile ranges for i in range(0, len(list)): for j in range(i+1, len(list)): items[str(i) + " - " + str(j)] = soma(i, j, list) maximum = max(items, key=items.get) print "The maximum value is: ", items[maximum], "- with index between", maximum if __name__ == "__main__": main()
false
a300e50e12f563157e5c5d7c06a69ad54c1e590c
KwameKert/algorithmDataStructures
/binarySearch/binSearch1.py
595
4.15625
4
#Binary search using the recursive approach #Time 0(log(n)) | space O(log(n)) def binSearch(array, target): return binSearchHelper(array,target, left= 0,right = len(array)-1) def binSearchHelper(array,target,left,right): if left > right: return -1 middle = (left +right)//2 potentialValue = array[middle] if target == potentialValue: return middle elif target < potentialValue: binSearchHelper(array,target,left, middle -1) else: binSearchHelper(array, target,middle+1,right) result = binSearch([1,2,4,8,9],4) print(result)
true
20b4e8cd2ef814faa0e544a98d3c6a27ebd32e68
adityaks-lts/my_python_scripts
/script2.py
2,816
4.46875
4
#Create a function called every_three_nums that has one parameter named start. #The function should return a list of every third number between start and 100 (inclusive). For example, every_three_nums(91) should return the list [91, 94, 97, 100]. If start is greater than 100, the function should return an empty list. def every_three_nums(start): return list(range(start,101,3)) print(every_three_nums(91)) #Create a function named remove_middle which has three parameters named lst, start, and end. #The function should return a list where all elements in lst with an index between start and end (inclusive) have been removed. #For example, the following code should return [4, 23, 42] because elements at indices 1, 2, and 3 have been removed: #remove_middle([4, 8 , 15, 16, 23, 42], 1, 3) #Write your function heredef remove_middle(lst,start,end): def remove_middle(lst,start,end): lst0 = lst[0:start] lst1 = lst[start:end] lst2 = lst[end+1:] ans = lst0 + lst2 return ans print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3)) #Create a function named more_frequent_item that has three parameters named lst, item1, and item2. #Return either item1 or item2 depending on which item appears more often in lst. #If the two items appear the same number of times, return item1. def more_frequent_item(lst,item1,item2): if lst.count(item1) > lst.count(item2): return item1 elif lst.count(item1) < lst.count(item2): return item2 else: return item1 print(more_frequent_item([2, 3, 3, 2, 3, 2, 3, 2, 3], 2, 3)) # Create a function named double_index that has two parameters: a list named lst and a single number named index. #The function should return a new list where all elements are the same as in lst except for the element at index. The element at index should be double the value of the element at index of the original lst. #If index is not a valid index, the function should return the original list. #For example, the following code should return [1,2,6,4] because the element at index 2 has been doubled: def double_index(lst,index): if index >= len(lst): return lst lst1 = lst[0:index] lst2 = lst[index +1 : ] lst3 = lst[index] * 2 lst1.append(lst3) lst4 = lst1 + lst2 return lst4 #Uncomment the line below when your function is done print(double_index([3, 8, -10, 12], 2)) #Create a function called middle_element that has one parameter named lst. #If there are an odd number of elements in lst, the function should return the middle element. If there are an even number of elements, the function should return the average of the middle two elements. def middle_element(lst): x = len(lst) if x%2 == 0: middle_number = (lst[int(x/2)]+lst[int(x/2) - 1])/2 return middle_number else : middle_number = lst[x//2] return middle_number
true
191ab6ad32c617fbf2a999c31bbfb7d02c754f98
jgloves/graphTheory
/graphic_sequence.py
1,876
4.34375
4
"""The following is an implementation of a recursive algorithm based on a result of Havel(1955) and Hakimi(1961) that decides whether a non-increasing sequence of non-negative integers is a graphic sequence. A graphic sequence is a sequence of integers that is the degree sequence of some simple graph. The degree sequence of a graph is the sequence formed by arranging the graph's vertex degrees in non-increasing order. Reference: Graph Theory and Its Applications, 2nd edition by Gross and Yellen.""" def havel_hakimi(sequence): """Prepares the "next" sequence for graphic_sequence() to test. Note: Returns a sequence that is graphic if and only if the input sequence is graphic. This is necessary for recursion in the graphic_sequence() module. args: sequence: a list of integers returns: another sequence """ n = sequence[0] + 1 for i in range(1, n): sequence[i] = sequence[i] - 1 del sequence[0] return sorted(sequence, reverse=True) def graphic_sequence(sequence): """Determines whether sequence is a graphic sequence. args: sequence: a list of integers returns: True if sequence is a graphic sequence False if sequence is not a graphic sequence """ if sequence[0] == 0: return True else: if sequence[-1] < 0: return False else: if len(sequence) < sequence[0] + 1 : return False else: return graphic_sequence(havel_hakimi(sequence)) if __name__ == "__main__": # some examples for testing graphic_sequence([3, 2, 3, 2, 1, 1]) #True graphic_sequence([2,2,2,2,3,3]) #True graphic_sequence([1, 0]) #False graphic_sequence([0]) #True graphic_sequence([1]) #False graphic_sequence([2,2,2,2]) #True
true
c1ed383d1fda330b097c4bebe329465fb9bd2571
R-Sandor/python2Work
/Chapter 10/petmain.py
425
4.125
4
import pet # Get the pet's name, type, and age name = input("What is your pet's name? ") animal_type = input("What type of animal is that? ") age = input("How old is your pet?") # Create an instance of the Pet class. my_pet = pet.Pet(name, animal_type, age) print("Here is the information you entered:") print("Pet name:", my_pet.get_name()) print("Animal type:", my_pet.get_animal_type()) print("Age:", my_pet.get_age())
true
9aaf7f13472d28b519d107cf37a53a73edce15a6
kakarlaravi/myprojectB12_python-project
/NUMBER SYSTEM.py
904
4.1875
4
# Number system :- Numbers system are used to represent number of symbols r charecters \n\t # used to represent any numerical value. # Binary --------> bin() -------> 0b # Decimal --------> dec() -------> # Octal ---------> oct() -------> 0o # Hexa decimal-----> hex() -------> 0x x = bin(25) print(x) x = 0b01010001 print(x) x = oct(10) print(x) x = bin(31) print(x) x = bin(52) print(x) x = 0b110011 print(x) x = bin(51) print(x) x = 0b1000001 print(x) x = 0b110011010 print(x) x = oct(15) print(x) x = hex(25) print(x) x = 0xf print(x) x = oct(35) print(x) x = bin(0o35) print(x) x = bin(0x65) print(x) x = oct(0b11101) print(x) #x = bin(0o643) #print(x) #x = oct(0b110100011) #print(x) x = bin(0o643) print(x) x = bin(0x643) print(x) x = 0b11001000011 print(hex(x)) x = 0o521 print(hex(x)) x = 0x258 print(oct(x))
false
626ee90b12b17512949c0d128ebccedc0264cd1e
PraveenRaoVP/Programming_Shorts_Codes
/001/001-python-dict-comprehension.py
342
4.28125
4
#We know that we can perform list comprehension like this list_Ex1 = [i for i in range(0,10)] list_Ex2 = [chr(i+65) for i in range(0,10)] #But do you know you can do comprehension like this in dictionary also? #We can do so like : dict_comp_example = {key:value for key, value in zip(list_Ex1,list_Ex2)} print(dict_comp_example)
false
068e658c976430481adacb7af14381a7a8bb12ca
type-coder-engineer/Project-Euler
/pb46.py
993
4.125
4
#coding: utf import time import math def is_prime(nb): if nb > 1: if nb == 2: return True elif nb % 2 == 0: return False for possible in range(3, int(math.sqrt(nb) + 1), 2): if nb % possible == 0: return False return True return False def oddComposite(): n = 8 while(1): if n % 2 == 1 and not is_prime(n): yield n n += 1 def verify(n): test = 1 while(2*test**2 < n): rest = n - 2*test**2 if is_prime(rest): return True else: test += 1 return False def solve(): for one in oddComposite(): # print one # raw_input() if not verify(one): return one else: pass if __name__ == '__main__': start = time.time() print "The answer is {}".format(solve()) end = time.time() print "it took {} seconds".format(end - start)
true
d0cbfa5f728c1f9d978283e3b54c9ed5a3681422
addliu/AT
/Stack.py
1,546
4.34375
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 基础数据结构:栈 用list()实现 class Stack(object): def __init__(self, length): object.__init__(self) self.stack = [object() for index in range(0, length)] self.length = length self.__top__ = 0 # pop函数,出栈操作,删除栈顶元素 def pop(self): if self.is_empty(): print("[Error]:stack under flow!!!") return self.__top__ -= 1 # push函数,入栈操作,将元素压入栈中 def push(self, obj): if self.__top__ >= self.length - 1: print("[Error]:stack over flow!!!") return self.stack[self.__top__] = obj self.__top__ += 1 # 返回栈的信息 def __str__(self): object.__str__(self) string = ("栈长度为:%s" % self.length + '\n') string += "栈中元素如下:\n" for index in range(0, self.__top__): string += str(self.stack[index]) + ', ' # 去除字符串末尾的 ', ' 两个字符 string = string[:-2] string += '\n' string += ("栈顶在第%s个位置" % (self.__top__ + 1) + '\n') return string # 判断栈是否为空 def is_empty(self): if self.__top__ == 0: return True return False if __name__ == '__main__': print("请输入n:") n = int(input()) s = Stack(n) for i in range(0, 10): s.push(i) print(s) for i in range(0, 5): s.pop() print(s)
false
b5882684d6698c37ca54026d40712e28938d9149
Jokekiller/variables
/Convertng someones height and weight.py
445
4.25
4
#Harry Robinson #22/09/2014 #Converting someones height and weight print("This prgramme will convert your height and weight") height = float(input("Give your height in inches; ")) weight = float(input("Give your weight in stones; ")) heightInCentimetres = height * 2.54 weightInKilograms = weight * 6.364 print("Your height in centimetres {0}".format(heightInCentimetres)) print("Your weight in kilograms {0}".format(weightInKilograms))
true
55018e67f9711c7248f5a3215c937ecd57e2921b
kenstratton/cs162_project2
/app_mine/Project1.py
1,923
4.28125
4
# phone from classes import Phone while True: # User input to create an instance print("Input info:") name = input("Your name: ") phone = input("Your phone number: ") if not str.isdigit(phone): print("[!] Phone number should be expressed in figures.\n") continue email = input("Your email address: ") if name and phone and email: phone = Phone(name, phone, email) break else: print("\n*Input of all items is required.") # Instances to provide info for a user to try instance methods p_j = Phone("Joseph", "111", "j@j.com") p_d = Phone("Daniel", "222", "d@d.com") print("\nInfo of imaginary friends:") print("Name: {} PhoneNumber: {} Email: {}".format( p_j.user_name, p_j.phone_num, p_j.email_address)) print("Name: {} PhoneNumber: {} Email: {}".format( p_d.user_name, p_d.phone_num, p_d.email_address)) while True: # User input to manipulate the instance i = input("\nCommand Menu:\n[C]all\n[E]mail\n[H]istory\nE[x]it\n: ").lower() items = ["c", "e", "h", "x", "call", "email", "history", "exit"] if i in items: if i == "call" or i == "c": num = input("\nPut phone number: ") print(phone.call(num)) elif i == "email" or i == "e": address = input("\nPut email address: ") text = input("Text messages:\n") print(phone.email(address, text)) elif i == "history" or i == "h": hist_type = input("[C]all/[E]mail : Which history do you want to check? ").lower() hist_dict = phone.show_history(hist_type) if hist_dict["e"]: print(hist_dict["e"]) else: for hist in hist_dict["hist_lis"]: print(hist) elif i == "exit" or i == "x": print("\nGoobye!\n") break else: print("\n[!] Invalid input on the menu.")
true
5c5aa1ef9c2cc05124ea5e4a70d4ba66621c4216
xiaoyulyu2020/labsheet
/circle_081.py
671
4.21875
4
#!/usr/bin/env python3 class Point(object): def __init__(self, x=0, y=0): self.x = x self.y = y def midpoint(self, other): x = (self.x + other.x) // 2 y = (self.y + other.y) // 2 return Point(x, y) def __str__(self): return f"{self.x} {self.y}" class Circle(object): def __init__(self, point, radius): self.point = point self.radius = radius def __add__(self, other): point = self.point.midpoint(other.point) radius = self.radius + other.radius return Circle(point, radius) def __str__(self): return f"Centre: ({self.point.x:.1f}, {self.point.y:.1f})\nRadius: {self.radius}"
false
817f4926dc2cadfee855389766a71e999d40ba05
KyleHeLi/python_practise
/LeetCode/155_Min_Stack.py
1,100
4.1875
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stackList = [] def push(self, x): """ :type x: int :rtype: void """ curMin = self.getMin() if curMin == None or x < curMin: curMin = x self.stackList.append((x, curMin)) def pop(self): """ :rtype: void """ self.stackList.pop() def top(self): """ :rtype: int """ return self.stackList[-1][0] def getMin(self): """ :rtype: int """ if len(self.stackList) == 0: return None else: return self.stackList[-1][1] def main(): minStack = MinStack() minStack.push(-2) minStack.push(0) minStack.push(-3) # Returns -3 print(minStack.getMin()) minStack.pop() # Returns 0 print(minStack.top()) # Returns -2 print(minStack.getMin()) if __name__ == '__main__': main()
false
ce97fe8cd2c158015d6077423aa0fc9fb8c8d6cc
anand-me/PyLearners
/src/L1.2-Variables_and_Types/script_f.py
525
4.25
4
############ Variables and Types ##################" ############# In python you do not need to declare variables before using them, or declaring there type, since Python is object oriented. We should keep in mind that in Python each variable is an object. ################Defining Strings ########### my_string = 'Keep Continuing Python Learning' my_new_string = "Use double quote to prevent issues with apostrophes,\n Don't worry day by day it will be more easy and fun for you." print (my_string) print (my_new_string)
true
8c9342822a68d9494ee445586476221f9c2857bb
anand-me/PyLearners
/src/L1.7-Conditions/script_a7.py
332
4.25
4
#####################Conditions################# ####Python uses boolean variables to identofy the conditions. The boolean values True or False are returned when expression is evaluated or compared.### ###### IN operator ##### name = "Thomas" if name in ["Thomas", "Cadario"]: print ("Your name is either Thomas or Cadario.")
true
9124849b69caf2623c3170f787add333d507a768
firozansar/Python-samples
/BasicExp/listExp.py
1,985
4.1875
4
numbers = [1, 2, 3, 4] my_list = range(51) # a list of the numbers from 0 to 50 (inclusive). def first_item(items): print (items[0]) # print(first_item(numbers)) numbers.append(5) # print(numbers) def double_first(n): n[0] = n[0] * 2 def double_all(n): for i in range(0, len(n)): n[i] = n[i] * 2 double_all(numbers) print(numbers) print ("******************") list_a = [3, 9, 17, 15, 19] list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90] lists = [list_a, list_b] def flatten(list_of_lists): for lst in list_of_lists: for item in lst: print (item) print ("Flatten:") print(flatten(lists)) def zippen(list1, list2): for a, b in zip(list1, list2): print ("Pair {0} - {1}".format(a, b)) print ("Zip :") print(zippen(list_a, list_b)) print ("*** List Comprehension *****") # This will create a new_list populated by the numbers one to five. new_list = [x for x in range(1, 6)] print(new_list) # => [1, 2, 3, 4, 5] # If you want those numbers doubled, you could use: doubles = [x * 2 for x in range(1, 6)] print(doubles) # => [2, 4, 6, 8, 10] # And if you only wanted the doubled numbers that are evenly divisible by three: doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0] print(doubles_by_3) # => [6] # prints out a list containing ['C', 'C', 'C']. c = ['C' for x in range(5) if x < 3] print (c) print ("*** List Slicing *****") # [start:end:stride] # if you don’t pass a particular index to the list slice, Python will pick a default. # The default starting index is 0. # The default ending index is the end of the list. # The default stride is 1. to_five = ['A', 'B', 'C', 'D', 'E'] print (to_five[3:]) # prints ['D', 'E'] print (to_five[:2]) # prints ['A', 'B'] print (to_five[::2]) # print ['A', 'C', 'E'] print (to_five[::-1]) # negative strive will reverse the list. # print ['E', 'D', 'C', 'B', 'A'] to_21 = range(1, 22) odds = to_21[::2] middle_third = to_21[7:14]
true
46342955938c24a459d1a156ac2fbec9c7badc51
kunal-1308/Python
/oop/simple_class.py
1,150
4.34375
4
#!/usr/bin/python # fd.readline() class Human: planet = "Earth" # class attribute # constructor : gets implicitly invoked on object creation def __init__(self, age, name): print("Constructor") self.age = age # object attributes self.name = name self.type_of_animal = "Social" print(id(self.age)) print(id(Human.planet)) print(id(self.type_of_animal)) def __del__(self): print("Destructor Invoked {}".format(self.name)) def Walk(self): print("{} is walking".format(self.name)) def __gt__(self, obj): print("gt invoked") return self.age > obj.age def main(): x = Human(28, "Jeetendra") print(x.age) print(x.name) #x[1:2:1] y = Human(30, "Bharat") print(y.age) print(y.name) x.Walk() y.Walk() x.teach = True print (x.__dict__) print (y.__dict__) print (dir(x)) x > y # x.__gt__(y) if __name__ == "__main__": main() ''' Human.planet = "Jupiter" print (x.planet) print (y.planet) print x.__dict__ print (dir(x)) print (dir(y)) #print (dir(Human)) '''
false
3f8dba0c56975e4203dc22e38e930c89e7867682
chinoiserie/stepik_python_0
/week_1/1_12_5.py
599
4.125
4
# Напишите программу, которая получает на вход три целых числа, по одному числу в строке, и выводит на консоль в три строки # сначала максимальное, потом минимальное, после чего оставшееся число. На ввод могут подаваться и повторяющиеся числа. a, b, c = int(input()), int(input()), int(input()) if a < b: a, b = b, a if a < c: a, c = c, a if c < b: b, c = c, b print(a, b, c, sep = "\n")
false
4d41281a1f280c6d7a7abf1d5294064d58296e0a
vasilyook/python
/Глава 3. Цикл While, игра Отгадай число/surprise.py
583
4.15625
4
#подключение рандомного модуля import random surprise = random.randint(1,5) if surprise == 1 : print("\nСаша, я тебя люблю!") elif surprise == 2 : print("\nСаша, ты самый лучший на свете!") elif surprise == 3 : print("\nЯ хочу быть с тобой всегда!") elif surprise == 4 : print("\nЧто ты хочешь в подарок на др?") else : print("\nЧто ты хочешь на нашу годовщину??") input("\n\nНажмите Enter, чтобы выйти.")
false
fc3d31afe83219fe2273bafb718988faf0d3ff19
tinaditte/practicepython
/opg13.py
997
4.5
4
""" Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate. (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) """ user = int(input("How many sequences of fibonnaci numbers? ")) cache = dict() def fibo(num): if num == 0: return 1 elif num == 1: return 1 elif num in cache.keys(): return cache[num] else: cache[num] = fibo(num-1) + fibo(num-2) return cache[num] alist = [fibo(i) for i in range(user)] print(alist) def fibonacci(): i = 0 while True: yield fibo(i) i += 1 fibobject = fibonacci() fibonaccis = [next(fibobject) for i in range(user)] print(fibonaccis)
true
d57ea9d7915705e83ed1d44cdc151b48092d19bc
tinaditte/practicepython
/opg11.1.py
399
4.1875
4
num = int(input("Number: ")) def isprime(num): num_range = range(1, num) listofdivs = [i for i in num_range if num % i == 0] if len(listofdivs) == 1: return True else: print(listofdivs) return False if isprime(num) == True: print("Your number is a prime") elif isprime(num) == False: print("Your number is not a prime, here is a list of divisors ")
false
52ec3dcacb9d67e48b223fc6d3980ecf669886fc
vivekpabani/projecteuler
/python/009/problem_009.py
605
4.21875
4
#!/usr/bin/env python """ Problem Definition : A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ import math import sys def main(): for a in xrange(1, 1001): for b in xrange (a, 1001): c = a**2 + b**2 d = math.sqrt(c) if d.is_integer() and a+b+d == 1000: print a, b, int(d) sys.exit(0) if __name__ == '__main__': main()
true
618b5f6ef896082bb4f68fbb5abcbae26e728c2c
vivekpabani/projecteuler
/python/096/problem_096.py
1,893
4.25
4
#!/usr/bin/env python #--- In Progress. ---# """ Problem Definition : Su Doku (Japanese meaning number place) is the name given to a popular puzzle concept. Its origin is unclear, but credit must be attributed to Leonhard Euler who invented a similar, and much more difficult, puzzle idea called Latin Squares. The objective of Su Doku puzzles, however, is to replace the blanks (or zeros) in a 9 by 9 grid in such that each row, column, and 3 by 3 box contains each of the digits 1 to 9. Below is an example of a typical starting puzzle grid and its solution grid. A well constructed Su Doku puzzle has a unique solution and can be solved by logic, although it may be necessary to employ "guess and test" methods in order to eliminate options (there is much contested opinion over this). The complexity of the search determines the difficulty of the puzzle; the example above is considered easy because it can be solved by straight forward direct deduction. The 6K text file, sudoku.txt (right click and 'Save Link/Target As...'), contains fifty different Su Doku puzzles ranging in difficulty, but all with unique solutions (the first puzzle in the file is the example above). By solving all fifty puzzles find the sum of the 3-digit numbers found in the top left corner of each solution grid; for example, 483 is the 3-digit number found in the top left corner of the solution grid above. """ __author__ = 'vivek' import time startTime = time.clock() value_matrix = [] filename = 'sudoku.txt' i = 1 for line in open(filename): if i > 2: #separator = '' temp_list = [] #line = line.split(separator) for value in line : temp_list.append((value)) value_matrix.append(temp_list) i += 1 if i > 10: break for item in value_matrix: print item print "Run time...{} secs \n".format(round(time.clock() - startTime, 4))
true
3b85fd2f823eeb22065387ab27b40861ea37ba74
vivekpabani/projecteuler
/python/001/problem_001.py
1,059
4.125
4
#!/usr/bin/env python """ Problem Definition : If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The answer of these multiples is 23. Find the answer of all the multiples of 3 or 5 below 1000. """ import time import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) def main(): start_time = time.clock() logger.info('Initializing answer.') answer = 0 logger.debug("answer : %d", answer) logger.info('Starting loop.') for x in xrange(1, 1000): logger.debug("Iteration : %d", x) if x % 3 == 0: answer += x logger.debug("Added to answer : %d Answer : %d", x, answer) elif x % 5 == 0: answer += x logger.debug("Added to answer : %d Answer : %d", x, answer) logger.info('Out of loop.') logger.debug("Final answer : %d ", answer) print answer print "Run time...{} secs \n".format(round(time.clock() - start_time, 4)) if __name__ == '__main__': main()
true
3d41ae96ef9cb0502046e3e4b3d86144ed2372c5
imsid22/my-personal-repo
/DigiX/Task 1.py
335
4.46875
4
def multiples(): """ This function loops through the numbers from 1 to 100 and determines which ones are multiples of the numbers 3 and 5 and prints those specific numbers :return: None """ for i in range(1, 101): if i%3==0 or i%5==0: print(i) if __name__ == "__main__": multiples()
true
1a6d8675707f785cb6a6dded7d2685c440ea5263
txtbits/daw-python
/intro_python/Ejercicio con letras/Ejercicio 3.py
634
4.25
4
# -*- coding: cp1252 -*- ''' 3. Escribe un programa que pida una frase cifrada con el mismo sistema y la descifre. ( Escribe un programa que pida una frase y que la codifique cambiando el cdigoascii de cada letra sumndole +2. ) ''' frase = raw_input('Escribe una frase secreta: ') cifrado = '' for letra in frase: asci = ord(letra) if asci != 32: asci += 2 cifrado = cifrado + chr(asci) print cifrado raw_input('Pulsa una tecla para descifrar') descifrado = '' for letra in cifrado: asci = ord(letra) if asci != 32: asci -= 2 descifrado = descifrado + chr(asci) print descifrado
false
7f0f7b36c88c7a9c869636dd7d7992d8f915a8ed
txtbits/daw-python
/primeros ejercicios/Ejercicios de acumular números/ejercicio1.py
359
4.21875
4
''' Escribe un programa que calcula la suma de los números de 1 a 20 (incluyendo ambos números) ''' # Etiqueta resultado inicializada a 0 resultado = 0 # for ...range para recorrer del 1 al 21 for num in range(1,21): # Incrementando resultado en cada iteración resultado += num # Mostrar resultado print 'El resultado es %d' %resultado
false
6f90d519aa911c309ab51fcd9f1e6faaef48b7ba
michaelstresing/python_fundamentals
/06_classes_objects_methods/06_03_freeform.py
2,852
4.875
5
''' - Write a script with three classes that model everyday objects. - Each class should have an __init__ method that sets attributes to a default value if values are not passed. - Create at least two objects of each class using the __init__ method. - Each object should have at least three attributes. - Each class should have at least two class attributes. - Create a print method in each class that prints out the attributes in a nicely formatted string. - Include a __str__ method in each class. - Overload the __add__ method in one of the classes so that it's possible to add attributes of two instances of that class using the + operator. - Once the objects are created, change some of the attribute values. Be creative. Have some fun. :) Using objects you can model anything you want. Cars, animals, poker games, sports teams, trees, beers, people etc... ''' class Footballer: def __init__(self, name='name', teams='team', number='0'): self.name = name self.teams = teams self.number = number def __str__(self): return f"The footballer, {self.name}, wears {self.number} playing for {self.teams}." def printme(self): return f"The footballer, {self.name}, wears {self.number} playing for {self.teams}." class FootballClub: def __init__(self, name='name', city='city', ucltrophies='0'): self.name = name self.city = city self.ucltrophies = ucltrophies def __str__(self): return f"The team, {self.name}, based in {self.city} has won the Champions League {self.ucltrophies} time(s)." def printme(self): return f"The team, {self.name}, based in {self.city} has won the Champions League {self.ucltrophies} time(s)." def winatrophy(self): self.ucltrophies += 1 print(f"{self.name} won! They now have {self.ucltrophies} trophies!") def __add__(self, otherclub): return FootballClub(self.ucltrophies + otherclub.ucltrophies) class UCLWinners: def __init__(self, team='team', year='0000', motm='name'): self.team = team self.year = year self.motm = motm def __str__(self): return f"{self.motm} was Man of the Match, when {self.team} won the Champions League in {self.year}." def printme(self): return f"{self.motm} was Man of the Match, when {self.team} won the Champions League in {self.year}." ronaldo = Footballer('Chistiano Ronaldo', 'Juventus', 7) messi = Footballer('Leo Messi', 'Barcelona', 10) barca = FootballClub('FC Barcelona', 'Barcelona', 5) juve = FootballClub('Juventus', 'Turin', 2) thisyear = UCLWinners('Liverppol FC', 2019, "Virgil van Dijk") twothousandtwelve = UCLWinners('Chelsea FC', 2012, "Didier Drogba") print(ronaldo) barca.winatrophy() print(barca) print(barca.ucltrophies + juve.ucltrophies) messi.teams = "Arsenal" print(messi)
true
9b4948a3d246e2aadd8c2606a49835ec830e5040
michaelstresing/python_fundamentals
/09_testing/09_01_unittest.py
714
4.34375
4
''' Demonstrate your knowledge of unittest by first creating a function with input parameters and a return value. Once you have a function, write at least two tests for the function that use various assertions. The test should pass. Also include a test that does not pass. ''' from math import sqrt import unittest def pythag(a, b): c1 = a ** 2 + b ** 2 c = sqrt(c1) return c print(pythag(3, 4)) class Testpythag(unittest.TestCase): def test_pythag(self): self.assertEqual(pythag(3, 4), 5) self.assertAlmostEquals(pythag(1, 1), 1.414214) self.assertEqual(pythag(0, 0), 0) self.assertEqual(pythag(-2, 0), 2) if __name__ == '__main__': unittest.main()
true
e418f8866e7b93abc39804f3a52a9d43f0be7269
michaelstresing/python_fundamentals
/04_conditionals_loops/03_09_squares.py
218
4.375
4
''' Write a script that prints out all the squares of numbers from 1- 50 Use a for loop that demonstrates the use of the range function. ''' for num in range(1, 50): print(f"The square of {num} is {num ** 2}")
true
a244c0ce826fdf811e9f7ae52f1f46ce335f0f07
michaelstresing/python_fundamentals
/03_more_datatypes/2_lists/04_10_unique.py
509
4.375
4
''' Write a script that creates a list of all unique values in a list. For example: list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13] unique_list = [55, 'hi', 4, 13] ''' list_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13] uniquelist = list(set(list_)) print(uniquelist) #alternative possibility? uniquelist2 = [] for item in list_: if item not in uniquelist2: uniquelist2.append(item) print(uniquelist2) #it looks like the first option will sort, whilst the second keeps the order of the original list
true
07d9eb0023405f27b7f8de30efc723f3beb37349
michaelstresing/python_fundamentals
/03_more_datatypes/4_dictionaries/04_19_dict_tuples.py
589
4.1875
4
''' Write a script that sorts a dictionary into a list of tuples based on values. For example: input_dict = {"item1": 5, "item2": 6, "item3": 1} result_list = [("item3", 1), ("item1", 5), ("item2", 6)] ''' input_dict = {"item1": 5, "item2": 6, "item3": 1} result_list = [] for key, value in input_dict.items(): result_list.append((key, value)) def sort(item): return (item[1]) list2 = sorted(result_list, key= sort) print(list2) #oddly... << list2 = result_list.sort(result_list, key= sort) >> didn't work. I was under the impression that sorted() and .sort were the same?
true
c73374c0c6f362ac88353eb3036e994e4ceca7e8
michaelstresing/python_fundamentals
/08_exceptions/08_03_else.py
391
4.1875
4
''' Write a script that demonstrates a try/except/else. ''' while True: try: num1 = int(input("Please enter a number: ")) num2 = int(input("Please enter another number: ")) result = num1 / num2 except ZeroDivisionError: print("You cannot divide by 0") except ValueError: print("Please enter numbers only") else: print(result)
true
2b0f59fc8364476751ae02c5dc4e7a7e7eb4e16d
addyp1911/Python-week-1-2-3
/python/DataStructures/CashCounter/CashCounter.py
1,035
4.125
4
# Simulate Banking Cash Counter # Desc -> Create a Program which creates Banking Cash Counter where people come in # to deposit Cash and withdraw Cash. # Have an input panel to add people to Queue to either deposit or withdraw money # and dequeue the people. Maintain the Cash Balance. # I/P -> Panel to add People to Queue to Deposit or Withdraw Money and dequeue # Logic -> Write a Queue Class to enqueue and dequeue people to either deposit or withdraw money # and maintain the cash balance import CashCounterBL as cb cc=cb.Queue() num=int(input("enter the no of people wanting to withdraw or deposit= ")) for i in range(1,num+1): balance=int(input("enter the balance of the person= ")) cc.enqueue(i) string=input("enter 'd' for depositing money and 'w' for withdrawing money") if(string=='d'): cash=int(input("enter the amount to be deposit= ")) cc.deposit(cash,balance) else: cash=int(input("enter the amount to be withdraw= ")) cc.withdraw(cash,balance)
true
77859b5783a2483861437028d40688ab90cd9760
addyp1911/Python-week-1-2-3
/python/FunctionalPrograms/DayOfWeek/DayOfWeek.py
873
4.25
4
# To the Util Class add dayOfWeek static function that takes a date as input # and prints the day of the week that date falls on. # Your program should take three command-line arguments: m (month), d (day), and y (year). # For m use 1 for January, 2 for February, and so forth. # For output print 0 for Sunday, 1 for Monday, 2 for Tuesday, and so forth. # Use the following formulas, for the Gregorian calendar (where / denotes integer division): # y0 = y − (14 − m) / 12 # x = y0 + y0/4 − y0/100 + y0/400 # m0 = m + 12 × ((14 − m) / 12) − 2 # d0 = (d + x + 31m0 / 12) mod 7 import DayOfWeekBL try: m=int(input("enter the month of your date= ")) y=int(input("enter the year of your date= ")) d=int(input("the day of the date = ")) DayOfWeekBL.dayofweek(d,m,y) except: print("user please enter the valid day,year or month input")
true
7c3068d11c6ff82a96599437c9cb3a9fa4a9bb8e
addyp1911/Python-week-1-2-3
/python/Algorithms/TempConv/TempConvBL.py
602
4.40625
4
# ----------------------------------TempConversion prg----------------------------------------------- # TempConversion.py # date : 26/08/2019 # method to convert the user entered temperature in celsius to fahrenheit and vice versa def convert(): celsius=float(input("enter the temperature in celsius= ")) celToFahren= (celsius*9/5)+32 print("the temperature when converted to fahrenheit is= ",celToFahren) fahrenheit=float(input("enter the temperature in fahrenheit= ")) fahrenToCel=(fahrenheit-32)*5/9 print("the temperature when converted to celsius is= ", fahrenToCel)
true
0cb4847f6bff670b3d822bb638613e207b450ea1
addyp1911/Python-week-1-2-3
/python/DataStructures/PalindromeChecker/PalindromeChecker.py
706
4.28125
4
#Palindrome-Checker # Desc -> A palindrome is a string that reads the same forward and backward, # for example, radar, toot, and madam. We would like to construct an algorithm # to input a string of characters and check whether it is a palindrome. # I/P -> Take a String as an Input # Logic -> The solution to this problem will use a deque to store # the characters of the string. We will process the string from left to right # and add each character to the rear of the deque. # O/P -> True or False to Show if the String is Palindrome or not. import PalindromeCheckerBL as pc dq=pc.Deque() string=input("enter the string= ") for i in string: dq.append(i) dq.printlist() dq.palindromechecker()
true
f989860c1efe69ab180f45539abf36908609d921
addyp1911/Python-week-1-2-3
/python/DataStructures/BalancedExpression/BalancedExpression.py
970
4.375
4
# a. Desc -> Take an Arithmetic Expression such as (5+6)∗(7+8)/(4+3)(5+6)∗(7+8)/(4+3) # where parentheses are used to order the performance of operations. # Ensure parentheses must appear in a balanced fashion. # b. I/P -> read in Arithmetic Expression such as (5+6)∗(7+8)/(4+3)(5+6)∗(7+8)/(4+3) # c. Logic -> Write a Stack Class to push open parenthesis “(“ and pop closed parenthesis “)”. # At the End of the Expression if the Stack is Empty then the Arithmetic Expression is Balanced # Stack Class Methods are Stack(), push(), pop(), peek(), isEmpty(), size() # d. O/P -> True or False to Show Arithmetic Expression is balanced or not. import BalancedExpressionBL as be s=be.stack() try: string=input("enter the string to check if it's balanced or not= ") except: print("enter a valid expression with parantheses") if(s.checkstring(string)): print('the string is balanced') else: print('the string is unbalanced')
true
566a2f78b5fbbdbf052ad0fab86a1e0318e94371
Ajay-Nair/programs
/python/swap_case.py
243
4.59375
5
#Program to swapcases of a string. In other words,to convert all lowercase letters to uppercase letters and vice versa. def swap_case(s): s = s.swapcase() return s print("Enter String:") s = input() result = swap_case(s) print(result)
true
a7c239e82c77b52f32551f9a787bbe1e6d7aa464
ngthuyn/BTVN
/02_9.py
310
4.25
4
"""Bài 02. Viết chương trình tìm ra 3 phần tử của dict có key lớn nhất""" my_dict={ "ngay":18, "thang":8, "nam":2021, "bai":9, "khoa hoc":"pythoncore" } a=sorted(my_dict.keys(),reverse=1) for key in range(3): print(f"key: {a[key]}, value: {my_dict[a[key]]}")
false
f6ea631dbb5eef90e63dc507330c9d4f34ff1654
milosevich/My_second_exercises_in_Python
/last_n_reversed.py
281
4.40625
4
def last_n_reversed(sequence, n): """Given a sequence and a number n, return the last n elements of the sequence in reversed order""" return sequence[-1:-n-1:-1] fruits = ['apples', 'grapes', 'peaches', 'apricots', 'bananas'] print(last_n_reversed(fruits, 3))
true
ff07b66c664e71663e156564ab95f2216a6fe28b
Romero15/python
/15_if_else.py
1,146
4.34375
4
#If...else """ Python soporta las condiciones lógicas habituales de las matemáticas: Igual: a == b No Igual: ! A = b Menos de: a <b Menos de o igual a: a <= b Mayor que: a> b Mayor que o igual a: a> = b """ print("Ver codigo para más información") a = 33 b = 200 if b > a: print("b es mayor que a") #elif si la condicion anterior no es cierta, trata esta: a = 33 b = 33 if b > a: print("b es mayor que a") elif a == b: print("a y b son iguales") #else si ninguna de las anteriores es cierta entonces: se puede usar sin elif a = 200 b = 33 if b > a: print("b es mayor que a") elif a == b: print("a y b son iguales") else: print("a es mayor que b") #si solo hay una instruccion que ejecutar se puede poner en la misma linea que la condicional if a > b: print("a es mayor que b") #igualmente para el else print("A") if a > b else print("B") #condicion doble con operador logico and c = 300 if a > b and c > a: print("Ambas condiciones son ciertas") #condicion doble con operador logico or if a > b or a > c: print("Por lo menos una de las condiciones es cierta")
false
d895235f2a303f925ecfd05bfd452ee06c9ac455
rushikeshnandurkar/HackerRank-Problems
/Python/ArithmaticOperators.py
411
4.125
4
''' Read two integers from STDIN and print three lines where: The first line contains the sum of the two numbers. The second line contains the difference of the two numbers (first - second). The third line contains the product of the two numbers ''' n = int(input().strip()) m = int(input().strip()) print(n + m) print(n - m) print(n * m) print(n // m) # integer division print(n / m) # float division
true
a2effb2aad524d3a3d5072927e993d398f3be17a
mwoinoski/crs1906
/exercises/ex04_debugging/sample_unit_tests/person.py
837
4.125
4
""" person.py - Simple Person class for Chapter 3 examples. """ class Person: """Simple class for unit test demo""" def __init__(self, first_name, middle_name, last_name): self.first_name = first_name self.middle_name = middle_name self.last_name = last_name def __eq__(self, other): """Called when Person instances are compared with == operator""" return isinstance(other, Person) and \ other.first_name == self.first_name and \ other.middle_name == self.middle_name and \ other.last_name == self.last_name def __ne__(self, other): """Called when Person instances are compared with != operator""" return not self.__eq__(other) def __str__(self): return f"{self.first_name} {self.middle_name} {self.last_name}"
true
9f7e895ebcaf984a9e3f822e236a47d2d2783ab2
davidrocheleau/Fizzbuzz_Py
/fizzbuzz.py
717
4.3125
4
#!/usr/bin/env python # This program is a fizzbuzz generator for numbers divisible by 3 and/or 5 __author__ = "David Rocheleau" __email__ = "drochele@asu.edu" def fizzbuzz(start, stop, step): stop+=step for i in range(start,stop,step): ret_str = '' if(i%3==0): ret_str+='fizz' if(i%5==0): ret_str+='buzz' if not ret_str: ret_str = i print(ret_str) def main(): start = input('Enter start position of fizzbuzz: ') stop = input('Enter stop position of fizzbuzz: ') step = input('Enter step size for fizzbuzz: ') fizzbuzz(int(start), int(stop), int(step)) print('Program has ended. Have a nice day!') main()
true
fc47bcfdba2b7f4e8252a0566686c4135bbfc53c
mofei952/algorithm_exercise
/leetcode/007 Reverse Integer.py
1,568
4.375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : mofei # @Time : 2018/10/27 15:28 # @File : 007 Reverse Integer.py # @Software: PyCharm """ Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution: def reverse(self, x): """ 反转整型变量的数字 :type x: int :rtype: int """ sign = -1 if x < 0 else 1 x *= sign result = 0 while x: r = x % 10 x = x // 10 result = result * 10 + r result *= sign if result < -2 ** 31 or result > 2 ** 31 - 1: return 0 return result def reverse2(self, x): """ 反转整型变量的数字, 通过转换为字符串再反转实现 :type x: int :rtype: int """ sign = -1 if x < 0 else 1 x *= sign s = str(x) result = 0 for i in s[::-1]: result = result * 10 + (ord(i)-ord('0')) result *= sign if result < -2 ** 31 or result > 2 ** 31 - 1: return 0 return result if __name__ == '__main__': result = Solution().reverse2(1534236469) print(result)
true
17995f5e09c1f422c814cfa2120fe843f9e8eaa0
mofei952/algorithm_exercise
/leetcode/028 Implement strStr().py
1,135
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : mofei # @Time : 2018/9/15 23:19 # @File : 028 Implement strStr().py # @Software: PyCharm """ Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). """ class Solution(object): def strStr(self, haystack, needle): """ 查找第一次出现needle的位置 :type haystack: str :type needle: str :rtype: int """ for i in range(len(haystack) - len(needle) + 1): if haystack[i:i + len(needle)] == needle: return i return -1 if __name__ == '__main__': result = Solution().strStr('hello', 'll') print(result)
true
620115213a7eae5e6f8eb49d11c6917364b7d407
rana348/Python-Assignment-Day-7
/Day7.py/Question1.py
739
4.4375
4
#Python3 code to demonstrate #swap of key and value no #initializing dictionary old_dict={21:"FTP",22:"SSH",23:"telnet",80:"http"} new_dict=dict([(value,key)for key,value in old_dict.items()]) #Printing original dictionary print("original dictionary is:") print(old_dict) print() #Printing new dictionary after swapping keys and values print("dictionary after swapping is :") print("keys:values") for i in new_dict: print(i,":",new_dict[i]) #OUTPUT original dictionary is: {21: 'FTP', 22: 'SSH', 23: 'telnet', 80: 'http'} dictionary after swapping is : keys:values FTP : 21 SSH : 22 telnet : 23 http : 80
true
3904207630dce4bda1d15524abbd65a6c2c44fc3
yingthu/MySandbox
/1_tree/LC156_Binary_Tree_Upside_Down.py
747
4.15625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def upsideDownBinaryTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ # idea: feel like it would be more straightforward # if we use a recursive method if root and root.left: newRoot = self.upsideDownBinaryTree(root.left) root.left.right = root root.left.left = root.right root.left = None root.right = None return newRoot return root # Time: O(n), Space: O(n)
true
8e152afd444efe00b1dbe322ce2359270f904bb5
stefandurlesteanu/Codecool
/3rd_SI_week/Algorithm_from_flowchart/algorithm_from_flowchart.py
828
4.21875
4
def list_to_be_sorted(): list_of_nums = (input("Please insert numbers separated by space: ")).split() list_of_nums = list(map(int, list_of_nums)) return list_of_nums def sorting(numbers): iterations = 1 N = len(numbers) while iterations < N: j = 0 while j <= N-2: if numbers[j] > numbers[j+1]: temp = numbers[j+1] numbers[j+1] = numbers[j] numbers[j] = temp j += 1 else: j += 1 iterations += 1 return numbers def printing_result(sorted_list): print ('Your sorted list is: {}'.format(sorted_list)) def main(): first_list = list_to_be_sorted() sorted_list = sorting(first_list) return printing_result(sorted_list) if __name__ == "__main__": main()
true
bfd462ace86554761cd1facdd670afdba8a21762
Swedeldsouza/python-begineer
/session3/operatorassignment.py
2,379
4.125
4
#4 questions ''' Take 3 sides of the triangle as input from the user and check whether that triangle is equilateral, scalene or isosceles(if else) ''' ''' a=int(input("Enter side1:")) b=int(input("Enter side2:")) c=int(input("Enter side3:")) if(a==b and b==c ): print("equilateral triangle") elif(a==b or b==c or a==c): print("isosceles triangle") else: print("Scalene triangle") ''' #Convert month name to a number of days(if else) ''' x=["Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec"] for i in x: print(i) a=str(input("Enter month:")) if(a=="Jan"or a== "April" or a=="June" or a=="Aug" or a=="Oct" or a== "Dec"): print(a,"31 days") elif(a=="Feb"): print(a,"28 days") else(a=="March" or a== "May"or a== "July" or a=="Sept" or a=="Nov" ): print(a,"30 days") ) ''' ''' a=str(input("Enter month:")) b=int(input("Enter year:")) if(a=="Jan"): print(a,"31 days") elif(a=="feb" and b%4==0): print(a,"29 days") elif(a=="feb" and b%4!=0): print(a,"28 days") elif(a=="March"): print(a,"30 days") elif(a=="April"): print(a,"31 days") elif(a=="May"): print(a,"30 days") elif(a=="June"): print(a,"31 days") elif(a=="July"): print(a,"30 days") elif(a=="Aug"): print(a,"31 days") elif(a=="Sept"): print(a,"30 days") elif(a=="Oct"): print(a,"31 days") elif(a=="Nov"): print(a,"30 days") elif(a=="Dec"): print(a,"31 days") ''' #generate dictionary from two list (while loop) list1=["korea","japan","india","china"] list2=["swedel","Jennifer","Jenny","Dsouza"] ''' for key in list1: for value in list2: print((key)+":"+(value)) continue print(dict (key:value)) ''' ''' #Method 2 zip dictionary=dict(zip(list1,list2)) print(dictionary) #Mthod 1 naive mthod dictionary={} for key in list1: for value in list2: dictionary[key]=value list2.remove(value) break print(dictionary) ''' #for loop(factors of number" ''' u=int(input("Enter number:") if(u%i==0): print(i,"divisible by 3") while(i<=10,u%i==0): print(i) i=i+1 ''' '''' u=int(input("enter number")) zi=range(1,u) for i in zi: if(u%i==0): print(i,"factorial of",u) '''
false
621e003dcd78932aaaa68b3033032d32ed4876e9
jonasmzsouza/fiap-tdsr-ctup
/20200504/Trabalho01Exerc02.py
1,291
4.125
4
# TrabalhoComputationalThinking-2020.pdf # Exercício 2 # O salário mensal de um professor, sem considerar os impostos, corresponde a soma dos seguintes valores: # salário base, hora-atividade e descanso semanal remunerado (DSR). Para calcular o salário base multiplicamos # o número de aulas semanais por 4,5 semanas e pelo valor hora-aula, o descanso semanal remunerado corresponde # a 1/6 do salário base e a horaatividade corresponde a 5% da soma do salário base com o descanso semanal remunerado. # Escreva um algoritmo que calcula e imprime o valor do salário base, o valor da hora-atividade, o valor do DSR # e o valor do salário mensal. A entrada do algoritmo será o número de aulas semanais e valor hora-aula, # não se preocupe com a validação de dados. aulaSemanais = int(input("Informe o total de aulas lecionadas na semana: ")) horaAula = float(input("Informe o valor hora aula: ")) salarioBase = aulaSemanais * 4.5 * horaAula dsr = salarioBase * (1 / 6) horaAtividade = 0.05 * (salarioBase + dsr) salarioMensal = salarioBase + horaAtividade + dsr print("\nVALORES" "\nSalário Base....: {:.2f}" "\nDSR.............: {:.2f}" "\nHora-Atividade..: {:.2f}" "\nSalário Mensal..: {:.2f}".format(salarioBase, dsr, horaAtividade, salarioMensal))
false
017ed6ba658204572a336cfddca5cc72f65e727a
jonasmzsouza/fiap-tdsr-ctup
/20200504/Trabalho01Exerc03.py
1,297
4.28125
4
# TrabalhoComputationalThinking-2020.pdf # Exercício 3 # Dados dois números inteiro positivos a e b, escreva um algoritmo que encontra o menor número inteiro # que é múltiplo do número a e do número b. Neste exercício, você deverá validar as informações de entrada, ou seja, # a e b devem ser número positivos. Faça, no papel, dois testes de mesa do seu algoritmo. # Bata uma foto ou escaneie o teste de mesa feito no papel e anexe ao seu trabalho. numA = int(input("Digite um número inteiro positivo A: ")) numB = int(input("Digite um número inteiro positivo B: ")) contA = 1 menorMultiplo = 0 if numA > 0 and numB > 0: if numA > numB: maior = numA else: maior = numB while contA <= maior and menorMultiplo == 0: multiploA = numA * contA contB = 1 while contB <= maior and menorMultiplo == 0: multiploB = numB * contB if multiploA == multiploB: menorMultiplo = multiploB contB = contB + 1 contA = contA + 1 else: print("Informe apenas números maiores que 0!") print("O menor múltiplo comum entre ({}, {}) = {}! Porque? {} x {} = {} e {} x {} = {}." .format(numA, numB, menorMultiplo, numA, (contA - 1), multiploA, numB, (contB - 1), multiploB))
false
cf2addf6478fdc3d08460b3d4c40abb742915297
mxhit-j/Molecular-Modeling-and-Simulations-BIM-303-
/BIM_2019_18_NewRaph.py
670
4.28125
4
# Code for implementation of Newton # Raphson Method for solving equations # The function is: def func( x ): return x**2 - 4*x - 10 # Derivative of the above function # which is 2*x - 4 def derivFunc( x ): return 2*x - 4 # Function to find the root def newtonRaphson( x ): h = func(x) / derivFunc(x) #print('Iteration-%d, h=%0.6f and derivFunc(h) = %0.6f%'%(count,h,derivFunc(h))) while abs(h) >= 0.0001: h = func(x)/derivFunc(x) # x(i+1) = x(i) - f(x) / f'(x) x = x - h print("The value of the root is : ", "%.4f"% x) x1 = float(input("Enter a guess value = ")) newtonRaphson(x1)
true
526cfa53b6da164a8adcebf6969a6a9bbae3df0b
ihavemadefire/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
536
4.25
4
#!/usr/bin/python3 """This module contains an add def.""" def add_integer(a, b=98): """This function adds two ints or floats and returns an int. Args: a (int or float): first number to be added. b (int or float): second number to be added; default to 98. """ if not isinstance(a, int) and not isinstance(a, float): raise TypeError("a must be an integer") elif not isinstance(b, int) and not isinstance(b, float): raise TypeError("b must be an integer") return (int(a) + int(b))
true
9ddf357bb31495d9a8c899cc2fb28ab9df93b99e
ihavemadefire/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
709
4.34375
4
#!/usr/bin/python3 """This module defines a funtion say_my_name""" def say_my_name(first_name, last_name=""): """Defines a funtion say_my_name. Args: first_name: Name to be printed. last_name: Last name to be printed. """ if not isinstance(first_name, str): raise TypeError('first_name must be a string') if not isinstance(last_name, str): raise TypeError('last_name must be a string') if first_name is None: raise NameError('name \'{:s}\' is not defined'.format(first_name)) if last_name is None: raise NameError('name \'{:s}\' is not defined'.format(last_name)) print("My name is {:s} {:s}".format(first_name, last_name))
true
fdd2b44e7caab87c0770f7092b4be5d69046affc
yvah/HW4
/task1.py
731
4.15625
4
# 1. Дан массив. Реализовать функцию которая будет переставлять 2 выбранных элемента списка местами. # Функция должна иметь вид: def swap(target_list, item_index1, item_index2). target_list = [int(i) for i in input('Введите массив: ').split(' ')] item_index1 = int(input('Индекс элемета №1: ')) item_index2 = int(input('Индекс элемета №2: ')) def swap(target_list, item_index1, item_index2): target_list[item_index1], target_list[item_index2] = target_list[item_index2], target_list[item_index1] print(target_list) swap(target_list, item_index1, item_index2)
false
adc9e051bf46dc8dfa5280828bbd3de04c542bcf
AzeezBello/_python
/univelcity/even_numbers.py
287
4.1875
4
#EVEN NUMBERS PRINTER # for x in range(50): # if x % 2 == 0: # print(x) #ODD NUMBERS PRINTER # for x in range(50): # if x % 2 != 0: # print(x) #ODD NUMBERS PRINTER odd_numbers = 0 even_numbers for x in range(50): if x % 2 != 0: print(x)
false
7e82b44916222974ec71221d9b9edeaa8364d9c1
madhan-mj/CWH-Practice-codes
/Guess the number.py
1,005
4.21875
4
Hidden = 18 for i in range(0,9): if i >9: print("GAme Over !!!!") break else: print("Guess and Enter any number : ") num = int(input()) if num == Hidden: print("Congratulation !!! YOU WON THE GAME.") print("You have taken total" , 9-i, "guesses") break elif num >=100: print("Your number is too Greater than the Hidden number . Please try below 100 ") print("Number of guesses left = ", 9 - i) elif num >= 10 and num <= 20: print("Your are near to the Hidden Number.") print("Number of guesses left = ", 9 - i) elif num > Hidden and num < 100: print("Your number is greater than the Hidden Number.") print("Number of guesses left = ", 9 - i) elif num < Hidden: print("Your number is less than the Hidden Number.") print("Number of guesses left = ", 9 - i) continue
true
8a3b16faadbd71e9355e10cd9fb7c324b48dbc4a
jhagen920110/interview
/LinkedList2.py
1,365
4.28125
4
# this code will insert node to the last class Node: def __init__(self, value = None, next = None): self.value = value self.next = next def __str__(self): return 'Node ['+str(self.value)+']' class LinkedList: def __init__(self): self.first = None self.last = None def insert(self, x): if self.first == None: # if the list is empty, make the node as first node and last node self.first = Node(x, None) self.last = self.first elif self.last == self.first: # if there is one node, make new node as last node and existing node.next point to node just created self.last = Node(x, None) self.first.next = self.last else: # else, save created node to current and add it to the lastNode.next, then update self.last to current (created node) current = Node(x, None) self.last.next = current self.last = current def __str__(self): while(self.first != self.last): # print node until last node print(self.first) self.first = self.first.next print(self.first) # print last node def clear(self): self.__init__() LL = LinkedList() LL.insert(1) LL.insert(2) LL.insert(3) LL.__str__() # final should be Node [1] Node [2] Node [3]
true
5ab9cf53e53cb347a743843bf743b09364dd41fd
dan-mcm/MusicPrograms
/Transposers/Transposer - List Version.py
2,121
4.28125
4
# Tranposer program based on the use of lists # Currently only translates c to other keys # Version 2 is working on translation of all keys to all other keys input1 = input("Please insert your starting key: ") input2 = input("Please insert key you wish to transpose to: ") input3 = input("Please insert notes to translate: ") cKey = ["C","D","E","F","G","A","B"] gKey = ["G","A","B","C","D","E","F#"] dKey = ["D","E","F#","G","A","B","C#"] aKey = ["A","B","C#","D'","E'","F#","G#"] eKey = ["E","F#","G#","A","B","C#'","D#'"] bKey = ["B","C#'","D#'","E'","F#'","G#'","A#'","B'"] def keyTransposer(selectedKey,translatedKey,song): """function tranposes key of C to other keys""" transposedSong = [] output = "" # Currently only allowed to run from C as need to figure out how to account for # and b input... if selectedKey == 'c': startKey = cKey print("Selected start key notes: ", startKey) #test statement # Version 2 will explore how to optimise this long if statement.... # Sticking to some basic keys for testing purposes if translatedKey == 'c': transposedKey = cKey print("Selected transposition key notes: ", transposedKey) elif translatedKey == 'g': transposedKey = gKey print("Selected transposition key notes: ", transposedKey) elif translatedKey == 'd': transposedKey = dKey print("Selected transposition key notes: ", transposedKey) elif translatedKey == 'a': transposedKey = aKey print("Selected transposition key notes: ", transposedKey) elif translatedKey == 'e': transposedKey = eKey print("Selected transposition key notes: ", transposedKey) elif translatedKey == 'b': transposedKey = bKey print("Selected transposition key notes: ", transposedKey) for note in song: notePosition = startKey.index(note) #seems an issue with selectedKey to startKey newNotePosition = transposedKey[notePosition] transposedSong.append(newNotePosition) print("Composing transposition...") for note in transposedSong: output += note + ", " return output if __name__ == "__main__": print(keyTransposer(input1,input2,input3))
true
bb8a00aba6ddd645448cdfcc7439921cc05caef7
4neta/Cryptosystem_RSA
/rsa_decryption.py
589
4.15625
4
print('-- RSA Algorithm \\ DECRYPTION --') print('To decrypt, you need a prepared file "crypto.txt".') print("Enter your private key") d = int(input(" d = ")) n = int(input(" n = ")) f = open("crypto.txt","r") g = open("message_from.txt", "w") while True: line = f.readline().strip() if not line: break # end loop when EOF numb = pow(int(line),d)%n # decrypt numbers txt = chr(numb) # conversion into the original text g.write(txt) # writing to a file, char by char f.close() g.close()
true
1341a25b66201da76a7d7d58d3d74af341b8ebbc
Eric-Wonbin-Sang/CS110Manager
/2020F_hw6_submissions/madireddysaumit/Date.py
867
4.375
4
#Saumit Madireddy #I pledge my honor that I have abided by the Stevens Honor System. def main(): is_correct = True months_with_31_days = [1, 3, 5, 7, 8, 10, 12] date = input("Enter a date in the month/day/year format (xx/xx/xxxx): ") date_list = date.split("/") if len(date_list) !=3: is_correct = False else: month, day, year = date_list try: month = int(month) day = int(day) year = int(year) if month > 12 or month < 1 or day > 31 or day < 1 or year < 1: is_correct = False elif month not in months_with_31_days and day == 31: is_correct = False except: is_correct = False if is_correct: print("The date", date, "is valid") else: print("The date", date, "is not valid.") main()
true
1463f4c01411c176ff8f9043ceb16fd6d98da682
Eric-Wonbin-Sang/CS110Manager
/2020F_hw4_submissions/mascolomatthew/MatthewMascolo.py
596
4.125
4
#MatthewMascolo.py #I pledge my honor that I have abided #by the Stevens Honor System. Matthew Mascolo # #This program takes a list of New York Knicks players #and staff in Before.txt, then it capitalizes all #players' first and last names and prints them out in After.txt def main(): inFile = 'Before.txt' outFile = 'After.txt' inFile = open(inFile, "r") outFile = open(outFile, "w") for i in inFile: first, last = i.split() newName = first.upper() + " " + last.upper() print(newName, file=outFile) inFile.close() outFile.close() main()
true
655b024e1626f6080aa942f11bd729ed6cc96313
Eric-Wonbin-Sang/CS110Manager
/2020F_quiz_2_pt_2_submissions/atmacamelissa/MelissaAtmacaQuiz2Part2.py
2,678
4.21875
4
#I pledge my Honor that I have abided by the Stevens Honor System. #I understand that I may access the course textbook and course lecture notes but I am not to access any other resource. #I also pledge that I worked alone on this exam. #Melissa Atmaca def addition(x, y): sum = x + y return sum def subtraction(x, y): diff = x - y return diff def multiplication(x, y): prod = x * y return prod def division(x, y): div = x / y return div def vow(string): vowels = ["a", "A", "e", "E", "i", "I", "o", "O", "u", "U"] count = 0 for vowel in vowels: if vowel in string: count += 1 print("The vowel count in the string is", count) def encrypt(string): for i in string: print(ord(i), end=" ") return def main(): select = int(input("For Mathematical Functions, Please Enter the Number 1.\nFor String Operations, Please Enter the Number 2:\n")) if select == 1: matop = int(input("For Addition, Please Enter the Number 1\nFor Subtraction, Please Enter the Number 2\nFor Multiplication, Please Enter the Number 3\nFor Division, Please Enter the Number 4: \n")) if matop == 1: num1, num2 = input("Please enter two numbers separated by a comma: ").split(",") a = addition(float(num1), float(num2)) print(a) elif matop == 2: num1, num2 = input("Please enter two numbers separated by a comma: ").split(",") a = subtraction(float(num1), float(num2)) print(a) elif matop == 3: num1, num2 = input("Please enter two numbers separated by a comma: ").split(",") a = multiplication(float(num1), float(num2)) print(a) elif matop == 4: num1, num2 = input("Please enter two numbers separated by a comma: ").split(",") division(float(num1), float(num2)) print(a) else: print("Your entry is invalid. Please input a numerical character that is within the numerical range.") elif select == 2: stringop = int(input("To Determine the Number of Vowels in a String; Enter the Number 1\nTo Encrypt a String; Enter the Number 2:\n")) if stringop == 1: str = input("Please input a string: ") vow(str) elif stringop == 2: str = input("Please input a string: ") encrypt(str) else: print("Your entry is invalid. Please input a numerical character that is within the numerical range.") else: print("Your entry is invalid. Please input a numerical character that is within the numerical range.") main()
true
d8fb4f558a23075c21a16f114bf6b2199705ff7f
Eric-Wonbin-Sang/CS110Manager
/2020F_hw6_submissions/brendeliiiphilip/PhilipBrendelCH7P2.py
1,364
4.125
4
#Philip Brendel #I pledge my honor that I have followed the Stevens Honor code def checkMonth(month): months31 = [1,3,5,7,8,10,12] if int(month) > 12 or int(month) < 1: return False if int(month) in months31: return 31 print(31) if int(month) == 2: return 28 print(28) else: return 30 print(30) def checkDay(day, month): if int(day) in range(1,(int(month))+1): return True else: return False def checkYear(year): if len(year) != 2: return False def validDate(): date = input("Input the date in m/d/y format, (ex. 09/05/02) ") date = date.split('/') day = date[1] month = date[0] year = date[2] Yearchecked = checkYear(year) if Yearchecked == False: print("Date is invalid, please try again.") print("Your year is invalid") else: monthChecked = checkMonth(month) if monthChecked == False: print("Date is invalid, please try again.") print("Your month is invalid") else: dayChecked = checkDay(day, monthChecked) if dayChecked == False: print("Date is invalid, please try again.") print("Your day is invalid.") else: print("Your date is valid.") validDate()
true
7a38a916afbcd45dea55ae5b7b770b09c6d95def
Eric-Wonbin-Sang/CS110Manager
/2020F_quiz_2_pt_2_submissions/maloneycatherine/quiz 2 part 2 cmaloney.py
2,837
4.125
4
# Catherine Maloney - CS 110 Quiz 2 Part 2 # I pledge my honor that I have abided by the Stevens honor system. # I understand that I may access the course textbook and course lecture notes # but I am not to access any other resource. I also pledge that I worked alone # on this exam. # This program performs Python operations based on the selections the user inputs. def main(): menu = int(input("For Mathematical Functions, Please Enter the Number 1;" "\nFor String Operations, Please Enter the Number 2: ")) if menu != 1 or 2: print("Your menu entry is invalid.") if menu == 1: math = int(input("For Addition, Please Enter the Number 1;" "\nFor Subtraction, Please Enter the Number 2;" "\nFor Multiplication, Please Enter the Number 3;" "\nFor Division, Please Enter the Number 4: ")) if math == 1: x = int(input("Enter integer 1 to be added: ")) y = int(input("Enter integer 2 to be added: ")) add = x + y print("The sum of the integers you entered is: ",add) elif math == 2: x = int(input("Enter integer 1 to be subtracted: ")) y = int(input("Enter integer 2 to be subtracted: ")) sub = x - y print("The difference of the integers you entered is: ",sub) elif math == 3: x = int(input("Enter integer 1 to be multiplied: ")) y = int(input("Enter integer 2 to be multiplied: ")) mult = x*y print("The product of the integers you entered is: ",mult) elif math == 4: x = int(input("Enter integer 1 to be divided: ")) y = int(input("Enter integer 2 to be divided: ")) divide = x/y print("The quotient of the integers you entered is: ",divide) else: print("Your menu entry is invalid.") if menu == 2: string = int(input("To Determine the Number of Vowels in a String; Enter the Number 1;" "\nTo Encrypt a String; Enter the Number 2: ")) if string == 1: str_input = str(input("Enter a string that will have its vowels counted: ")) count = 0 vowels = ["A","a","E","e","I","i","O","o","U","u"] for letter in str_input: if letter in vowels: count += 1 print("The number of vowels in your string is: ",count) elif string == 2: str_input = str(input("Enter a string to be encyrpted: ")) print("Your encrypted string is: ") for i in str_input: print(ord(i), end = "") else: print("Your menu entry is invalid.") main()
true
b201217414313878985c5bda52e668288d4999ed
Eric-Wonbin-Sang/CS110Manager
/2020F_hw6_submissions/kooikerelaine/ElaineKooikerCH7P1.py
999
4.40625
4
#I pledge my Honor I have abided by the Stevens Honor System. Elaine Kooiker #Problem One; The Body Mass Index (BMI) is calculated as a person’s weight (in pounds) times 720, #divided by the square of the person’s height (in inches). #A BMI in the range of 19 to 25 (inclusive) is considered healthy. #Write a program which calculates a person’s BMI and prints a message stating whether the person is above, within, or below the healthy range. import math def get_BMI(weight, height): BMI=(weight*720)/(height**2) return BMI def define_BMI(BMI): if (19<=BMI<=25): statement="You are within a healthy BMI range." elif (BMI>25): statement="Your BMI is above a healthy range." elif(BMI<25): statement="Your BMI is below a healthy range." return statement def main(): weight=float(input("Enter your weight in pounds: ")) height=float(input("Enter your height in inches: ")) BMI=get_BMI(weight, height) print(define_BMI(BMI)) main()
true
ccfd7747deaa2572fc1efbe3b919e209638e88ff
Eric-Wonbin-Sang/CS110Manager
/2020F_hw6_submissions/couvalevan/EvanCouvalCH7P1.py
317
4.1875
4
def main(): weight = int(input("please enter your weight in pounds: ")) height = int(input("please enter your height in inches: ")) bmi = (weight * 720)/(height**2) if bmi >= 19 and bmi <= 25: health = "healthy" else: health = "unhealthy" print(bmi) print(health) main()
false
2f313ac9b7726f3609d8b7d5ef6003aca977e572
rkothakapu/ElementsOfProgrammingInterviews
/Chapter4_PrimitiveTypes/ETI_4_2_SwapBits.py
420
4.34375
4
def swap_bits(x: int, i: int, j: int) -> int: """ :param x: number in which bits are to be swapped :param i: position i :param j: position j :return: number after bits at loc i, j are swapped """ # hint: When is the swap necessary? # Swap is necessary if bits at i, j are different, i.e. bit_i ^ bit_j = 1 if x & (1 << i) ^ x & (1 << j): x ^= (1 << i) | (1 << j) return x
false
96b45df241944532d9d5516b58d220e0690d0ddd
VINOTHKANNANBASKARAN/Python1.0
/MultiThreading.py
531
4.34375
4
from threading import Thread from time import sleep class Hi(Thread): def run(self): for i in range(10): print("Hi") sleep(1) class Hello(Thread): def run(self): for i in range(10): print("Hello") sleep(1) hi = Hi() hello=Hello() hi.start() sleep(.2) hello.start() hi.join() hello.join() #Main Thread will wait until the hi and hello threads complete there task to print the bye #This is how we make main thread wait for our other threads print("Bye Bye")
true
b722d2f9bed3ae7ed788c8f9c2e5369dce309eb1
viraco4a/SoftUni
/PythonBasics/Nested_Loops_Ex/Prime_not_Prime.py
576
4.21875
4
def is_prime(num): if number < 2: return False for i in range(2, num // 2 + 1): if num % i == 0: return False return True line = input() prime_sum = 0 non_prime_sum = 0 while line != "stop": number = int(line) if number < 0: line = input() print("Number is negative.") continue if is_prime(number): prime_sum += number else: non_prime_sum += number line = input() print(f"Sum of all prime numbers is: {prime_sum}") print(f"Sum of all non prime numbers is: {non_prime_sum}")
true
9783f5b1402d77acec8444940d6383287e3e8066
shmehta21/DS_Algo
/stack.py
1,053
4.1875
4
# Stack using Python lists -> LIFO class MyStack( object ): def __init__(self): self.myStack = [] self.size = 5 def __len__(self): return len(self.myStack) def push(self, data): if len(self.myStack) >= self.size: #List can be resized here as an alternate OR we can implement Stack as a linked list so that there is no mem constraint and a linked list will grow dynamically print('Stack overflow!!!') return self.myStack.append(data) def pop(self): if len(self.myStack) == 0: print('Stack underflow!!! No items left on the stack') return item = self.myStack[-1] #LIFO del self.myStack[-1] return item def peek(self): return self.myStack[-1] if __name__ == '__main__': s1 = MyStack() s1.push(1) s1.push('A') s1.push(2) s1.push('B') print(f'Stack size before popping: {len(s1)}') print(f'Peeping last item on stack: {s1.peek()}') print(f'Popping out {s1.pop()} from stack') print(f'Popping out {s1.pop()} from stack') s1.push(3) s1.push('C') s1.push(4) s1.push('D') s2 = MyStack() s2.pop()
true
4dfac646d6ea1da0987535da1ccf5802878e257b
shmehta21/DS_Algo
/recursion_count.py
738
4.15625
4
############################## #Sum of #'s in a list using recursion' - uses a divide-conquer technique to approach the problem # 1.) Identifies a base/recursive case # 2.) Divides and reduces the problem until it reaches the base case # a. Works by counting elements in a list of 0 or 1 elements with rest of the elements in a separate list # b. Keeps doing this recursively until all elements in the list have been counted ############################## def recursive_count(myArr): if len(myArr)<2: return len(myArr) return len([myArr[0]]) + recursive_count(myArr[1:]) if __name__ == '__main__': a = [1,2,3,4,5] print('# of elements in a->', recursive_count(a)) a1 = [1] print('# of elements in a1->', recursive_count(a1))
true
3ddbcf6e88d8827c8d19adee52cc48fa33f2e966
carrda/Python_part_1
/ListExercises.py
1,049
4.34375
4
# List Exercises # sum list of numbers numList = [-1, -2, 2,5,7] factorNum = 2 # will increase list items by factor of two numTot = 0 largestNum = numList[0] # arbitrarily set starting largest number smallestNum = numList[0] # same for smallest number positiveList = [] factoredList = [] for item in numList: numTot = numTot + item if item > largestNum: largestNum = item if item < smallestNum: smallestNum = item if item % 2 == 0: # determine if item is even number print(str(item) + " is an even number.") if item > 0: print(str(item) + " is a positive number") positiveList.append(item) # build list of positive numbers factoredList.append(item * factorNum) print("Total of numbers in list is " + str(numTot)) print("Largest number in list is " + str(largestNum)) print("Smallest number in list is " + str(smallestNum)) print("Here's the list of positive numbers.") print(positiveList) print("Here's the list multipled by " + str(factorNum)) print(factoredList)
true
5aae0a6f985bcc25a467d83da6b9b05cbd6554e7
carrda/Python_part_1
/drawAStar.py
275
4.1875
4
# Draw a star with Turtle Graphics from turtle import * for i in range(5): forward(100) right(144) up() forward(200) down() for i in range(5): forward(50) right(144) up() right(90) forward(150) down() pencolor('orange') width(10) circle(180) mainloop()
false
315d825f99eb40ae00d43c6f2a668e2f8b219b20
carrda/Python_part_1
/VectorMatrix.py
667
4.1875
4
# Vector and Matrix List Exercises # Multiply two equal length vectors -- could be any sizew vector1 = [3, 4, -2] vector2 = [5, 2, 1] matrix1 = [[2, -2], [2,4]] matrix2 = [[5]] multiplyVector = [] for index in range(0, len(vector1)): multiplyVector.append(vector1[index] * vector2[index]) print("Example of vector multiplication") print(str(vector1) + " X " + str(vector2) + " = " + str(multiplyVector)) # De-Dup a list -- remove duplicate entries origList = [5, 3, 4, 5, 8] noDupList = [] for item in origList: if item not in noDupList: noDupList.append(item) print("Original list: " + str(origList)) print("Without dups: " + str(noDupList))
true
ea42c047b8a219c83b2116024008a19d285cc74d
jwood91/Python-Crash-Course
/5 If Statements/amusementpark.py
1,106
4.34375
4
age = 12 # elif lets your program go through multiple conditions for different # situations and returns the outcome that fits: if age <= 4: print("Your admission is £0") elif age < 18: print("Your admission is £5") else: print("Your admission is £10") # to write this more concisely you would put the price within the if else chain age = 18 if age < 4: price = 0 elif age <= 18: price = 5 else: price = 10 print('your admission cost is £' + str(price) + '.') # the above way is more simple to modify, if you needed to edit the message # in the string yu can just edit one string rather than three like in the first # example # you can use as mans elif lines as you like in your code. You also do not # need to finish on an else block if the last line will be more clear with an # elif statement: age = 64 if age < 4: price = 0 elif age <= 18: price = 5 elif age < 65: price = 10 elif age >= 65: price = 5 print('your admission cost is £' + str(price) + '.') # the elif statment showing why the price is £5 over 65 is mor clear and an # else statement.
true
bdd21d7a1f94d29ff071da11a842a9cfc8770249
jwood91/Python-Crash-Course
/5 If Statements/magicnumber.py
1,338
4.15625
4
answer = 17 if answer != 42: print("This is not the correct answer, please try again!") # The above tests if two numbers are not equal. # you can include various mathematical comparisons in your conditional # statements age = 19 print(age == 21) print(age > 21) print(age <= 21) print(age < 21) # you can check multiple conditions at once using 'and' statement print(my_age <= 21 and friend_age >= 21) # you can also use an 'or' statement which will pass if either one of the # conditions is True print(my_age > 18 or friend_age >= 21) # the above prints still True even though my_age's value is not less than 18 # but friend_age value is greater than or equal to 21 so it returns True. # you can check if a value is in a list using the 'in' function toppings = ['bacon', 'ham', 'pineapple', 'cheese'] print('pineapple' in toppings) print('peperoni' in toppings) # it tells me that peperoni is not in my list but pineapple is. # you can check also if a value is not in a list using the 'not' keyword banned_users = ['andrew', 'carolina', 'david'] user = 'marie' if user not in banned_users: print(user.title() + " You can post a response if you wish") # this if statement checks multiple conditions and then gives an output my_age = 18 friend_age = 22 if my_age and friend_age >= 18: print("You may enter the club")
true
8697d28273ce32738e6e65de7e5a598024a4e4d9
jwood91/Python-Crash-Course
/3 Introducing Lists/motorcycles.py
2,319
4.65625
5
# You can change the values of items within the list: motorcycles = ["honda", "yamaha", "suzuki"] print(motorcycles) # This will replace the first item motorcycles[0] = 'ducati' # To add items to a list you need to use the .append() function motorcycles.append("ducati") print(motorcycles) # You can use the append function to build lists dynamically. so you can start # with an empty list and add items. motorcycles = [] print(motorcycles) motorcycles.append("honda") print(motorcycles) # You can insert an item at any point in the list by using the .insert() # fuction. index position first then second the item to add example below: motorcycles = ["honda", "yamaha", "suzuki"] motorcycles.insert(1, "ducati") print(motorcycles) # You can use a del statement to remove an item from anywhere in the list # if you know the index location in the example below you will no longer be # able to access the item once the del statement is run motorcycles = ["honda", "yamaha", "suzuki"] del motorcycles[0] print(motorcycles) # you can remove items from the list using the .pop() method. This lets you # remove an item from a list but then continue working with it. motorcycles = ["honda", "yamaha", "suzuki"] motorcycles.pop() print(motorcycles) motorcycles = ["honda", "yamaha", "suzuki"] popped_motorcycle = motorcycles.pop() motorcycles.append(popped_motorcycle) print(motorcycles) # you can also pop an item from any indexed position first_owned = motorcycles.pop(0) print("The first motorcycle I owned was a " + first_owned.title() + ".") print(motorcycles) motorcycles.append(first_owned) print(motorcycles) # When deciding to use a del statement or pop() method think do I need to use # that item again. If you don'tneed it you can use the del statement, if you # want to use it then use the pop() method. # Sometimes you want to remove an item you do not know the index of you can use # the .remove() method. motorcycles = ["honda", "suzuki", "ducati", "yamaha"] print(motorcycles) motorcycles.remove("ducati") print(motorcycles) # Similar to the pop() method you can work with the item from the remove() # method. motorcycles = ["honda", "suzuki", "ducati", "yamaha"] too_expensive = "ducati" motorcycles.remove(too_expensive) print(motorcycles) print("A " + too_expensive + " is too expensive for me.")
true
27350bd8af0265304e3bf44f15c5a64d4e8de10a
jwood91/Python-Crash-Course
/5 If Statements/cars.py
637
4.28125
4
cars = ['audi', 'bmw', 'toyota', 'subaru'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) # single = will set the value of car as a variable with the sting attached # double == will check to see if the value of car is equal to bmw car = 'audi' print(car == 'audi') print(car == 'bmw') # checking for equality is case sensitive car = "Audi" print(car == "audi") # the above returns a false value because of the capitalised Aa # below lowers the strings case all lower case and now it projects a true value print(car.lower() == 'audi') for item in cars: print(item.lower())
true
011ccc5d17fdab92cff6ce91453ad05c95894d82
jwood91/Python-Crash-Course
/6 Dictionaries/many_users.py
644
4.1875
4
# you can nest dictionary's inside of dictionary's for example # if you had a username and you wanted to store further information about # a user. user = { 'aestinien': { 'first': 'albert', 'last': 'einstein', 'location': 'berlin', }, 'mwest': { 'first': 'mary', 'last': 'curie', 'location': 'colchester', } } for username, user_info in user.items(): print("\nUsername: " + username) full_name = user_info['first'] + " " + user_info['last'] location = user_info['location'] print("\tFull Name: " + full_name.title()) print("\tLocation: " + location.title())
false
1965bbd1b01a204cb0b59ca998b0057232b735e3
Zzpecter/Coursera_AlgorithmicToolbox
/week2/8_last_digit_sum_of_fib_squares.py
1,112
4.28125
4
# Created by: René Vilar S. # Algorithmic Toolbox - Coursera 2021 def get_fibonacci_pisano_rene(n): pisano_period = get_pisano_period(3) remainder_n = n % pisano_period previous, current = 0, 1 for _ in range(remainder_n - 1): previous, current = current, previous + current return current def get_pisano_period(m): previous, current = 0, 1 for i in range(0, m ** 2): previous, current = current, (previous + current) % m # Pisano Period always starts with 01 if previous == 0 and current == 1: return i + 1 def format_output(f_n, f_n_plus_1): return ((f_n % 10) * (f_n_plus_1 % 10)) % 10 if __name__ == '__main__': n = int(input()) if n > 1: f_n = get_fibonacci_pisano_rene(n) f_n_plus_1 = get_fibonacci_pisano_rene(n+1) print(format_output(f_n, f_n_plus_1)) elif n == 1: print(1) else: print(0) # print(f'fib_n: {f_n} fib_n+1: {f_n_plus_1}') # print(f'mod_fib_n: {f_n%10} mod_fib_n+1: {f_n_plus_1%10}') # print(f'last digit: {((f_n%10) * (f_n_plus_1%10))%10}')
false
190c05c390033b8802c67541945ca812f28a5e65
shwethasparmar/Common-coding-problems
/childAndSteps.py
404
4.15625
4
#A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. def step(stepNo, n): if(stepNo + 1 == n ): return 1 elif (stepNo + 2 == n): return 2 elif (stepNo +3 == n ): return 4 return step(stepNo+1, n) + step(stepNo+2, n) + step(stepNo+3, n) print(step(0,5))
true
96679ba89b998bc534712b4d30e2cae1d9549c2d
Uma-Kalakada/Python-Practice
/04_augmn_operators.py
651
4.3125
4
# program to perform all augmented operations on two numbers. a = 4 b = 2 print(f"a = {a} and b= {b}") a += b print(f"The result of a+=b is {a}.") print(f"a = {a} and b= {b}") a -= b print(f"The result of a-=b is {a}.") print(f"a = {a} and b= {b}") a *= b print(f"The result of a*=b is {a}.") print(f"a = {a} and b= {b}") a /= b print(f"The result of a/=b is {a}.") print(f"a = {a} and b= {b}") a //= b print(f"The result of a//=b is {a}.") print(f"a = {a} and b= {b}") a **= b print(f"The result of a**=b is {a}.") print(f"a = {a} and b= {b}") a %= b print(f"The result of a%=b is {a}.")
true
e30442a5769a2090b367a54ad014527426ae50a0
shayrm/python_and_ctf
/example_if_statments.py
471
4.15625
4
# play with the 'if' statment is_male = True # check if is_male is true or false def check_male(cond, name): if cond: print("yes, you are a male, your name is: " + name) else: print("No, you are not male, your name is: " + name) def check_name(name): if name == "Shay": return True else: return False name = input("Please enter your name: \n") result = check_name(name) check_male(result, name)
true
551082fd04de19d71a09f6d92b71a4395ddc97f3
shayrm/python_and_ctf
/dictionaries.py
519
4.1875
4
# set a dictionary with a key: value pair # convert three latter month to full name monthConvertion = { "Jan": "Jaunary", "Feb": "February", "Mar": "March", "Apr": "Appril" } print(monthConvertion["Jan"]) # can use the .get function, which could get a default value # the default value could be set when the key is invalide default_value = "Invalid option" print(monthConvertion.get("Apr", default_value)) print(monthConvertion.get("888", default_value)) print(monthConvertion["Feb"])
true
d78edb8f5b50660349cf234d8205ecc9449dbc56
Johanson20/Python4Geoprocessing
/ch14/moduloTry.py
516
4.1875
4
# moduloTry.py # Purpose: Compute the remainder of dividing two numbers. # Usage: Two integer values # Example input1: 25 4 # Example input2: 5 0 # Example input3: woods 3 import sys field1 = sys.argv[1] field2 = sys.argv[2] print("a: {0} b: {1}".format(field1, field2)) try: a = int(field1) b = int(field2) c = a % b except ZeroDivisionError: c = '{} mod {} is undefined'.format(a, b) except ValueError: print('Usage: <numeric value 1> <numeric value 2>') c = 'Not found' print("c:", c)
true
7d8013f06ff878859f81e18edd8eb4e3205dff7c
daadestroyer/20MCAOOPS
/Tuple_10/App06.py
306
4.1875
4
''' Python has two built-in methods that you can use on tuples. count() return no of same item present inside tuple index() search the tuple with specified value and return its index ''' tpl = ('apple', 'mango', 'orange', 'banana', 'cherry','banana') print(tpl.count('banana')) print(tpl.index('banana'))
true
35930ad501cc88ed2cdba2bedea0c39ad07a5873
daadestroyer/20MCAOOPS
/Strings_03/App03_SlicingString.py
318
4.40625
4
# PYTHON SLICING # slicing strings ''' b(start , end-1) ''' b = "Hello, World!" print(b[2:5]) # Slice From the Start print(b[:5]) # Slice To the End b = "Hello, World!" print(b[2:]) # Negative Indexing , Use negative indexes to start the slice from the end of the string: b = "Hello, World!" print(b[-5:-2]) # orl
true
44e226d004f1126aa0fea46c81143e527e96ed2d
daadestroyer/20MCAOOPS
/Tuple_10/App01.py
1,032
4.5
4
''' ORDERED Tuple are ordered , means that item have defined order , and that order will not change UNCHANGEABLE Tuples are unchangeable , meaning that we cannot change , add or remove items after the tuple is created, while list are changeable ALLOW DUPLICATES Tuple allow duplicates values as well , similarly List also allowed duplicate value also ''' thistuple = ('apple','mango','orange','apple') print(thistuple) print(len(thistuple)) ''' Create Tuple With One Item To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. ''' thistuple = ('apple',) print(type(thistuple)) # its a tuple thistuple = ('apple') print(type(thistuple)) ''' Tuple Items - Data Types Tuple items can be of any data type: ''' print() tuple1 = ('apple','banana','cherry') tuple2 = (1,2,3,4,5,6) tuple3 = (True,False,False) print(tuple1) print(tuple2) print(tuple3) # A tuple with strings, integers and boolean values tuple1 = ("abc", 34, True, 40, "male") print(tuple1)
true
d2d6209f7fd0c93c754871bf6968715915a2922f
daadestroyer/20MCAOOPS
/Assignement/App02.py
608
4.125
4
while True: print('1. concat tuple :') print('2. find max :') print('3. find min :') print('4. reverse tuple :') choice = int(input('enter choice')) if choice == 1: t1 = tuple(input('enter tuple 1')) t2 = tuple(input('enter tuple2')) print(t1+t2) elif choice == 2: t1 = tuple(input('enter tuple')) print(max(t1)) elif choice == 3: t1 = tuple(input('enter tuple')) print(min(t1)) elif choice == 4: t1 = tuple(input('enter tuple')) print(t1[::-1]) else: print('exiting') break
false
ab7e0bb7a627c4480158a0eb7a3df7a40c676658
zabi-salehi/Coding-Problems
/Easy/Week 1/Problem Palindrome/solution.py
729
4.1875
4
''' Week 1 - Problem Palindrome @author: André Gilbert, andre.gilbert.77110@gmail.com Given an array of integers. Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same forward as backward. ''' from typing import List # O(n^2) time complexity, O(1) space complexity def solution(array: List[int]) -> List[bool]: for i in range(0, len(array)): if array[i] < 0: array[i] = False forward = str(array[i]) backward = forward[::-1] if forward == backward: array[i] = True else: array[i] = False return array # Example usage if __name__ == "__main__": array = [12321, -343, 1230] result = solution(array) print(result)
true
4c5c93d85a0274b15d3719cfe1852d97e04dbfca
warlockee/leetpy
/algos/merge-intervals.py
963
4.1875
4
""" imagine a number line, we put all the numbers on it and draw a line between two numbers for each interval. for all the overlap lines we just want the start and the end we need to sort the array of intervals, so we won't miss any overlaps by iterate through the array once. [1] first we check if there is overlaps if we the end of the last interval is greater or equal than the start of this inteval, we found the overlaps. [2] so we need to update the last interval's end [3] if there is no overlaps [4] we don't need to do anything, just put it in the array """ class Solution(object): def merge(self, intervals): result = [] intervals.sort(key=lambda x: x.start) # [1] for inter in intervals: if len(result) > 0 and result[-1].end >= inter.start: # [2] result[-1].end = max(result[-1].end, inter.end) # [3] else: # [4] result.append(inter) return result
true
b9f3e9504a6c3f4db658e1790bb0003ec8601dbd
warlockee/leetpy
/algos/subsets.py
2,531
4.125
4
""" For every number in `nums` you either take (O) or not take it (X). So for example ``` nums = [1,2,3] Subset [] is [X,X,X] Subset [1] is [O,X,X] => [1,X,X] Subset [2] is [X,O,X] => [X,2,X] Subset [3] is [X,X,O] => [X,X,3] Subset [1,2] is [O,O,X] => [1,2,X] Subset [1,3] is [O,X,O] => [1,X,3] . . . Subset [1,2,3] is [O,O,O] => [1,2,3] ``` So there are total 2x2x2 posibilities (subsets). Because for each number, it has two choices, take (O) or not take (X). """ class Solution(object): def subsets(self, nums): def helper(i, combination): answer.add(tuple(combination)) if i >= len(nums): return helper(i + 1, combination + [nums[i]]) helper(i + 1, combination) answer = set() helper(0, []) return [list(combination) for combination in answer] """ `helper()` help add `combination` to the answer. And if we have run through all the numbers, return. If not, for this number at index `i`, there are two scenarios. Add it to the combination, or not. And there might be duplicates, and I could not think of better way without using hash set on `answer`. The time complexity is O(2^N). The space complexity is O(2^N), too. """ class Solution(object): def subsets(self, nums): answer = [[]] for n in nums: new_subs = [] for sub in answer: new_subs.append(sub + [n]) answer.extend(new_subs) return answer """ So for each n in `nums`, what we do is ``` new_subs = [] for sub in answer: new_subs.append(sub+[n]) answer.extend(new_subs) ``` We take all the subset in the `answer`, append n, put the new subset into `new_subs`. And the answer become `subsets` + `new subsets`. You can think of it as `subsets` => the combination which we did not take n. `new subsets` => the combination which we take n. Now if we have iterated the third element, then the `answer` now contains all the possible subsets, the combination which we took the third element, and the combination which we did not take the third element. The time complexity is O(2^N). The space complexity is O(2^N), too. (This solution is in spired by @ZitaoWang's elegant solution) """ # DFS class Solution(object): def subsets(self, nums): def dfs(path, nums): opt.append(path) if len(nums) == 0: return for i, num in enumerate(nums): dfs(path + [num], nums[i + 1:]) opt = [] dfs([], nums) return opt
true
a1c53091e54ab725dff87a0227df870f5d0bf0ec
warlockee/leetpy
/algos/reorder-list.py
1,063
4.1875
4
""" The reorder list, we can see it as smallest, largest, 2th smallest, 2th largest, 3th smallest... First, put the ordered nodes in a stack, so we can get the largest node by `pop()`. And count how many nodes in total. Second, because the node is already ordered So we only need to insert a large node between every node until we hit the count. Last, remember to put `None` at the end. The tricky part is there may be even count or odd count of nodes in total. When face problem like this, you should approach these test cases by hand. Think about the edge cases. Here: 1->2->3->4 1->2->3->4->5 """ class Solution(object): def reorderList(self, head): if head is None: return h = head curr = head stack = [] count = 0 while curr: count += 1 stack.append(curr) curr = curr.next while count > 1: temp = h.next h.next = stack.pop() h.next.next = temp count -= 2 h = h.next.next h.next = None
true
63f21964fd79aecf64883fd5c365e7fe3dee0160
khanhdodang/automation-training-python
/python_basics/tutorial/08_operators.py
2,801
4.59375
5
''' Python Operators Operators are used to perform operations on variables and values. Python divides the operators in the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators ''' ''' Python Arithmetic Operators Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y ''' ''' Python Assignment Operators Assignment operators are used to assign values to variables: Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3 ''' ''' Python Comparison Operators Comparison operators are used to compare two values: Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y ''' ''' Python Logical Operators Logical operators are used to combine conditional statements: Operator Description Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10) ''' ''' Python Identity Operators Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator Description Example is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y ''' ''' Python Membership Operators Membership operators are used to test if a sequence is presented in an object: Operator Description Example in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y ''' ''' Python Bitwise Operators Bitwise operators are used to compare (binary) numbers: Operator Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off '''
true
3c77e4874b6cb47b768221cd0f338c3aa41d5f7c
khanhdodang/automation-training-python
/python_basics/exercises/39_check_whether_a_string_is_palindrome_or_not.py
599
4.40625
4
''' A palindrome is a string that is the same read forward or backward. For example, "dad" is the same in forward or reverse direction. Another example is "aibohphobia", which literally means, an irritable fear of palindromes. ''' # Program to check if a string is palindrome or not my_str = 'aIbohPhoBiA' # make it suitable for caseless comparison my_str = my_str.casefold() # reverse the string rev_str = reversed(my_str) # check if the string is equal to its reverse if list(my_str) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.")
true
99682c9027ab1edb94e6d4ad1c06ab4b0f4a5b2b
khanhdodang/automation-training-python
/python_basics/tutorial/04_numbers.py
1,898
4.375
4
''' Python Numbers There are three numeric types in Python: int float complex Variables of numeric types are created when you assign a value to them: Example ''' x = 1 # int y = 2.8 # float z = 1j # complex # To verify the type of any object in Python, use the type() function: # Example print(type(x)) print(type(y)) print(type(z)) ''' Int Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. Example Integers: ''' x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z)) ''' Float Float, or "floating point number" is a number, positive or negative, containing one or more decimals. Example Floats: ''' x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z)) ''' Float can also be scientific numbers with an "e" to indicate the power of 10. Example Floats: ''' x = 35e3 y = 12E4 z = -87.7e100 print(type(x)) print(type(y)) print(type(z)) ''' Complex Complex numbers are written with a "j" as the imaginary part: Example Complex: ''' x = 3 + 5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) ''' Type Conversion You can convert from one type to another with the int(), float(), and complex() methods: Example Convert from one type to another: ''' x = 1 # int y = 2.8 # float z = 1j # complex # convert from int to float: a = float(x) # convert from float to int: b = int(y) # convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c)) ''' Note: You cannot convert complex numbers into another number type. Random Number Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers: Example Import the random module, and display a random number between 1 and 9: ''' import random print(random.randrange(1, 10))
true
a729d32d30602b62186e18b88a194029a30e3c29
khanhdodang/automation-training-python
/python_basics/tutorial/18_arrays.py
1,396
4.34375
4
''' Python Arrays Note: Python does not have built-in support for Arrays, but Python Lists can be used instead. Arrays Note: This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have to import a library, like the NumPy library. Arrays are used to store multiple values in one single variable: Example Create an array containing car names: ''' cars = ["Ford", "Volvo", "BMW"] ''' What is an Array? An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: ''' car1 = "Ford" car2 = "Volvo" car3 = "BMW" ''' However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number. Access the Elements of an Array You refer to an array element by referring to the index number. Example Get the value of the first array item: ''' x = cars[0] ''' Example Modify the value of the first array item: ''' cars[0] = "Toyota" ''' The Length of an Array Use the len() method to return the length of an array (the number of elements in an array). Example Return the number of elements in the cars array: ''' x = len(cars)
true