blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
b3766c470429a222a65ad0cf487a6fff64592a26
KartikeyaGaur29/tathastu_week_of_code
/DAY 1/profit.py
365
4.125
4
cost_price = float(input("Enter the Cost Price : ")) selling_price = float(input("Enter the Selling Price : ")) profit = 0 if selling_price > cost_price : profit = selling_price - cost_price print(" The profit =",profit) new_sell_price = selling_price + (0.05*cost_price) print("New selling price for which the profit will increase by 5% =",new_sell_price)
true
25774940a1dfc4a4733ef570bdfd44ca6980dc6b
KartikeyaGaur29/tathastu_week_of_code
/DAY 6/Program10.py
678
4.15625
4
row = int(input("Enter the number of lists you want : ")) list = [] for i in range(0,row): print("Enter the size of list no.",i+1,) col = int(input()) print("Enter the elements : ") sub_list = [] for j in range(0,col): sub_list.append(int(input())) sub_list.sort() list.append(sub_list) print("The entered lists in sorted order are : ") for i in range(0,row): for j in range(0,col): print(list[i][j],end = " ") print() single_list = [] for i in range(0,row): for j in range(0,col): single_list.append(list[i][j]) single_list.sort() print("All lists merged together and sorted in one list :") print(single_list)
true
5d7b3a8c0bcb05248d342e5481b8b87285316fe9
uwaifo/Python-for-Algorithms--Data-Structures--and-Interviews
/Sections/Linked Lists/single_implimantataion.py
1,047
4.34375
4
''' Remember, in a singly linked list, we have an ordered list of items as individual Nodes that have pointers to other Nodes. In a Linked List the first node is called the head and the last node is called the tail. Let's discuss the pros and cons of Linked Lists: Pros Linked Lists have constant-time insertions and deletions in any position, in comparison, arrays require O(n) time to do the same thing. Linked lists can continue to expand without having to specify their size ahead of time (remember our lectures on Array sizing form the Array Sequence section of the course!) Cons To access an element in a linked list, you need to take O(k) time to go from the head of the list to the kth element. In contrast, arrays have constant time operations to access elements in an array. ''' class Node(object): def __init__(self,arg_value): self.value = arg_value self.nextnode = None a = Node(1) b = Node(2) c = Node(3) a.nextnode = b b.nextnode = c print(a.nextnode.value) print(c.nextnode)
true
3cd76a422a490f7cd55239e04459dddf7168e758
uwaifo/Python-for-Algorithms--Data-Structures--and-Interviews
/Sections/Stacks_Queue_Deques/queue_implimemtation.py
1,880
4.4375
4
''' Queue Methods and Attributes Before we begin implementing our own queue, let's review the attribute and methods it will have: ''' class QueueOverstand(object): #Queue() creates a new queue that is empty. It needs no parameters and returns an empty queue. def __init__(self): self.queue_items = [] #enqueue(item) adds a new item to the rear of the queue. It needs the item and returns nothing. def enqueue(self, param): #FIFO #here we use the standard list.insert method to put params at the indicated position of the queuse # here we put it in the 0 index position ie first self.queue_items.insert(0,param) return self.peep_top() #dequeue() removes the front item from the queue. It needs no parameters and returns the item. The queue is modified. def dequeue(self): #FIFO #here again we use the standard list pop method to remove from the buttom of the qeueu #Note that the items at the buttom are the first to have come in return self.queue_items.pop() #isEmpty() tests to see whether the queue is empty. It needs no parameters and returns a boolean value. def isEmpty(self): return self.queue_items == [] ''' if len(self.queue_items) == 0: return True else: return False ''' #size() returns the number of items in the queue. It needs no parameters and returns an integer. def size(self): return len(self.queue_items) def peep_top(self): return self.queue_items[0] food_line = QueueOverstand() print(food_line.isEmpty()) print(food_line.enqueue('Uwaifo')) print(food_line.size()) print(food_line.enqueue('Ifeanyi')) print(food_line.size()) print(food_line.dequeue()) print(food_line.size()) print(food_line.isEmpty())
true
b48fe6db93dad806001b73f28a87ea960b122789
Simbadeveloper/AndelaCodeCamp
/LEVELUP/PL_python/coffee.py
1,295
4.625
5
"""Instruction for coffee machine 1. make and serve me, you and Gibbs a cup of coffee(add coffee, and hot water, stir) 2. change how the mix is stirred 3. A better way to make cofee with less repetition 4. Make you coffe with milk and suger (add suger, and milk) 5. Make Gibbs coffe with milk, sugar and something else (add sugar, milk'...) 6. Refactor """ # make my coffee ingredients = ['coffee', 'hot water'] print ('started making coffee...') print('Getting cup') print('Adding {}'.format(', '.join(ingredients))) print('Stir the mix 6 sec') print('Finished making coffee...') my_coffee = 'Tasty coffee' print("--Here' your {} {}. Enjoy !!!! --\n".format(my_coffee, 'silas')) #make you coffee print ('started making coffee...') print('Getting cup') print('Adding {}'.format(', '.join(ingredients))) print('Stir the mix for 6 sec') print('Finished making coffee...') your_coffee = 'Tasty coffee' print("--Here' your {} {}. Enjoy !!!! --\n".format(your_coffee, 'You')) #make Gibbs coffee print ('started making coffee...') print('Getting cup') print('Adding {}'.format(', '.join(ingredients))) print('Stir the mix for 6 sec') print('Finished making coffee...') gibbs_coffee = 'Tasty coffee' print("--Here' your {} {}. Enjoy !!!! --\n".format(gibbs_coffee, 'Gibbs'))
true
0dd60a107ef46d46be7c69c436f370ec0b69bd00
Uchicago-Stat-Comp-37810/assignment-2-wendy182
/ex4.py
1,787
4.4375
4
# assign 100 to variable "cars", which is the number of cars. cars = 100 # assign 4.0 to variable "space_in_a_car", which is the maximal number of passengers one car can have. space_in_a_car = 4.0 # assign 30 to variable "drivers", which is the number of drives drivers = 30 # assign 90 to variable "passengers", which is the number of total passengers. passengers = 90 # create a variable "cars_not_driven", which is number of cars minus number of drivers. cars_not_driven = cars - drivers # create a variable "cars_driven", which equals the number of drivers. cars_driven = drivers # create a variable "carpool_capacity", which is number of cars driven multiply the maximal amount of passengers one car can have. carpool_capacity = cars_driven * space_in_a_car # create a variable "average_passengers_per_car", which is the number of passengers divided by the number of cars driven. average_passengers_per_car = passengers / cars_driven print("There are", cars, "cars available.") print("There are only", drivers, "drivers available.") print("There will be", cars_not_driven, "empty cars today.") print("We can transport", carpool_capacity, "people today.") print("We have", passengers, "to carpool today.") print("We need to put about", average_passengers_per_car, "in each car.") # Python returned that error because in the 8th line, the writer typed a wrong variable name "car_pool_capacity" instead of the right one "carpool_capacity", while the "car_pool_capacity" is not defined in the above line, so python cannot work on this variable. # Using 4.0 is not necessary, but it is more precise than using 4. If just use 4, then the value of carpool_capacity, which is space_in_a_car multiplying cars_driven, will be 120 - an integer, instead of 120.0 - a floating point number.
true
59b0f36a9f0248af4ee5567a392cfcd1d2bcab20
liqi-yu/python_qi
/python_pc/lianxi5.py
573
4.15625
4
class Date(object): def __init__(self,year=0,month=0,day=0): self.year=year self.month=month self.day=day @classmethod def from_string(cls,date_as_string): year,month,day=map(int,date_as_string.split('-')) datel=cls(year,month,day) return datel @staticmethod def is_date_valid(date_as_string): year,month,day=map(int,date_as_string.split('-')) return day <= 31 and month <=12 and year <=2038 d=Date.from_string('2019-11-11') is_date=Date.is_date_valid('2019-11-11') print(is_date)
true
43bc5cdea90cbd1a39a641bf7aa9e3d57e5aae46
bingwin/python
/python/基础/is_==.py
491
4.15625
4
# -*- coding: utf-8 -*- # Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。 x = [1, 2, 3] y = [1, 2, 3] print(id(x)) print(x == y) # 比较的是数值 相同 print(x is y) # 比较的是内存地址 不同 x.append(4) print(x == y) # 新加值后 不同 print(id(x)) t1 = 'ABC' t2 = 'ABC' print(id(t1), id(t2)) # 字符串相同,因为因为都指向的是'ABC'字符串的内存地址
false
99f2a5578aba43879e0a4ea6d5a32a65e89026c2
bingwin/python
/python/面向对象/函数/参数/arg.py
591
4.3125
4
# -*- coding: utf-8 -*- # Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。 #默认参数 def printinfo(name, age=35): print "Name: ", name print "Age ", age return # 调用printinfo函数 printinfo(age=50, name="miki") printinfo(name="miki") # 不定长参数 # 可写函数说明 def printinfo(arg1, *vartuple): print "输出: " print "arg1:" + str(arg1) for var in vartuple: print var return # 调用printinfo 函数 printinfo(10) printinfo(70, 60, 50)
false
964787c21aaa039b1006c9b6782d868c006a8e30
bingwin/python
/python/内存/memoru_address.py
1,214
4.40625
4
# -*- coding: utf-8 -*- # Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。 # 类属性对于类的所有实例都是相同的,而实例属性对于每个实例都是特定的。 对于两个不同的实例,将有两个不同的实例属性。 class MyClass(object): pass # Create first instance of MyClass this_obj = MyClass() print(this_obj) # Another instance of MyClass that_obj = MyClass() print (that_obj) class InstanceCounter(object): count = 0 # class attribute, will be accessible to all instances def __init__(self, val): self.val = val InstanceCounter.count +=1 # Increment the value of class attribute, accessible through class name # In above line, class ('InstanceCounter') act as an object def set_val(self, newval): self.val = newval def get_val(self): return self.val def get_count(self): return InstanceCounter.count a = InstanceCounter(9) b = InstanceCounter(18) c = InstanceCounter(27) for obj in (a, b, c): print ('val of obj: %s' % (obj.get_val())) # Initialized value ( 9, 18, 27) print ('count: %s' % (obj.get_count())) # always 3
false
f4ef145bfaeb635478909b7891301473f7d016fa
bingwin/python
/python/其他/迭代/yield/yield_test.py
720
4.25
4
# -*- coding: utf-8 -*- # Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。 def yield_test(n): print(n) # 函数这里先输出 for i in range(n): yield call(i) print("i=", i) # 做一些其它的事情 print("do something.") print("end.") def call(i): return i * 2 # 使用for循环 for i in yield_test(5): print(i, ",") # def test_1(): # test = {1, 2, 3} # for i in test: # # print(i) # yield i # print(10) # # # s = test_1() # print(s.next()) # 返回一个1,输出一个1 # print(s.next()) # print(s.next())
false
90950a165a9518f82e9c1789083c419584c9865d
bingwin/python
/python/面向对象/类/属性/shuxing.py
2,810
4.5
4
# -*- coding: utf-8 -*- # Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。 # 每一个与类相关联的方法调用都自动传递实参,它是一个指向实例本身的引用,让它实例能够访问类中的属性和方法。 class Dog(object): def __init__(self,name,mile): self.name = name self.mile = mile def sit(self): print(self.name) # 通过方法让自身属性进行递增 def inc(self,mile): self.mile += mile d = Dog("1", 10) print(d.mile) d.inc(1) print(d.mile) d.inc(2) print(d.mile) print("——————————————————————————————————————————————————") # https://blog.csdn.net/sjyttkl/article/details/80655421 # 属性可以分为两类,一类是Python自动产生的,如__class__,__hash__等,另一类是我们自定义的,如上面的hello,name。我们只关心自定义属性。 # 类和实例对象(实际上,Python中一切都是对象,类是type的实例)都有__dict__属性,里面存放它们的自定义属性(对与类,里面还存放了别的东西)。 class T(object): name = 'name' @property def hello(self): return self.name t = T() t.name = "name2" # t.hello = s # property不可修改 T.hello = 1 print(T.hello) print("dir(t)"+str(dir(t))) print("t.__dict__"+str(t.__dict__)) # 只打印自定义属性 print("——————————————————————————————————————————————————") print(dir(T)) print(T.__dict__) # 除了自定义 还有其他属性 print(T.__dict__['name']) print(T.name) print(t.name) print("——————————————————————————————————————————————————") print(t.__hash__()) print(hash(t)) print(T.__hash__) print(hash(T)) print("——————————————————————————————————————————————————") # Person类很明显能够看出区别,不继承object对象,只拥有了doc , module 和 自己定义的name变量, 也就是说这个类的命名空间只有三个对象可以操作. # Animal类继承了object对象,拥有了好多可操作对象,这些都是类中的高级特性。 class Person: """ 不带object """ name = "zhengtong" class Animal(object): """ 带有object """ name = "chonghong" if __name__ == "__main__": x = Person() print "Person", dir(x) y = Animal() print "Animal", dir(y)
false
b5e94441893339a2fede376bd4aa80dd5ba08430
bingwin/python
/python/基础/continue.py
969
4.3125
4
# -*- coding: utf-8 -*- # Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。 # Python continue 语句跳出本次循环,而break跳出整个循环。 # continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。 # continue语句用在while和for循环中。 for letter in 'Python': # 第一个实例 if letter == 'h': continue print '当前字母 :', letter var = 10 # 第二个实例 while var > 0: var = var - 1 if var == 5: continue print '当前变量值 :', var print "Good bye!" # 当前字母 : P # 当前字母 : y # 当前字母 : t # 当前字母 : o # 当前字母 : n # 当前变量值 : 9 # 当前变量值 : 8 # 当前变量值 : 7 # 当前变量值 : 6 # 当前变量值 : 4 # 当前变量值 : 3 # 当前变量值 : 2 # 当前变量值 : 1 # 当前变量值 : 0 # Good bye!
false
ae64695055ac06a0e3a4c2b835766da7710dcfc9
dlaevskiy/arhirepo
/cookbook/Data structures and algoritms/1_18.py
771
4.40625
4
# 1.18. Mapping Names to Sequence Elements # Problem # You have code that accesses list or tuple elements by position, but this makes the code # somewhat difficult to read at times. You d also like to be less dependent on position in # the structure, by accessing the elements by name. # One possible use of a namedtuple is as a replacement for a dictionary, which requires # more space to store. Thus, if you are building large data structures involving dictionaries, # use of a namedtuple will be more efficient. However, be aware that unlike a dictionary, # a namedtuple is immutable from collections import namedtuple Subscriber = namedtuple('Subscriber', ['addr', 'joined']) sub = Subscriber('jonesy@example.com', '2012-10-19') print sub print sub.addr print sub.joined
true
7263dff1d8697aacd265de539f38d8b442659e6b
dlaevskiy/arhirepo
/cookbook/String and text/2_6.py
208
4.15625
4
# Problem # You need to search for and possibly replace text in a case-insensitive manner. import re text = 'UPPER PYTHON, lower python, Mixed Python' print re.findall('python', text, flags=re.IGNORECASE)
true
e886a736d47f65b04ef013e54c3e577bb92112a3
dlaevskiy/arhirepo
/cookbook/String and text/2_4.py
998
4.4375
4
# 2.4. Matching and Searching for Text Patterns # Problem # You want to match or search text for a specific pattern. text = 'yeah, but no, but yeah, but no, but yeah' # Exact match print text == 'yeah' # False # Search for the location of the first occurrence print text.find('no') # 10 # regular expressions import re text1 = '11/27/2012' text2 = 'Nov 27, 2012' if re.match(r'\d+/\d+/\d+', text1): print 'yes' else: print 'no' # If you are going to perform a lot of matches using the same pattern, it usually pays to # precompile the regular expression pattern into a pattern object first. datepattern = re.compile(r'\d+/\d+/\d+') if datepattern.match(text1): print 'yes' else: print 'no' #groups datepattern = re.compile(r'(\d+)/(\d+)/(\d+)') m = datepattern.match('11/27/2012') print m.group(0) print m.group(1) print m.group(2) print m.groups() month, day, year = m.groups() text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' print datepattern.findall(text)
true
b2ad1d351baa8ff2e12cfc54ff0c3e13d6081903
dlaevskiy/arhirepo
/cookbook/Data structures and algoritms/1_17.py
294
4.1875
4
# 1.17. Extracting a Subset of a Dictionary # Problem # You want to make a dictionary that is a subset of another dictionary. prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } p1 = {key: value for key, value in prices.items() if value > 200} print p1
true
91a7b22c2f5ea2fa865f9964d2556ba456164491
dlaevskiy/arhirepo
/lutc/work_with_class_2_advanced_examples/example7_dictatributes.py
605
4.21875
4
class super(object): """ Hi, this is doc of super class """ def hello(self): self.data1 = 'spam' class sub(super): def hola(self): self.data2 = 'eggs' if __name__ == '__main__': X = sub() print X.__dict__ # dict names of instance print X.__class__ # name of class of instance print sub.__bases__ # super classes of this class Y = sub() X.hello() print X.__dict__ print sub.__dict__.keys() print super.__dict__.keys() print Y.__dict__ print super.__doc__ print X.data1, X.__dict__['data1'] # two the same operations
false
9c04483bcaab5abbd979fc862db0da109a85e45d
abhipannala/GenerativeLSTM
/support_modules/forest_importances.py
2,393
4.21875
4
""" ========================================= Feature importances with forests of trees ========================================= This examples shows the use of forests of trees to evaluate the importance of features on an artificial classification task. The red bars are the feature importances of the forest, along with their inter-trees variability. As expected, the plot suggests that 3 features are informative, while the remaining are not. """ #print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import ExtraTreesClassifier from sklearn.linear_model import LinearRegression import statsmodels.formula.api as smf from sklearn.model_selection import train_test_split from support_modules import nn_support as nsup import pandas as pd def calculate_importances(df, keep_cols): X = df[df.columns.difference(keep_cols)] y = df['ac_index'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 21) # Build a forest and compute the feature importances forest = ExtraTreesClassifier(n_estimators=500, random_state=0) print(X_train.dtypes) forest.fit(X_train, y_train) importances = forest.feature_importances_ imp_table = pd.DataFrame([{'feature':x,'importance':y} for x, y in list(zip(X_train.columns, importances))]) print(imp_table.sort_values(by=['importance'], ascending=False)) # linear regression X = df[df.columns.difference(keep_cols)] y = nsup.scale_feature(df.copy(), 'dur', 'max', True)['dur_norm'] # X = df[df.columns.difference(keep_cols)] # y = df['ac_index'] # create a fitted model with all three features lm1 = smf.ols(formula='dur_norm ~ ev_rd_p + ev_acc_t_norm', data=pd.concat([X, y], axis=1, sort=False)).fit() # lm1 = smf.ols(formula='ac_index ~ city5_norm + ev_acc_t_norm + ev_et_t_norm + snap2_norm', data=pd.concat([X, y], axis=1, sort=False)).fit() # print the coefficients print(lm1.summary()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 21) lm2 = LinearRegression() lm2.fit(X_train, y_train) for x, y in list(zip(X_train.columns, lm2.coef_)): print(x, y, sep=' ') # Print the feature ranking print("Feature ranking:", importances, ' ')
true
36a0a0d836bcef0adff34de94a8fa9690440955e
EdenShapiro/InterviewBit-Questions
/LinkedLists/ReverseLinkedListBetweenPoints.py
2,674
4.28125
4
# Reverse a linked list from position m to n. Do it in-place and in one-pass. # # For example: # Given 1->2->3->4->5->NULL, m = 2 and n = 4, # # return 1->4->3->2->5->NULL. # # Note: # Given m, n satisfy the following condition: # 1 <= m <= n <= length of list. # # Note 2: # Usually the version often seen in the interviews is reversing the whole linked list which is obviously an easier version of this question. class ListNode: def __init__(self, x): self.val = x self.next = None def print_nodes(head): A = head while A: print str(A.val) + " -> ", A = A.next print "None" node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node6 = ListNode(6) node7 = ListNode(7) node8 = ListNode(8) node9 = ListNode(9) node10 = ListNode(10) node11 = ListNode(11) node12 = ListNode(12) node13 = ListNode(13) node14 = ListNode(14) node15 = ListNode(15) node16 = ListNode(16) node17 = ListNode(17) node18 = ListNode(18) def reverse(head): A = head next_node = A.next A.next = None while next_node: temp = next_node.next next_node.next = A A = next_node next_node = temp return A def reverseBetween(A, m, n): head = A m_counter = 1 n_counter = 1 m_node = None m_node_prev = None while A.next and n_counter <= n: if m_counter == m-1 or m == 1: #start reversing print "start reversing" if m == 1: m_node_prev = None m_node = A new_end_of_list = A n_counter -= 1 else: m_node_prev = A m_node = A.next new_end_of_list = A.next next_node = m_node.next while next_node and n_counter < n - 1: temp = next_node.next next_node.next = m_node m_node = next_node next_node = temp n_counter += 1 new_beginning_of_list = m_node new_end_of_list.next = next_node if m == 1: head = new_beginning_of_list else: m_node_prev.next = new_beginning_of_list break m_counter += 1 n_counter += 1 A = A.next return head # For example: # 1->2->3->4->5->NULL, m = 2 and n = 4 # returns 1->4->3->2->5->NULL node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.next = node7 node7.next = node8 node8.next = None m = 4 n = 8 A = node1 print_nodes(reverseBetween(A, m, n))
true
8a88b737a5aa2f5d4bac7e63e1191749a4f9b426
kaikim98/Computing-for-data-science
/HW5/P5.py
1,916
4.15625
4
""" **Instruction** Write P5 function that reads a file and write another file as following - Ignore header(starts with '//'). - If there is any comment mark('#'), remove '#' and move commented parts to the next line - If there is another comment mark in the commented part, move any parts that follows the second comment to the next line. (i.e. A # B # C becomes three lines) - If any line starts with comment mark('#'), remove '#' only. - Assume there is no consecutive '#' in the input file (i.e. '##', '###', ... does not appear in the input file) - Filenames of input and ouput file are entered as input of P5 function - There is no return value of P5 function For example, if the input file has below lines, //Header: description //metals no weight beryllium 4 9.012 magnesium 12 24.305 calcium 20 20.078 #Good for your health #Comment in comment strontium 38 87.62 barium 56 137.327 # This is comment line and ignore radium 88 226 Output file should look as below beryllium 4 9.012 magnesium 12 24.305 calcium 20 20.078 Good for your health Comment in comment strontium 38 87.62 barium 56 137.327 This is comment line and ignore radium 88 226 """ def P5(input_filename: str, out_filename: str): L1 = [] with open(input_filename, 'r') as file: with open(out_filename, 'w') as out: for line in file: if line[0] == '/' and line[1] == '/' : continue if '#' in line[0]: b = line.replace('#', '') L1.append(b) continue if '#' in line[1:]: a = line.replace('#', '\n') L1.append(a) continue else: L1.append(line) for line in L1: out.write(line)
true
b192b2c00c702bf79e3c661728f445bb11729c00
xioperez01/holbertonschool-higher_level_programming
/0x0B-python-input_output/3-write_file.py
278
4.25
4
#!/usr/bin/python3 """ Module 3-write_file.py """ def write_file(filename="", text=""): """ Writes a string to a text file and Returns the number of characters writen """ with open(filename, mode="w") as f: num_char = f.write(text) return num_char
true
d5f77e3e385c811fd0c03d4fda80d0e6007041ac
ShraddhaPChaudhari/PythonWork
/Basic/swapping.py
570
4.3125
4
#to interchange the values of two variable with and without using temp. variable a=int(input('enter the first number')) b=int(input('enter the second number')) print('value of a=',a,' ','value of b=',b) temp=0 temp=a a=b b=temp print('the interchanged values using temp variable are-\nvalue of a=',a,'\nvalue of b=',b) a=int(input('\nenter the first number')) b=int(input('enter the second number')) print('value of a=',a,' ','value of b=',b) (a,b)=(b,a) print('the interchanged values without using temp variable are-\nvalue of a=',a,'\nvalue of b=',b)
true
3f7e4058ae385c86b4d30db8eafa338d97870c5a
meganjacob/Hangman-Game
/project1.py
2,960
4.21875
4
import random print('Let\'s play hangman!') print('If you would live to see a list of the letters you have already guessed, type in \'help\'.') print('If you think you know the word and would like to guess, type in \'guess answer\'.') # bank of random words words = ['study', 'world', 'python', 'coder', 'confuse', 'wonderful', 'forgive', 'water'] # initializing beginning values playGame = True join = ' ' # take input and start playing while playGame == True: lives = 6 usedLetters = [] wordFound = False word = words[random.randint(0,4)] solution = ['_' for i in word] print(join.join(solution)) print('Lives Left: ', lives) #loop in which a round is played, ends once game is won or lost while wordFound == False: #collect input userInput = input('Guess a letter: ') guess = userInput.lower() #if 'help' is entered display used letters if guess == 'help': print('You have already guessed:', ', '.join(usedLetters)) continue #if 'guess answer' is entered allow the user to guess the word if guess == 'guess answer': guess = input('You can guess the word now: ').lower() if guess == word: print('That\'s right! You won!') else: print('Sorry that is incorrect') break # make sure guess is valid if len(guess) != 1 or not (guess.isalpha()): print('Not a valid guess. Please enter a single letter.') continue # check if letter has already been used if guess in usedLetters: print('You have already guessed this letter.') continue # store used letter in an array to keep track of usedLetters.append(guess) # check if guess is correct if guess in word: index = word.find(guess) solution[index] = guess print (join.join(solution)) print('Lives Left: ', lives) else: print("Letter not found!") print (join.join(solution)) lives -= 1 if lives > 0: print('Lives Left: ', lives) continue else: print('Out of lives, game over!') break # check if game has been won if ''.join(solution) == word: wordFound = True print('Word guessed, you\'ve won!') # check if user wants to keep playing and validate options valid = False while (valid == False): play = input('Play again? (yes/no)\n') playAgain = play.lower() if playAgain == 'no': playGame = False valid = True elif playAgain == 'yes': print('New game!') valid = True else: print('Please enter a valid option.') continue
true
02c113d8b593c023e3c3061caf0ee84cc2ed600e
ipableras/PildorasInformaticasPython
/TrabajoConListas.py
472
4.3125
4
# Listas # doc python trabajadores =["Ana", "María", "Antonio", "Miguel"] print(trabajadores) print(len(trabajadores)) print(trabajadores.index("Antonio")) trabajadores.append("Juan") print(trabajadores) print(trabajadores[2]) print(trabajadores) print(trabajadores[-2]) print(trabajadores) print() # Borrar Maria print(trabajadores) del trabajadores[1] print(trabajadores) print() print(trabajadores[0:3]) print(trabajadores[2:3]) print(trabajadores[3:2])
false
0124acdaceb0697ba1caaa2226a04fc3cd1f0371
sucongCJS/leetCode
/Queue_Stack/Queue/circular_queue.py
2,621
4.46875
4
class Node: def __init__(self, value): self.val = value self.pre = self.next = None class MyCircularQueue: def __init__(self, k): """ Initialize your data structure here. Set the size of the queue to be k. :type k: int """ self.size = k self.curSize = 0 # is it necessary to name head and tail seperately? # the answer is no: we only use the head.next and tail.pre, so they can be in the same add with diff name self.head = self.tail = Node(-1) self.head.next = self.tail self.tail.pre = self.head def enQueue(self, value): """ Insert an element into the circular queue. Return true if the operation is successful. :type value: int :rtype: bool """ if self.curSize < self.size: node = Node(value) node.pre = self.tail.pre node.next = self.tail # the order must be self.tail.pre.next = node, then self.tail.pre = node # the evaluation order can be learnt from: https://www.v2ex.com/amp/t/443384 # which is self.tail.pre.next = node, then self.tail.pre = self.tail.pre.next self.tail.pre.next = self.tail.pre = node self.curSize += 1 return True return False def deQueue(self): """ Delete an element from the circular queue. Return true if the operation is successful. :rtype: bool """ if self.curSize > 0: self.head.next = self.head.next.next self.head.next.pre = self.head self.curSize -= 1 return True return False def Front(self): """ Get the front item from the queue. :rtype: int """ return self.head.next.val def Rear(self): """ Get the last item from the queue. :rtype: int """ return self.tail.pre.val def isEmpty(self): """ Checks whether the circular queue is empty or not. :rtype: bool """ return self.curSize == 0 def isFull(self): """ Checks whether the circular queue is full or not. :rtype: bool """ return self.curSize == self.size if __name__ == "__main__": a = MyCircularQueue(8) print(a.enQueue(3)) print(a.enQueue(9)) print(a.enQueue(5)) print(a.enQueue(0)) print(a.deQueue()) print(a.deQueue()) print(a.isEmpty()) print(a.isEmpty()) print(a.Rear()) print(a.Rear()) print(a.deQueue())
true
31db6292da9af8161d3a87898c40abd83ebc9b52
SidMallya/fibonacci
/fibonacci.py
308
4.125
4
n = int(input("How many Fibonnaci numbers do you want to print? (must be greater than 1)\n")) while n < 2: n = int(input("Please enter a number greater than 1.\n")) fib = [0, 1] print(fib[0],end=' ') print(fib[1],end=' ') while len(fib) < n: fib.append(fib[-2]+fib[-1]) print(fib[-1],end=' ')
false
62e3bfcfaeb8c73d050d72e686d041ea6c3a655e
aridokmecian/PySort
/bubbleSort.py
455
4.21875
4
def bubbleSort(arr): #Iterate backwards through elements from index at len(arr) to 0 for iteration in range (len(arr) - 1, 0, -1): #iterates through elements up to specificed iteration in previous line for i in range(iteration): #swaps elements if the current element is larger then the following element if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr
true
4eb45af25759a714129b5f343deece370b17054a
bibhuty-did-this/MySolutions
/Math/ProjectEuler010.py
685
4.15625
4
# All we have to do is to store the sum of all the prime numbers till that number in a lookup table # Function to find prime number from math import sqrt def isPrime(n): limit=int(sqrt(n)) i=3 while i<=limit: if n%i==0:return False i+=2 return True # Code for the lookup table summations=[] summations.append(0) summations.append(0) summations.append(2) sum=2 for i in range(3,1000000,2): if isPrime(i): sum+=i summations.append(sum) summations.append(sum) else: summations.append(sum) summations.append(sum) # Dispaly the result for _ in range(int(raw_input())): print summations[int(raw_input())]
true
6367fc33d63e3e5f057faf18920e72775cd50116
CodingGearsCourses/Python-Advanced-Concepts
/Module-04-Generators/py04_generator_expression_list.py
337
4.28125
4
# Copyright 2020 https://www.globaletraining.com/ # Simple "for" loops can be written using generator expression # Sample list animals = ['dog', 'cat', 'hen', 'fox', 'elephant'] # TODO: Generator Expression <<< animals_upper_gen = (animal.upper() for animal in animals if animal != "fox") # TODO: Print print(list(animals_upper_gen))
true
7626d501503a73d464f069f6667ad81c65621bf1
CodingGearsCourses/Python-Advanced-Concepts
/Module-02-Comprehensions/01_list_comprehensions_02.py
846
4.15625
4
# Copyright https://www.globaletraining.com/ # List comprehensions provide a concise way to create lists. def main(): my_numbers = [18, 32, 74, 34, 69, 2, 4, 52, 61, 32, 11, 5, 17, 95, 96, 18, 38, 35, 49, 89, 54, 44, 99, 29] my_numbers_double = [] for n in my_numbers: my_numbers_double.append(n*2) print(my_numbers_double) # TODO: Using Comprehension my_numbers_double_comp1 = [n * 2 for n in my_numbers] print(my_numbers_double_comp1) # TODO: Using Comprehension & condition (evens) my_numbers_double_comp2 = [n * 2 for n in my_numbers if n % 2 == 0] print(my_numbers_double_comp2) # TODO: Using Comprehension & condition (range) my_numbers_double_comp3 = [n * 2 for n in my_numbers if n % 2 == 0 if n > 50] print(my_numbers_double_comp3) if __name__ == '__main__': main()
false
519c0826ab84015ee3513fb32b6120522fdf0c60
hmathlee/matrixtools
/rref.py
2,525
4.125
4
def swap(a, b): temp = a a = b b = temp def row_reducer(): # Perform the Gauss-Jordan Method for a given matrix, inputted by the user rows = input("Please input the number of rows in the matrix:") # set number of rows while int(rows) < 1: rows = input("Error: number of rows must be a positive integer:") columns = input("Please input the number of columns in the matrix:") # set number of columns while int(columns) < 1: columns = input("Error: number of columns must be a positive integer:") new_row = 1 # create empty matrix in the form of a list of lists (each sub-list represents one row) m = [] while new_row < int(rows) + 1: m.append([]) new_row += 1 for i in range(1, int(rows) + 1): # fill in values of matrix for j in range(1, int(columns) + 1): value = input("Please input the value at Row " + str(i) + ", Column " + str(j) + " of the matrix:") m[i - 1].append(float(value)) for b in range(0, int(rows) - 1): # bring all zero rows to the bottom of the matrix for a in range(0, int(rows) - 1): if m[a] == [0] * int(columns): temp = m[a] m[a] = m[a + 1] m[a + 1] = temp for c in range(0, int(columns)): # perform elementary row operations for r in range(c, int(rows)): if m[r][c] == 0: for row_check in range(r + 1, int(rows)): if m[row_check][c] != 0: t = m[row_check] m[row_check] = m[r] m[r] = t else: for row_operate in range(0, int(rows)): if row_operate == r: continue else: factor = m[row_operate][c] / m[r][c] m[row_operate] = list(map(lambda x, y: x - factor * y, m[row_operate], m[c])) for t in range(0, int(rows)): # simplify if m[t] == [0] * int(columns): continue else: for s in range(0, int(columns)): if m[t][s] == 0: continue else: m[t] = list(map(lambda x: x / m[t][s], m[t])) break for u in range(0, int(rows)): # remove any unnecessary negative signs in front of zeroes for v in range(0, int(columns)): if m[u][v] == 0: m[u][v] = abs(m[u][v]) print(m)
true
4cda2b5151683b7d654d58a5e8eb72c867d9ca0d
MITRE-South-Florida-STEM/ps1-summer-2021-AshmitaPersaud
/ps1b.py
616
4.28125
4
annual_salary = float(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ")) total_cost = float(input("Enter the cost of your dream home: ")) semi_annual_raise = float(input("Enter the semi-annual raise, as a decimal: ")) current_savings = 0 r = .04 months = 0 portion_down_payment = total_cost*0.25 while current_savings < portion_down_payment: current_savings += portion_saved*(annual_salary/12)+ current_savings*(r/12) months += 1 if months%6 == 0: annual_salary += annual_salary*semi_annual_raise print("Number of months:", months)
true
cb68c9256afa162a163489fc043c8d5341890565
anshjoseph/problems_hackerrank
/Organizing_Containers_of_Balls.py
2,651
4.5
4
""" David has several containers, each with a number of balls in it. He has just enough containers to sort each type of ball he has into its own container. David wants to sort the balls using his sort method. David wants to perform some number of swap operations such that: Each container contains only balls of the same type. No two balls of the same type are located in different containers. Example David has containers and different types of balls, both of which are numbered from to . The distribution of ball types per container are shown in the following diagram. image In a single operation, David can swap two balls located in different containers. The diagram below depicts a single swap operation: image In this case, there is no way to have all green balls in one container and all red in the other using only swap operations. Return Impossible. You must perform queries where each query is in the form of a matrix, . For each query, print Possible on a new line if David can satisfy the conditions above for the given matrix. Otherwise, print Impossible. Function Description Complete the organizingContainers function in the editor below. organizingContainers has the following parameter(s): int containter[n][m]: a two dimensional array of integers that represent the number of balls of each color in each container Returns string: either Possible or Impossible Input Format The first line contains an integer , the number of queries. Each of the next sets of lines is as follows: The first line contains an integer , the number of containers (rows) and ball types (columns). Each of the next lines contains space-separated integers describing row . """ def organizingContainers(container): # Write your code here number_of_container = len(container[0]) number_of_content = len(container) max_col = list() transform_container = list() #col max for i in range(number_of_container): max_col.append(max([j[i] for j in container])) transform_container.append([j[i] for j in container]) # print(transform_container) # print(max_col) pass if __name__ == "__main__": test = True if not test: test_case = int(input()) martixs = list() for _ in range(test_case): size = int(input()) temp = list() for __ in range(size): row = list(map(int,input().split(" "))) temp.append(row) martixs.append(temp) organizingContainers(martixs) else: test_data = [[1 ,3 ,1],[2, 1, 2], [3, 3, 3]] organizingContainers(test_data)
true
f5ce518e365469eca7b84ce89123724783c66652
anshjoseph/problems_hackerrank
/The_Time_in_Words.py
1,965
4.46875
4
""" Given the time in numerals we may convert it into words, as shown below: At , use o' clock. For , use past, and for use to. Note the space between the apostrophe and clock in o' clock. Write a program which prints the time in words for the input given in the format described. Function Description Complete the timeInWords function in the editor below. timeInWords has the following parameter(s): int h: the hour of the day int m: the minutes after the hour Returns string: a time string as described Input Format The first line contains , the hours portion The second line contains , the minutes portion """ def timeInWords(H,M): minutes = ['zero','one','two','three','four','five', 'six','seven','eight','nine','ten', 'eleven','twelve','thirteen','fourteen', 'fifteen','sixteen','seventeen','eighteen', 'nineteen','twenty','twenty one', 'twenty two', 'twenty three','twenty four','twenty five', 'twenty six','twenty seven','twenty eight', 'twenty nine', 'thirty'] hours = ['zero','one','two','three','four','five', 'six','seven','eight','nine','ten','eleven','twelve'] return_str = "" if M == 0: return_str += f"{hours[H]} o' clock" elif M == 15: return_str += f"quarter past {hours[H]}" elif M == 30: return_str +=f"half past {hours[H]}" elif M == 45: if H == 12: return_str += f"quarter to {hours[1]}" else: return_str += f"quarter to {hours[H+1]}" elif M > 0 and M < 30: return_str += f"{minutes[M]} minutes past {hours[H]}" elif M > 30 and M < 60: if H == 12: return_str += f"{minutes[60-M] } minutes to {hours[1]}" else: return_str += f"{minutes[60-M] } minutes to {hours[H + 1]}" return return_str if __name__ == "__main__": Hour = int(input()) Min = int(input()) print(timeInWords(Hour,Min))
true
61230c0f37ae3457ad094f0e5d453c5119afe56d
ziolkowskid06/Algorithms
/Sorting algorithms/heap_sort.py
1,033
4.21875
4
""" """ def heapify(arr, heap_size, root_index): """Assumes part of array is already sorted""" # Assume the index of the largest element is the root index largest = root_index left_child = (2*root_index) + 1 right_child = (2*root_index) + 2 if left_child < heap_size and arr[left_child] > arr[largest]: largest = left_child if right_child < heap_size and arr[right_child] > arr[largest]: largest = right_child if largest != root_index: arr[root_index], arr[largest] = arr[largest], arr[root_index] heapify(arr, heap_size, largest) def heap_sort(arr): length = len(arr) # Create a Max Heap from the list. for i in range(length, -1, -1): heapify(arr, length, i) # Move the root of the max heap to the end of the list. for i in range(length-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] heapify(arr, i , 0) array = [44, 21, 2, 10, 32, 45, 10] heap_sort(array) print(array)
true
e78857601698a97411807523e05d3d164922b86c
maldonadoangel/PythonPractice
/clases_y_objetos/Aritmetica.py
1,400
4.25
4
class Aritmetica(): def __init__(self, numero1 = 0.0, numero2 = 0.0, total = 0.0): self.numero1 = numero1 self.numero2 = numero2 self.total = total def suma(self): self.total = self.numero1 + self.numero2 print(f'La suma de {self.numero1} + {self.numero2} = {self.total}') def resta(self): self.total = self.numero1 - self.numero2 print(f'La resta de {self.numero1} - self.numero2 = {self.total}') def multiplicacion(self): self.total = self.numero1 * self.numero2 print(f'La multiplicacion de {self.numero1} * {self.numero2} = {self.total}') def division(self): if self.numero2 == 0: print('Error la division no puede ser efectuada, no puedes tener un cero en el denominador, intentalo de nuevo') else: self.total = self.numero1 / self.numero2 # la notacion :.3f se utiliza para establecer la cantidad de decimales que tendra nuestra respuesta, en este caso es de 3 decimales print(f'La division de {self.numero1} / {self.numero2} = {self.total:.3f}') aritmetica = Aritmetica(10, 50) aritmetica.suma() aritmetica.resta() aritmetica.multiplicacion() aritmetica.division() print() print('------------------------------') aritmetica2 = Aritmetica(30, 1) aritmetica2.suma() aritmetica2.resta() aritmetica2.multiplicacion() aritmetica2.division()
false
74b6dc9fbfd2c26789fd1b997dfd1b8e8a392103
3lton007/HackerRank_Codes
/HackerRank_codes/Even_integers.py
430
4.125
4
""" Even Integers """ def even(start, n): result = list() if start % 2 == 1: # Make start even start += 1 while len(result) < n: # Adding start to the result list result.append(start) # Incrementing start by 2 start += 2 return result def main(): start = int(input()) n = int(input()) print(even(start, n)) main()
true
bbea688b5742f1d6e242c1f045bd39839b9e43a2
TECHMONSTER2003/Shape-AI-Python-Network-Security-Bootcamp
/hashing.py
1,143
4.21875
4
import hashlib #print(hashlib.algorithms_available) #I have used md5,shake_128,sha3_512 str0=input("enter a string to hash : ") str1=str0.encode() #I dont know why hashlib can accpet only encoded values but i read online that encoding is must print("single MD5 hash of ",str0," is : ",hashlib.md5(str1)) print("single shake_128 hash of ",str0," is : ",hashlib.shake_128(str1)) print("single sha3_512 hash of ",str0," is : ",hashlib.sha3_512(str1)) #nerd alert!!!!!!! print("lets go for iterations and salting😉") samp_str='abcdefghijklmnopqrstuvwxyz' #making some string for salting usage strx,hash,k='','',0 if len(str0)<=len(samp_str): for i in str0: strx=strx+i+samp_str[k] k=k+1 else: strx="a"+(str0)+'b' print(strx,"salting performed") str1=strx.encode() hash=hashlib.md5(str1) n=int(input("enter the number of iterations : ")) hashlist=[] #initialising an empty list to store hash values for i in range(n-1): #as its already hashed one time, I have used n-1 hashlist.append(hashlib.md5(str1)) print("Salting and ",n," iterations performed md5 hashing of ",str1," is",hashlist[n-2])
true
0e65478673efe1c87194bd2cae0f77fac3cd8c55
Welith/python_crash_course
/data science/chapter 1/primes.py
215
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 7 16:20:23 2018 @author: bkolev95 """ prime = [2, 3, 5, 7, 11, 13] for number in prime: print(number) prime.append('17') print(prime)
false
9f705a39b09fb352ed3f51c665d22671339252cc
daniel-saeedi/DataStructureAlgorithm
/CA1/Question3.py
2,237
4.125
4
""" Calculating prime numbers from 1 to sqrt(n). You can uncomment this : """ # from itertools import compress #n = 10**5 # def primes(n): # """ Returns a list of primes < n for n > 2 """ # sieve = bytearray([True]) * (n//2) # for i in range(3,int(n**0.5)+1,2): # if sieve[i//2]: # sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1) # return [2,*compress(range(3,n,2), sieve[1:])] # primeslist = primes(int(n**0.5)+1) """ For time efficiency I calculated this before""" primeslist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313] numbers_set = list() def insert_divisors(n, counter_dict): i = 1 # Note that this loop runs till square root while i <= n**(1/2): if (n % i == 0) : if (n / i == i): counter_dict[i] = counter_dict.get(i, 0) + 1 else : counter_dict[i] = counter_dict.get(i, 0) + 1 counter_dict[n//i] = counter_dict.get(n//i, 0) + 1 i = i + 1 """ Returns a list of the prime factorization of n """ def factorization(n, primeslist): pf = [] for p in primeslist: if p*p > n : break count = 0 while not n % p: n //= p count += 1 if count > 0: pf.append((p, count)) if n > 1: pf.append((n, 1)) return pf """ Returns an unsorted list of the divisors of n """ def insert_divisors(n, primeslist, counter_dict) : divs = [1] for p, e in factorization(n, primeslist): divs += [x*p**k for k in range(1,e+1) for x in divs] for div in divs: counter_dict[div] = counter_dict.get(div, 0) + 1 def count_divisors(query, counter_dict): if query not in counter_dict: return 0 return counter_dict[query] def main() : i = 1 counter_dict = {} max_lines = int(input()) while i <= max_lines : a,b = input().split() a = int(a) b = int(b) if a == 1 : numbers_set = insert_divisors(b, primeslist, counter_dict) else : print(count_divisors(b, counter_dict)) i += 1 main()
true
9daf216931af282f0f3d6fa33956c0baa0da6a12
BrendanArthurRing/code
/katas/opposite-number.py
776
4.5
4
# https://www.codewars.com/kata/opposite-number/train/python ''' Very simple, given a number, find its opposite. Examples: 1: -1 14: -14 -34: 34 ''' def opposite(number): return number * -1 # The best practice def opposite(number): return -number # Test Block class Test: def assert_equals(a, b): if a == b: print("Passed \n \n") if a != b: print(f"Failed\n{a} should equal {b}\n\n") def describe(text): print(text) def expect_error(text, test_function): print(text) if test_function == ZeroDivisionError: print("Passed") print("Failed") def it(text): print(text) Test.assert_equals(opposite(1), -1)
true
0c4e4218de0e43e9e0bab70c42a8b98626b636b2
BrendanArthurRing/code
/katas/perimiter-squares-rectangle.py
1,987
4.28125
4
# https://www.codewars.com/kata/559a28007caad2ac4e000083 ''' The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It's easy to see that the sum of the perimeters of these squares is : 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80 Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing: alternative text # Hint: See Fibonacci sequence # Ref: http://oeis.org/A000045 The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares. perimeter(5) should return 80 perimeter(7) should return 216 ''' class Test: def assert_equals(a, b, hint=None): if a == b: print("Passed \n \n") if a != b: print(f"Failed\n{a} should equal {b}\n\n") if hint: print(hint) def describe(text): print(text) def expect_error(text, test_function): print(text) if test_function == ZeroDivisionError: print("Passed") print("Failed") def it(text): print(text) # Here is my code def perimeter(n): arr = [1, 1] for i in range(n - 1): arr.append(arr[i] + arr[i + 1]) x = 4 * sum(arr) return x # Best Practice was def fib(n): a, b = 0, 1 for i in range(n+1): if i == 0: yield b else: a, b = b, a+b yield b def perimeter(n): return sum(fib(n)) * 4 # Clever was def perimeter(n): a, b = 1, 2 while n: a, b, n = b, a + b, n - 1 return 4 * (b - 1) # Tests Test.assert_equals(perimeter(5), 80) Test.assert_equals(perimeter(7), 216) Test.assert_equals(perimeter(20), 114624) Test.assert_equals(perimeter(30), 14098308) Test.assert_equals(perimeter(100), 6002082144827584333104
true
44cbc9e2e01f11b6e422de10093c5eabca044bb6
Fawe0000/Algoritms_for_Python
/lesson_2/les_2_task_3.py
475
4.25
4
#3. Сформировать из введенного числа обратное по порядку входящих в него цифр # и вывести на экран. Например, если введено число 3486, надо вывести 6843. def obr(in_n): obr_i = '' while in_n > 0: obr_i = obr_i + str(in_n % 10) in_n //= 10 return obr_i n = int(input('Введте натуральное число: ')) print(obr(n))
false
3505c381100094c312d2c695243a78fa2df0cec0
Cpasgrave/Python-Challenges
/Golden_Mountain.py
2,016
4.59375
5
# -*- coding: utf-8 -*- ''' Challenge: 'The Golden Mountain' At one international Olympiad in Informatics, the following task was given. Let's solve it! 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 The figure shows an example of a triangle of numbers. Write a program that calculates the largest sum of numbers through which the path starts, starting at the top and ending somewhere on the bottom. Each step can go diagonally down to the right or diagonally to the left. In the example - this is the path 7➡3➡8➡7➡5, given a max amount of 30. by rudolph flash ''' from random import choice # this code is better suited to watch with computers than phones. # P(n, m, M) will produce a random pyramid, # n being its height, # m = min value M = max value : P = lambda n,m,M:[[choice(range(m, M+1))for j in range(i)]for i in range(1,n+1)] # You can tune the settings here (first height, then min and max values): pyramid = P(1000,-999,999) # V(p) prints the pyramid with a readable form: V=lambda p:[[print("{}{}".format(" "*(len(p)-len(r)),''.join([str(c)+(" "*(5-len(str(c))))for c in r])))]for r in p] # solve function returns max path # and a solved pyramid def solve(p): t=[p[-1]] ; s = [] ; k = 0 # Here it makes a new pyramid, adding each local value # with the max from both values under it for r in range(-1,-len(p),-1): t.insert(0,[max(i,j)+k for i, j, k in zip(t[r], t[r][1:], p[r-1])]) # extracting total (max path) to be able to return it tot = t[0][0] # here, replacing all the values not in the path with "-" # and bringing back path valules from the original # (not summed) pyramid for g in range(len(p)): t[g] = [" - " for i in t[g][:k]]+[p[g][k]]+[" - " for i in t[g][k+1:]] if g != len(p)-1: if t[g+1][k] < t[g+1][k+1]: k += 1 return t, tot # applying : # V(pyramid) solution = solve(pyramid) print(" ") # V(solution[0]) print(" ") print("max path :", solution[1])
true
1e68e0e4a17a1fbf7305ba2e0c01b1551343baed
Cpasgrave/Python-Challenges
/alphabet parser.py
699
4.125
4
""" This codes takes two letters as input and returns the ordered alphabet letters from the first to the second, in ascending or descending order depending on the given letters. """ alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] range=[] first=input("first ?\n") print(first) last=input("last ?\n") print(last) if (first not in alphabet) or (last not in alphabet) : print("Sorry girl, you can enter latine letters only, try harder !") else : range.append(first) x=(alphabet.index(first)) y=(alphabet.index(last)) while(y>x): x+=1 range.append(alphabet[x]) while(x>y): x-=1 range.append(alphabet[x]) print(range)
true
8da7b5ca48cec0631ed953da0d820505bb109a74
JAbrantesRadiology/PythonCrashCourse
/magic_number.py
705
4.125
4
answer = 17 if answer != 42: print("That is not the correct answer.") age= 19 print(age<21) print(age>15) print(age<=21) print(age>22) #To check if two conditions are both true at the same time, use the "and" - if #both conditions are passed, the True value is given. print("\nNew test 'And' ") age_0 = 22 age_1 = 18 print(age_0 >=21 and age_1 >=21) age_0 = 22 age_1 = 21 print(age_0 >=21 and age_1 >=21) #For readability print((age_0>=21) and (age_1 >=21)) #To check if any of the conditions are true , use the "or" - if #one of the conditions passes, the True value is given. print("\nNew test 'Or' ") age_0 = 22 age_1 = 18 print(age_0 >=21 or age_1 >=21) age_0=18 print(age_0 >=21 or age_1 >=21)
true
d5e1f6a47fbb750b4e207953c05296817decab00
Gahyki/NumericalMethods
/2 - Nonlinear equations/25 - ClosedFalsePositionIter.py
801
4.3125
4
import numpy as np def f(x): #define your function here return x**2 - 3 def m(a, b): #middle return (a+b)/2 def xc(a, b): return (a*f(b) - b*f(a))/(f(b)-f(a)) def inter(a, b, xc): if f(a)*f(xc) < 0: return (a, xc) elif f(b)*f(xc) < 0: return (xc, b) else: return "This doesn't work" #running the script its = int(input("How many iterations are required? ")) + 1 a = int(input("What is the value of a? ")) b = int(input("What is the value of b? ")) for i in range(its): print("\n") #change the range middle = xc(a,b) iteration = inter(a, b, middle) print(iteration) if iteration == "This doesn't work": break a = iteration[0] b = iteration[1] print("Approximation of the root is: " + str(m(a, b)))
true
d1d6c9daf70536a4c1eea7660f5901ad5b9c7da3
akiselev1/hackerrank-solutions
/words_score.py
1,106
4.15625
4
""" Created by akiselev on 2019-07-18 In this challenge, the task is to debug the existing code to successfully execute all provided test files. Consider that vowels in the alphabet are a, e, i, o, u and y. Function score_words takes a list of lowercase words as an argument and returns a score as follows: The score of a single word is 2 if the word contains an even number of vowels. Otherwise, the score of this word is 1. The score for the whole list of words is the sum of scores of all words in the list. Debug the given function score_words such that it returns a correct score. Your function will be tested on several cases by the locked template code. """ def is_vowel(letter): return letter in ['a', 'e', 'i', 'o', 'u', 'y'] def score_words(words): score = 0 for word in words: num_vowels = 0 for letter in word: if is_vowel(letter): num_vowels += 1 if num_vowels % 2 == 0: score += 2 else: score += 1 return score n = int(input()) words = input().split() print(score_words(words))
true
61a23e3def13f015cb8db3e4a73a69de1a059dfb
akiselev1/hackerrank-solutions
/html_parser3.py
1,217
4.34375
4
""" Created by akiselev on 2019-07-15 You are given an HTML code snippet of N lines. Your task is to detect and print all the HTML tags, attributes and attribute values. Print the detected items in the following format: Tag1 Tag2 -> Attribute2[0] > Attribute_value2[0] -> Attribute2[1] > Attribute_value2[1] -> Attribute2[2] > Attribute_value2[2] Tag3 -> Attribute3[0] > Attribute_value3[0] The -> symbol indicates that the tag contains an attribute. It is immediately followed by the name of the attribute and the attribute value. The > symbol acts as a separator of attributes and attribute values. If an HTML tag has no attribute then simply print the name of the tag. Note: Do not detect any HTML tag, attribute or attribute value inside the HTML comment tags (<!-- Comments -->). Comments can be multiline. All attributes have an attribute value. """ from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print (tag) [print('-> {} > {}'.format(*attr)) for attr in attrs] # instantiate the parser and fed it some HTML parser = MyHTMLParser() parser.feed(''.join([input().strip() for _ in range(int(input()))])) parser.close()
true
9c8a165ed037a61866c7b0827a74244e21343fdf
akiselev1/hackerrank-solutions
/re_roman.py
448
4.21875
4
""" Created by akiselev on 2019-06-27 You are given a string, and you have to validate whether it's a valid Roman numeral. If it is valid, print True. Otherwise, print False. Try to create a regular expression for a valid Roman numeral. The number will be between 1 and 3999 (both included). """ regex_pattern = r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$" import re print(str(bool(re.match(regex_pattern, raw_input()))))
true
7cb2a31347964c3d85d458034bbbb0eabe7591f3
Justin-Keener/CS-1301
/HW 1/hw1.py
1,979
4.125
4
# Part 2: Functions # Parameters: N/A # Returns: N/A import math def mars_weight(): """Ask the user what is his or her weight on her, convert that weight to what it would be on mars. Then print out that weight. """ earth_wght = float(input('What is your weight? ')) mars = (earth_wght*.38) print('At a weight of ', int(earth_wght), ' pounds you would weigh ', int(mars), ' pounds on Mars.',"\n") mars_weight() # Function: Volume of a cone # # Parameters: N/A # Returns: Volume of the Cone def volume_of_cone(): """The function uses the input values of the parameters to return a value for the volume of the cone.""" r = int(input('What is the length of the radius of the cone? ')) h = int(input('What is the height of the cone? ')) v = float((math.pi*r*r*h)/3) return v print("{:.3f}".format((volume_of_cone())),"\n") # Function: Liquid Converter # Parameters: N/A # Return Value def liquid_converter(): """ The function is an user-interactive function to convert any number of fluid ounces to the equivalent number of gallons, quarts, pints, and gills." """ fluid_oz = int(input("How many fluid ounces would you like to convert? ")) galls = fluid_oz // 128 new1_fluid_oz = fluid_oz - (galls*128) quart = new1_fluid_oz // 32 new2_fluid_oz = new1_fluid_oz - (quart*32) pint = new2_fluid_oz // 16 new3_fluid_oz = new2_fluid_oz - (pint*16) gill = new3_fluid_oz // 4 print(fluid_oz, " fluid ounces is ", galls, " gallon(s) ", quart, " quart(s) ", pint , " pint(s) ", gill, " gill(s)", "\n") liquid_converter() # Function: main # Parameter: N/A # Return Value: N/A def main(): init = int(input("Which function would you like to call? ")) if init == 1: mars_weight() elif init == 2: volume_of_cone() elif init == 3: liquid_converter() else: print("Not a function") for i in range(3): main()
true
f5b2acc13da36f663166f70d58a6db691d6c0c93
fanzhangg/algorithm-problems
/maths/linear/functions.py
2,578
4.125
4
import numpy def horner(coeffs: [int or float], x: int or float, is_decr=True)->int: """ This function evaluate a polynomial via Horner's method :param coeffs: :param x: :param is_decr: :return: """ if is_decr: ans = coeffs[0] for i in range(1, len(coeffs)): ans = ans * x + coeffs[i] else: ans = coeffs[-1] for i in range(len(coeffs) - 2, -1, -1): ans = ans * x + coeffs[i] return ans def nest(coeffs: list, x: int or float, base_points: list)-> int or float: """ Evaluates polynomial from nested form using Horner’s Method :param coeffs: coefficients (constant term first) :param x: x-coordinate :param base_points: a list of base points :return: value of polynomial at x """ y = coeffs[-1] for i in range(len(coeffs) - 2, -1, -1): y = y * (x - base_points[i]) + coeffs[i] return y def int_dec_to_bin(num: int)->str: """ :param num: an integer :return: the binary number of num """ bins = [] while True: bins.insert(0, str(num % 2)) num = num // 2 if num == 0: return "".join(bins) def frac_dec_to_bin(frac: float, accurates: int)->str: """ :param frac: the fraction of a float :param accurates: the accuracies of the binary number :return: a binary number of a fraction """ bins = [] if frac >= 1 or frac < 0: raise ValueError("frac must be a fraction") for _ in range(accurates): frac = frac * 2 frac_int = int(frac // 1) frac = frac % 1 bins.append(str(frac_int)) frac = frac return "".join(bins) def float_dec_to_bin(fl: float, accurates: int)->str: """ :param fl: a float number :param accurates: the accuracies of the binary number :return: the binary number of the float """ int_str = int_dec_to_bin(int(fl)) frac_str = frac_dec_to_bin(fl % 1, accurates) return ".".join((int_str, frac_str)) def int_bin_to_dec(bin_str: str): """ :param bin_str: a binary integer :return: the decimal integer """ ans = 0 for i in range(len(bin_str)): x = int(bin_str[i]) p = len(bin_str) - 1 - i ans += x * (2 ^ p) return ans def frac_bin_to_dec(bin_str: str): ans = 0 for i in range(len(bin_str)): x = int(bin_str[i]) p = len(bin_str) - i ans += x * 1 / (2 ^ p) return ans nest([1, 1/2, 1/2, -1/2], 1, [0, 2, 3]) horner([13, 9, 2, 6, 3], 2, is_decr=False)
true
3b882f93fb76e8139ca51baa2a7d64872c52c9fb
fanzhangg/algorithm-problems
/searching/binary_search.py
2,510
4.46875
4
""" # Binary Search ## Algorithm: - Exam the middle item - If it is not the correct item - Use the ordered nature of the list to ignore half of the remaining items - If the item > the middle: - ignore the lower half & the middle one - search the upper half ## Running Time: O(log n) - Each time eliminate half of the remaining items - If we start with n items, items left in comparison i: n/2^i, until n/2^i = 1(i = log n) - The max number of comparison is logarithmic to the number of items in the list * Aware the cost of search """ def binary_search(items: list, target)->bool: """ Implement the binary search as a recursive function * Slicing takes O(k) time :return: true if the target item is in the list """ if len(items) == 0: return False else: mid_i = len(items) // 2 if items[mid_i] == target: return True elif items[mid_i] < target: # Search the right half return binary_search(items[mid_i+1:], target) else: # Search the left half return binary_search(items[:mid_i], target) def binary_search_2(items: list, target)->bool: """ Implement the binary search using while loop """ start_i = 0 end_i = len(items) - 1 while True: mid_i = (start_i + end_i) // 2 if items[mid_i] == target: return True elif items[mid_i] < target: # Search the right half start_i = mid_i + 1 else: # Search the left half end_i = mid_i - 1 if start_i > end_i: break return False def binary_search_3(items: list, start_i: int, end_i: int, target)->bool: """ Implement the binary search as a recursive function by passing the starting and ending indices :param start_i: starting index :param end_i: ending index :param target: the target item to search :return: true if the target item is in the list """ if start_i > end_i: return False else: mid_i = (start_i + end_i) // 2 if items[mid_i] == target: return True elif items[mid_i] < target: # search right half of the list start_i = mid_i + 1 return binary_search_3(items, start_i, end_i, target) else: end_i = mid_i - 1 return binary_search_3(items, start_i, end_i, target) binary_search([3, 5, 6, 8, 11, 12, 14, 15, 17, 18], 8)
true
ca09d9c0dd94109e79e75d47bc070dc94641838b
fanzhangg/algorithm-problems
/sorting/algorithms/shell_sort.py
826
4.28125
4
""" # Shell sort - Break the original list into a number of smaller sublists, each of which is sorted using an insertion sort; - Use an increment `i` to create a sublist by choosing all items that are `i` items apart """ def shell_sort(items: list): sublist_count = len(items) // 2 while sublist_count > 0: for start_i in range(sublist_count): gap_insertion_sort(items, start_i, sublist_count) sublist_count = sublist_count // 2 def gap_insertion_sort(items: list, start, gap): for i in range(start + gap, len(items), gap): current_value = items[i] position = i while position >= gap and items[position - gap] > current_value: items[position] = items[position - gap] position = position - gap items[position] = current_value
true
575d8081932f2a4c708bf312e98318628534489a
Shankar11/My_DataScience_Track
/My_Learnings/Python/quick_sort.py
696
4.15625
4
from statistics import median def quick_sort(array): #three arrays are created left_arr = [] match = [] right_arr = [] # size of our array if len(array) > 1: pivot = median([array[0],array[int((len(array)-1)/2)],array[len(array)-1]]) #sorting the numbers to the defined arrays for x in array: if x < pivot: left_arr.append(x) if x == pivot: match.append(x) if x > pivot: right_arr.append(x) # using recursive call return quick_sort(left_arr)+match+quick_sort(right_arr) else: return array print(quick_sort([9,5,1,-5,10,0,23, 7]))
true
6731826d20e5c4bba01748b7377885162e0fe719
hartzis/py-fun
/optimusprime.py
1,847
4.4375
4
#------------------------------------------------------------------------------- # Name: optimusPrime # Purpose: Figure out if a number is a prime # # Author: brian hartz # # Created: 18-11-2013 # Copyright: (c) brianhartz 2013 # Licence: <your licence> #------------------------------------------------------------------------------- def optimusPrime(test_num): # test if number is even a number let alone an integer if not type(test_num) == int: print "Not a valid input integer" return # check if number is divisible by 2 or <=7 or zero, # then create list of numbers for prime testing, explained below if test_num in (0,1): print "Number {} is not a prime".format(test_num) return elif test_num in (2,3,5,7): print "Number {} is a prime".format(test_num) return # see prime test below for explination elif test_num % 2 == 0: print "Number {} is not a prime, divisible by 2".format(test_num) return else: # Create a list of all numbers that are less than (test_num/2) test_list = range((test_num/2)) # reverse list for prime test test_list.reverse() # prime test: Loop through all numbers in test_list, and if the remainder of # test_num / test_list is equal to zero, then it is not a prime, unless the # list gets all the way to 1, then it is a prime. All of this is quickly # calculated using the amazing modulo operator '%' for i in test_list: if test_num % (i) == 0: if i == 1: print "Number {} is a prime".format(test_num) return else: print "Number {} is not a prime, divisible by {}".format(test_num, (i)) return def main(): pass if __name__ == '__main__': main()
true
ab573effe7f113014780a10858def7956398020e
lambdaschoolcoursework/introduction-to-python-i-and-ii
/src/13_file_io.py
912
4.15625
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # open up the 'data.txt' file (which already exists) for reading # print all the contents of the file, then close the file # note: pay close attention to your current directory when trying to open 'data.txt' import os directory = os.getcwd() data = open(f'{directory}\src\data.txt', 'r') print(data.read()) data.close() # open up a file called 'bar.txt' (which doesn't exist yet) for writing # write three lines of arbitrary content to that file, then close the file # open up 'bar.txt' and inspect it to make sure that it contains what you expect it to contain bar = open('src/bar.txt', 'w+') bar.write('first line\n') bar.write('second line\n') bar.write('third line\n') bar.close() # need directory in one but not the other?
true
fe06199e7c4582af2ffb7cf956dbcfb79c9d926f
mancol01/python-repo-1
/vital/sqrt_2Args.py
326
4.21875
4
############################################ x=int(input("Enter the value of x:\n")) a=int(input("Enter the value of a :\n")) def my_sqrt(a, x): print(x) while True: y = (x + a/x) / 2.0 print(y) if y == x: break x = y return y print(my_sqrt(a, x))
true
5c75cdf4be6994e09f9375da85ddbb563e336ef4
Shreyankkarjigi/Python--Codes
/Data Structures/Bubble sort.py
1,579
4.125
4
#Bubble sort algorithm (comparison based sorting) #sorting with comparison algo ''' In bubble sort,we compare and sort adajacent elements and are swapped, with smaller elements to left and larger element to right This algo is not suitable for larger dataset as its worse case scenario is O(n2) How bubble sort works in following manner: consider an unsorted list [14,33,27,35,10] lets compare 14 and 33 first 14<33 ,so they are in correct position next we compare 33 and 27 27<33 so we swap [14,27,33,35,10] next we compare 33 and 35 33<35 so no need to swap next we compare 35,10 10<35 swap [14,27,33,10,35] iteation 1 ends here,but list isnt sorted yet so we iterate again until 10 comes to right position [10,14,27,33,35] ''' #implementation #define function,pass sequence as parameter def bubble(sequence): #define range,this will till len of sequence-1 as we cant compare last element with anything r=len(sequence)-1 #for now lets sorted=False,this wiil act as exit point in loop sorted=False #we use while loop , if list is already sorted , return list as it is while not sorted: #sorted=true sorted=True #check each element in list,compare with adjacent element for i in range(r): if sequence[i]>sequence[i+1]: #set sorted as false sorted=False #swap sequence[i],sequence[i+1]=sequence[i+1],sequence[i] return sequence #call function ,pass unsorted list as argument print(bubble([14,33,27,35,10]))
true
3b5b8a93c44e782be70cc13d6c79870795334978
Shreyankkarjigi/Python--Codes
/Problems on Strings/string2.py
837
4.21875
4
#Code by Shreyank #Github-https://github.com/Shreyankkarjigi #problem #input a string from user #input a index value from user #input second string from user #concat second string to first string at given index ''' example string1="shreyank" string2="karjigi" index=1 output=skarjigireyank index element is completely removed and replaced with second string ''' string1=str(input("enter first string")) string2=str(input("enter second string")) index=int(input("enter index value")) new_string=string1[0:index]+string2+string1[index+1:] print(new_string) ''' altenatively dont remove the char just add the string skarjigihreyank ''' new_string2=string1[0:index]+string2+string1[index:] print(new_string2) ''' output enter first stringshreyank enter second stringkarjigi enter index value1 skarjigireyank skarjigihreyank '''
false
f8de3cbd0c6cec95e83731dc7adb711a2a92e8e5
Shreyankkarjigi/Python--Codes
/Problems on Lists/Remove duplicates and display the list.py
975
4.5
4
#Code by Shreyank #Github-https://github.com/Shreyankkarjigi #problem ''' You have a list of items containing lot of duplicates in it.Your task is to make a new list where all the duplicates have been removed , also from the original list display the most repeated number. sample input [1,2,3,4,5,5,5,5,6,6,7,7,7] sample output [1,2,3,4,5,6,7] most repeated item is: 5 ''' #For sake of less code i considered a predefinend list , you can also ask user and add to list my_list=[1,2,3,4,5,5,5,5,6,6,7,7] print("Here is my original list\n") print(my_list) # serach most repeated number in list , for this convert the list to set and count max duplicates # why use key and count? # most_rep=max(set(my_list),key=my_list.count) print("Most repeated number in list is:",most_rep) #remove the duplicates from list , to do this simply convert the list to set as set cannot contain any duplicates new_list=set(my_list) print("List without duplicates\n") print(new_list)
true
ce0dec2a9c9de83ad73b72b211eefb0c680d58fe
Shreyankkarjigi/Python--Codes
/Problems on Lists/Check list for duplicate elements.py
603
4.34375
4
#Code by Shreyank #Github-https://github.com/Shreyankkarjigi #problem ''' wap to check if a list contains any duplicat elements logic Take a list check its len convert the list to set (since set cannot contain duplicates the len of both will differ) also when you convert a list with duplicate elements to set all the duplicates are ignored from set ''' my_list=[1,2,3,4,4] #you can input and store too logic remains same if len(my_list)==len(set(my_list)): print("list contains no duplicates") else: print("list has duplicates") ''' output: my_list=[1,2,3,4,4] list has duplicates '''
true
9a4a7eb1efb664a0ba95fdf922b2245b5f7b8898
Shreyankkarjigi/Python--Codes
/Data Structures/queue using function.py
1,564
4.15625
4
#queue using function ''' queue are abstract data structure that uses a two way list to enter and remove elements in que elements are entered from one side and removed from other side, it is based on FIFO (First in,first out) approach push() is used to add elements to queue pop() is used to remove elements from queue queue is implemented using deque which is imported from collections module ''' from collections import deque queue=deque([]) #push function def push(queue): for i in range(10): print("pushing element",i,"to queue") queue.append(i) print(queue) def pop(queue): for j in range(10): print("removing element",queue.popleft(),"from queue") print(queue) if not queue: print("queue is now empty") print(push(queue)) print(pop(queue)) ''' output pushing element 0 to queue pushing element 1 to queue pushing element 2 to queue pushing element 3 to queue pushing element 4 to queue pushing element 5 to queue pushing element 6 to queue pushing element 7 to queue pushing element 8 to queue pushing element 9 to queue deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) None removing element 0 from queue removing element 1 from queue removing element 2 from queue removing element 3 from queue removing element 4 from queue removing element 5 from queue removing element 6 from queue removing element 7 from queue removing element 8 from queue removing element 9 from queue deque([]) queue is now empty None '''
true
978cc4fa41bc809622d02ce44cbc4fd56717eb59
didierrevelo/holbertonschool-higher_level_programming-1
/0x07-python-test_driven_development/3-say_my_name.py
650
4.625
5
#!/usr/bin/python3 """ this method print to full name in format My name is <first name> <last name> """ def say_my_name(first_name, last_name=""): """say_my_name Args: first_name ([str]): [first name] last_name (str, optional): [last name]. Defaults to "". Raises: TypeError: [if first name is not str] TypeError: [if last name is not str] """ 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") print("My name is {:s} {:s}".format(first_name, last_name))
true
97f39f1abf7154430c67707586854db4085f8be8
rammanur/PYTHON_FUN
/rock_paper_scissors.py
2,917
4.25
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 12 13:53:38 2013 @author: rammanur Rock-paper-scissors template The key idea of this program is to equate the strings "rock", "paper", "scissors" to numbers as follows: 0 - rock 1 - paper 2 - scissors """ import random rock, papers, scissors = range(3) rps_names = ["rock", "paper", "scissors"] rock, papers, scissors = range(3) rps_names = ["rock", "paper", "scissors", ""] # v2 helper functions def number_to_name_v2(number): # convert number to a name using if/elif/else # don't forget to return the result! len = rps_names.__len__() if (number < 0): return rps_names[len] if (number >= len): return rps_names[len] return (rps_names[number]) def name_to_number_v2(name): # Converts given name to number # Rock = 0, Paper = 1, Scissors = 2 if name in rps_names: return rps_names.index(name) else: return (-1) # v1 helper functions def number_to_name(number): # convert number to a name using if/elif/else # don't forget to return the result! name = "" if (number == 0): name = "rock" elif (number == 1): name = "paper" elif (number == 2): name = "scissors" else: name = "" return (name) def name_to_number(name): # Converts given name to number # Rock = 0, Paper = 1, Scissors = 2 retval = -1 if (name == "rock"): retval = 0 elif (name == "paper"): retval = 1 elif (name == "scissors"): retval = 2 else: retval = -1 return (retval) def rps(player_name): # convert name to player_number using name_to_number player_wins, comp_wins = 0, 0 player_number = name_to_number(player_name) if (player_number == -1): return print "Player chooses %s" % (player_name,) # compute random guess for comp_number using random.randrange() comp_number = random.randrange(0, 3) # compute difference of player_number and comp_number modulo five difference = comp_number - player_number # use if/elif/else to determine winner #if (difference == 1 or difference == -2): # comp_wins = 1 #elif (difference == -1 or difference == 2): # player_wins = 1 if (comp_number == player_number): player_wins = 1 elif (comp_number > player_number || ) # convert comp_number to name using number_to_name comp_name = number_to_name(comp_number) print "Computer chooses %s" % (comp_name,) # print results if (player_wins): print "Player wins!" elif (comp_wins): print "Computer wins!" else: print "Its a tie!" print "\n" # test your code rps("rock") rps("paper") rps("scissors") rps("rock") rps("paper") rps("scissors") # always remember to check your completed program against the grading rubric
true
5026367a15b0e36fe1d48961af8b35ade8b002a6
Robbot/w3resourcesPython
/Basic/20_40/Ex25.py
752
4.15625
4
"""25. Write a Python program to check whether a specified value is contained in a group of values Test Data : 3 -> [1, 5, 8, 3] : True -1 -> [1, 5, 8, 3] : False""" def is_in_list(num): numbers = [1, 5, 8, 3] return num in numbers num = int(input("Please enter a number: ")) # print(f"See True if this number is in list of numbers or False if it is not: {is_in_list(num)}") if is_in_list(num) == True: print(f"{num} is in the list of numbers") else: print(f"{num} is not in the list of numbers") """Sample solution was def is_group_member(group_data, n): for value in group_data: if n == value: return True return False print(is_group_member([1, 5, 8, 3], 3)) print(is_group_member([5, 8, 3], -1)) """
true
f17affee0d6a6df8fa1a6de6055c3c6971b94e3f
rbolt13/python-test
/yahtzee.py
1,075
4.125
4
""" This is will eventually be the game of yahtzee. For now, it outputs and saves the roll of six dice. ----------------------------------------------- Sources : Write Yahtzee in Python : https://colab.research.google.com/drive/1I_0h72NlXz7YH29FES0qNyus_NvlsPV2 https://stackoverflow.com/questions/44008489/dice-rolling-simulator-in-python/44009898 """ """ import random print("Welcome to Yahtzee") txt = "Your first roll is {}, {}, {}, {}, {}, {}" die1 = random.randint(1,6) die2 = random.randint(1,6) die3 = random.randint(1,6) die4 = random.randint(1,6) die5 = random.randint(1,6) die6 = random.randint(1,6) print(txt.format(die1, die2, die3, die4, die4, die5, die6)) """ import random random.randint(1,6) def rollDice(n): rolls = [random.randint(1,6) for i in range (n)] return rolls currRolls = rollDice(5) print(currRolls) counts = [currRolls.count(1), currRolls.count(2),currRolls.count(3), currRolls.count(4), currRolls.count(5), currRolls.count(6)] print(counts) maxCount = max(counts) print (maxCount) maxVal = counts.index(maxCount) print(maxVal+1)
true
ef602f800ce33cbdf574ee2fa144e1bcdb28de51
sindredl/Python-IS-206
/Other exercises/ex30.py
1,345
4.46875
4
# -*- coding: utf-8 -*- people = 30 cars = 40 buses = 15 #Checks if cars is greater than people, if it is it checks if people is greater than buses, then it prints out additional information if cars > people: print "We should take the cars" if cars > people and people > buses: print "The bus have no room for us" #else if the cars is less than people elif cars < people: print "We should not take the cars." # if no one of these are true then this will be printed else: print "We can't decide." #if buses is greater than cars it will print this if buses > cars: print "That's too many buses" # else if buses are less than cars it will print this elif buses < cars: print "Maybe we could take the buses." # if no one of the two if's over are true, this will be printed else: "We still can't decide" #if people are greater than buses in numbers this will be executed and printed if people > buses: print "Alright, let's just take the buses." # if the condition over is not met(true) this else statement will be executed and print out the text else: print "Fine, let's stay home then." #executes this statement if people are greater than buses or if cars are less than buses if people > buses or cars < buses: print "We can possible take the bus. I dont know if the cars are enough" else: print "I dont know what we should do!"
true
37b94555d80835fe96a28cbc4145776eb3590603
Fyziik/python_exam
/9._session_9/innerFunctions.py
523
4.125
4
# In python we dont have to return a specific value for a function, we can also have a function return a function def calculate(a, b, method): if method == 1: def add(a, b): return int(a) + int(b) return add(a, b) elif method == 2: def subtract(a, b): return int(a) - int(b) return subtract(a, b) a = input('First number: ') b = input('Second number: ') toDo = input('1. to add, 2. to subtract: ') result = calculate(a, b, int(toDo)) print(result)
true
ad339e2c472f01a2f0fe38afd04b12695549f4ab
Fyziik/python_exam
/10._session_10/exercises/2._schoolOfStudents.py
1,769
4.4375
4
# In this exercise you start out by having a list of names, and a list of majors. # Your job is to create: # A list of dictionaries of students (ie: students = [{‘id’: 1,’name’: ‘Claus’, ‘major’: ‘Math’}]), created in a normal function that returns the result. # A Generator that “returns” a generator object. So the student is yield instead of returned. # Both functions should do the same, but one returns a list and one a generator object. # students = [{‘id’: 1,’name’: ‘Clasu’, ‘major’: ‘Math’}] # The id could be generated by a counter or like in a loop. # The Name should be found by randomly chosing a name from the names list # The Major should be found by randomly chosing a major from the major list import random names = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas'] majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business'] def students_list(num_students): student_list = [] for i in range(num_students): id = i name = random.choice(names) major = random.choice(majors) student = { "id" : id, "name" : name, "major" : major } student_list.append(student) return student_list def students_generator(student_list): length = len(student_list) for i in range(length): yield student_list[i] # Create iterable dictionary of students people_list = students_list(2) print (people_list) # Generate generator people_gen = students_generator(people_list) test = (i for i in people_gen) # Step through generator and print steps print(next(test)) print(next(test)) # Stop Iteration sets in print(next(test)) (i for i in range(10)) (x ** 2 for x in range(10) if x % 2 == 0)
true
d500dd7e84f0c2a7e9aa721bab9d56f7d318c644
amyghotra/IntroToCS
/floodMap.py
817
4.125
4
#flood map #this program assumes that you have file 'elevationsNYC.txt' on your computer #import libraries which will be used import numpy as np import matplotlib.pyplot as plt #reads the information on the file, and puts it onto an array, "elevations" elevations = np.loadtxt("elevationsNYC.txt") #this loads the array into plt plt.imshow(elevations) #determines the color of the pixel based on the elevation if elevations[row,col] > 6: #colors the pixel gray elevations[row,col,0] = 0.5 elevations[row,col,1] = 0.5 elevations[row,col,2] = 0.5 elif elevations[row, col] <= 20: #colors the pixel gray elevations[row,col,0] = 0.5 elevations[row,col,1] = 0.5 elevations[row,col,2] = 0.5 else: #colors the piexel green elevations[row,col,1] = 1.0 #shows the plot plt.show()
true
c0b2b118c6ee441a93c3938b9961d84d6392d8fa
wildkoala/wp_code_work
/object_oriented_programming/staticmethods.py
2,038
4.1875
4
import datetime my_date = datetime.date(2016, 7, 10) # Instance methods affect just that instance # class methods affect all instances of a class # static methods don't automatically take self OR cls as a parameter. They behave just like regular functions, just attached to a particualr class. class Employee: # This variable defined before the init is known as a class variable. The instances themselves don't have this attribute, so it checks the next level up, which is the variables for the entire class. raise_amount = 1.04 num_of_emps = 0 # declared as a class variable bc we cant think of a case where we would want the total number of workers to be different between instances. def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + "@company.com" Employee.num_of_emps += 1 # increments the class variable. Prefixed with the class name so that it knows we aren't looking for a variable within the mapping of that particular instance. def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amount) # could also do Employee.raise_amount. That would then be applied to every member of the class not just that particular instance @classmethod # adding this decorator is all you need to do to specify that it applies/uses variables that are part of the class and not just an instance. def set_raise_amt(cls, amount): # used cls instead of class because class is a reserved word. cls.raise_amount = amount @classmethod # this now allows us to take strings and instatiate our class without having the users need to write a parser themselves. def from_string(cls, emp_str): first, last, pay = emp_str.split('-') return cls(first, last, pay) @staticmethod def is_workday(day): if day.weekday() == 5 or day.weekday() == 6: return False return True print(Employee.is_workday(my_date))
true
73b8e0a21f5571d397ca4fabe1851d3c2554cd6e
janicechau12/data-structure-algorithm
/leetcode/Tree/Medium/117.py
1,238
4.15625
4
# 117. Populating Next Right Pointers in Each Node II # Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. # Initially, all next pointers are set to NULL. """ # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next """ class Solution(object): def connect(self, root): """ :type root: Node :rtype: Node """ if root is None: return root queue = [] queue.append(root) while(len(queue) > 0): size = len(queue) for i in range(size): # BFS node = queue.pop(0) if (i < size -1) : node.next = queue[0] if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root # explanation - https://www.youtube.com/watch?v=gc0pFTn90zg # solution - https://zhenyu0519.github.io/2020/03/13/lc117/
true
2a1284597c961faa87eb310e72461c64d3936560
MohammadBNA/Guessing-Game
/main.py
1,762
4.15625
4
from random import randint chosen_number = randint(1,101) guess_total = 0 guess_list = [] last_guess = 0 correct_guess = False print('Welcome to The Guessing Game\nThe Program has picked a random number\nAnd you must guess what that number is') print('the number is between 1 and 100, so you must chose a number in this range') print('After your first guess, if you are within 10 numbers of the desired number, you will see "Warm"') print('Otherwise you will see "Cold", in the subsequent guesses, if you are closer to the number, you will see "Warmer!"') print('Otherwise you will see "Colder", Finaly when you guess the number, the program will tell how many tries it took') while correct_guess == False: last_guess = int(input('What number do you pick?')) if 0 >= last_guess or last_guess >= 101: print('You are out of range! pick again.') guess_total += 1 continue elif last_guess == chosen_number: print(f'You have chosen correctly! it took you {guess_total} tries to do so.') correct_guess = True else: if guess_total == 0: if abs(chosen_number-last_guess) < 11: print('Warm') guess_list.append(last_guess) guess_total += 1 else: print('Cold') guess_list.append(last_guess) guess_total += 1 else: if abs(chosen_number-guess_list[-1]) > abs(chosen_number-last_guess): print('Warmer!') guess_list.append(last_guess) guess_total += 1 else: print('Colder!') guess_list.append(last_guess) guess_total += 1
true
ca9eaaa0f3fcfcb9d2550229c15b2792c7d3eb20
Silverkinzor/PythonCC
/PythonCC10-13.py
1,867
4.15625
4
# 10-13. Verify User: The final listing for remember_me.py assumes either that the # user has already entered their username or that the program is running for the # first time. We should modify it in case the current user is not the person who # last used the program. # Before printing a welcome back message in greet_user(), ask the user if # this is the correct username. If it’s not, call get_new_username() to get the correct # username. import json def get_stored_username(): """Get stored username if available.""" filename = 'username.json' try: with open(filename) as f_obj: username = json.load(f_obj) except (FileNotFoundError, ValueError): return None else: return username def get_new_username(): """Prompt for a new username.""" username = input("What is your name? ") filename = 'username.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username def verify_user(): """Checks if the current user was also the last user""" while True: correct_username = input('Is this the correct username? (Y/N) ') correct_username = correct_username.lower().strip() if correct_username == 'y' or correct_username == 'n': break else: print('Enter one of the options.') return correct_username def greet_user(): """Greet the user by name.""" username = get_stored_username() correct_username = '' if username: print(username) correct_username = verify_user() if username and correct_username == 'y': print("Welcome back, " + username + "!") else: username = get_new_username() print("We'll remember you when you come back, " + username + "!") greet_user()
true
a09d17f2f4761f6ef0075c1871e2b79057158935
Silverkinzor/PythonCC
/PythonCC10-05.py
1,234
4.34375
4
# 10-5. Programming Poll: Write a while loop that asks people why they like # programming. Each time someone enters a reason, add their reason to a file # that stores all the responses. # Each time someone enters a reason... not a data collection phase and then a work phase, but at once. ok. filename = 'programming_poll.txt' polling_active = True print('Thank you for taking this poll!') while polling_active: # a while True, break statement would work just as well. name = input('\nName?: ') reason = input('Why do you like programming?: ') with open(filename, 'a') as file_object: file_object.write(name.title() + ': ' + reason + '\n') while True: try_again = input('\nWill another person take the poll? (Y/N): ') try_again = try_again.strip().lower() if try_again == 'y' or try_again == 'n': break if try_again == 'n': polling_active = False print('\nPolling finished, output stored in programming_poll.txt') # side note: # reminder to create an extension of PythonCC6-E3 to allow inputs within the program # or maybe even from a text file, and then outputs the result to a text file, not just the program
true
215c91b8a0135015b02d558127fc2821bdc0254e
Silverkinzor/PythonCC
/PythonCC3-01.py
391
4.3125
4
# 3-1. Names: Store the names of a few of your friends in a list called names. Print # each person’s name by accessing each element in the list, one at a time. # I'll use names of the keions instead of friends :P names = ['Yui', 'Mio', 'Ritsu', 'Mugi'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) # Using a For Loop: # for x in names: # print(x)
true
0e453ee247267f1845cc788da4974f8de0caf1b3
Silverkinzor/PythonCC
/PythonCC5-04.py
755
4.28125
4
# 5-4. Alien Colors #2: Choose a color for an alien as you did in Exercise 5-3, and # write an if-else chain. # - If the alien’s color is green, print a statement that the player just earned # 5 points for shooting the alien. # - If the alien’s color isn’t green, print a statement that the player just earned # 10 points. # - Write one version of this program that runs the if block and another that # runs the else block. print('V. 1') alien_colour = 'green' if alien_colour == 'green': points = 5 else: points = 10 print(str(points) + ' points earned!') print('\nV. 2') alien_colour = 'yellow' if alien_colour == 'green': points = 5 else: points = 10 print(str(points) + ' points earned!')
true
61d3a1f771f36a6a92ef886ce273080296452ceb
Silverkinzor/PythonCC
/PythonCC3-09.py
1,626
4.3125
4
# 3-9. Dinner Guests: Working with one of the programs from Exercises 3-4 # through 3-7 (page 46), use len() to print a message indicating the number # of people you are inviting to dinner. # Using PythonCC3-06 guests = ['lawrence', 'holo', 'col'] for guest in guests: print('Hey ' + guest.title() + ", you're invited to dinner! ") # What was intended, probably: # print('Hey ' + guests[0].title() + ", you're invited to dinner! ") # print('Hey ' + guests[1].title() + ", you're invited to dinner! ") # print('Hey ' + guests[2].title() + ", you're invited to dinner! ") print("\n" + str(len(guests)) + " people are invited to dinner!") guests.remove('col') print("\nCol can't make it. :(") for guest in guests: print(guest.title() + ", you're still invited!") # print(guests[0].title() + ", you're still invited!") # print(guests[-1].title() + ", you're still invited!") print("\n" + str(len(guests)) + " people are invited to dinner!") print("\nHey all, I've found a bigger dinner table so I will be inviting more guests!") guests.insert(0, 'mio') guests.insert(1, 'ritsu') guests.append('yui') guests.append('mugi') print('') for guest in guests: print(guest.title() + ", you're invited!") # print(guests[0].title() + ", you're invited!") # print(guests[1].title() + ", you're invited!") # print(guests[2].title() + ", you're invited!") # print(guests[3].title() + ", you're invited!") # print(guests[4].title() + ", you're invited!") # print(guests[5].title() + ", you're invited!") print("\n" + str(len(guests)) + " people are invited to dinner!")
true
cbc5e9e8489b08be437edff570b8972044f74148
Silverkinzor/PythonCC
/PythonCC9-01.py
1,175
4.375
4
# All this stuff about classes is a bit overwhelming # It kind of makes sense, though. Kind of. # 9-1. Restaurant: Make a class called Restaurant. The __init__() method for # Restaurant should store two attributes: a restaurant_name and a cuisine_type. # Make a method called describe_restaurant() that prints these two pieces of # information, and a method called open_restaurant() that prints a message indicating # that the restaurant is open. # Make an instance called restaurant from your class. Print the two attributes # individually, and then call both methods. class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(self.restaurant_name.title() + ' serves ' + self.cuisine_type + '.') def open_restaurant(self): print(self.restaurant_name.title() + ' is now open!') restaurant = Restaurant('mcdonalds', 'fast food') print(restaurant.restaurant_name) print(restaurant.cuisine_type) restaurant.describe_restaurant() restaurant.open_restaurant()
true
1fb2b517f59551fa4f6bedc625cf85d0244438d5
Silverkinzor/PythonCC
/PythonCC8-07.py
1,495
4.625
5
# 8-7. Album: Write a function called make_album() that builds a dictionary # describing a music album. The function should take in an artist name and an # album title, and it should return a dictionary containing these two pieces of # information. Use the function to make three dictionaries representing different # albums. Print each return value to show that the dictionaries are storing the # album information correctly. # Add an optional parameter to make_album() that allows you to store the # number of tracks on an album. If the calling line includes a value for the number # of tracks, add that value to the album’s dictionary. Make at least one new # function call that includes the number of tracks on an album. # note: # number = 0 # when number is used as a boolean, it returns false # but number != 0 used as a boolean returns true albums = [] def make_album(name, title, number=0): album = {'artist': name, 'title': title} if number: album['number_of_tracks'] = int(number) return album blue_turtles = make_album('sting', 'dream of the blue turtles', 10) albums.append(blue_turtles) jazz = make_album(title='jazz', name='queen') albums.append(jazz) moody_blue = make_album('elvis presley', 'moody blue') albums.append(moody_blue) for single_album in albums: print(single_album) for info_type, info in single_album.items(): print(info_type.title() + ': ' + str(info).title()) print('')
true
313b6f2fc984e23ffe406a29734f69c03de90cea
AlexanderEfrem/Phyton-Homeworks-
/HomeWork1/Task4.py
907
4.34375
4
#4. Пользователь вводит целое положительное число. # Найдите самую большую цифру в числе. # Для решения используйте цикл while и арифметические операции. value = 0 while value <=0: value = int(input("Введите целое положительно число ")) if value <=0: value = int(input("Введите целое положительно число ")) else: string = str(value) index = 0 maxValue = 0 while int(string[index]) > int(maxValue): maxValue = string[index] index = index + 1 if (index >= len(string)): print("Максимальное число = ", maxValue) exit() print("Максимальное число = ", maxValue)
false
51fdd6c05e51a37b04ec458f52de2ab30609a948
realdip/SoftServeTrainee
/triangles.py
2,057
4.1875
4
class Triangle: def __init__(self, name, sides, area): self.name = name self.sides = sides self.area = area def __str__(self): return "[{}]: {} cm²".format(self.name, self.area) def triangle_area(sides): a, b, c = sides p = (a + b + c) / 2 if p <= a or p <= b or p <= c: return None area = ((p - a) * (p - b) * (p - c)) ** 0.5 return round(area, 2) def create(): name = input("Имя: ") valid_sides = None while not valid_sides: sides = input("Стороны через запятую: ").replace(' ', '').split(',') try: a, b, c = sides sides = (abs(float(a)), abs(float(b)), abs(float(c))) except ValueError: print('Некорректный ввод:', sides) except TypeError: print('Некорректный ввод:', sides) if len(sides) == 3: area = Triangle.triangle_area(sides) if area: valid_sides = True return Triangle(name, sides, area) else: print('Ошибка ввода:', sides) print('Нельзя построить треугольник по заданым сторонам') else: print("Введенное количество сторон не 3") def start(): new_triangles = [] repeat = True while repeat: new_triangles.append(Triangle.create()) answer = input("Введите 'y' или 'yes' чтобы продолжить: ").lower() if answer not in ('yes', 'y'): # or just press ENTER repeat = None print('\nОтсортировано:') i = 1 for self in sorted(new_triangles, key=lambda x: x.area): print('{}. [Треугольник {}]: {} сm²'.format(i, self.name, self.area)) i += 1 if __name__ == "__main__": start()
false
0a02188b82c08d755e727c571aa9d0f95b009557
critoma/armasmiot
/labs/workspacepy/tutorial-python/p004_lists.py
411
4.3125
4
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print (list) # Prints complete list print (list[0]) # Prints first element of the list print (list[1:3]) # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting from 3rd element print (tinylist * 2) # Prints list two times print (list + tinylist) # Prints concatenated lists
true
a2c2e5731c45c165b0d5cb306bac6dbeb364b64d
divyakhemlani22/AdvancedPython
/Lists2.py
1,417
4.375
4
# Lists: ordered, mutable, allows duplicate elements mylist = ["banana","cherry","apple"] print(mylist) #creating a list # Goes to the last item in the list item = mylist[-1] print(item) # using a loop to print the list for x in mylist: print(x) # checking if element is inside the list if "banana" in mylist: print("yes") else: print("no") # checking number of elements inside the list print(len(mylist)) # adding another element to the list mylist.append("lemon") print(mylist) # pop element mylist.pop() print(mylist) # removing element mylist.remove("cherry") print(mylist) # clearing list mylist.clear() print(mylist) # reversing list mylist.reverse() # printing 2 elements in the list mylist = [1,2,3,4,5,6,7,8,9] a = mylist[::2] print(a) new_list = sorted(mylist) print(mylist) print(new_list) mylist = [0] * 5 print(mylist) mylist2 = [1,2,3,4,5] new_list = mylist + mylist2 print(new_list) # printing range from 1 to 5 exclude the first mylist3 = [1,2,3,4,5,6,7,8,9] a = mylist3[1:5] print(a) # reversing a list - printing every last 1 backwards mylist4 = [1,2,3,4,5,6,7,8,9] a = mylist4[::-1] print(a) # making a copy of a list list_org = ["banana","cherry","apple"] list_cpy = list_org print(list_cpy) # appending to the copy of the list list_cpy.append("lemon") print(list_cpy) print(list_org) a = [1,2,3,4,5,6] b = [i*i for i in mylist] print(mylist) print(b)
true
25d210b9d1bee0658626d297cc058907fd0ddef2
jsdosanj/Learning-Python-1.0
/4.py
1,127
4.15625
4
print("") """ a = 1 # Global Variable def f1(): print(a) def f2(): print(a) f1() f2() """ """ a = 1 # Global Variable def f1(): a = 1000 # Local variable print(a) def f2(): print(a) f1() f2() """ """ def f3(x = 1, y = 2, z = "Test"): print("x = " + str(x)) print("y = " + str(y)) print("z = " + str(z)) # f3(10, 20, "NewTest") # f3(x = 10, y = 20, z = "NewTest") # f3(y = 222, x = 111, z = "NewTest") # f3(y = 222, x = 111) # f3(x = 111) f3() """ """ def f4(*args): Sum = 0 for arg in args: #print(arg) Sum = Sum + arg print("args has " + str(len(args)) + " arguments.") return Sum Sum = 0 Sum = f4(1); print(str(Sum) + "\n") Sum = f4(1, 2, 3); print(str(Sum) + "\n") Sum = f4(1, 2, 3, 4, 5); print(str(Sum) + "\n") """ def f5(x, y, z): print("x = " + str(x)) print("y = " + str(y)) print("z = " + str(z)) f5(100, 200, 300) print("") List1 = [100, 200, 300] f5(*List1) print("") f5(List1[0], List1[1], List1[2]) print("")
false
6f7dcdfa59dee94b404ce4147d69a36e4a5da31b
thailanelopes/exercicios_em_python
/17exercicio.py
247
4.125
4
#variáveis maior = 0 #entrada numero = int(input("Informe um número: ")) while numero != 0: if numero > maior: maior = numero numero = int(input("informe um número: ")) print("O maior número é {0}: ".format(maior))
false
8535564f1f0bccb00599c1c6a1ba199343760d7d
puraharreddy/dsp-lab
/reverse order in list.py
1,322
4.1875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 12 20:16:16 2020 @author: sony """ # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize def __init__(self): self.head = None # Function to reverse the linked list def reverse(self): prev = None current = self.head while(current is not None): next = current.next current.next = prev prev = current current = next self.head = prev # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data,) temp = temp.next # execution starts here llist = LinkedList() llist.push(300) llist.push(200) llist.push(100) print ("Given Linked List") llist.printList() llist.reverse() print ("\nReversed Linked List") llist.printList()
true
906b5e6d5cd2857e8041ca3a3b732a537eba25cb
byui-cse/cse111-course
/docs/lesson07/pass_args.py
1,087
4.34375
4
""" Demonstrate that numbers are passed to a function by value and lists are passed to a function by reference. """ def main(): print("main()") x = 5 lx = [7, -2] print(f" Before calling modify_args(): x {x} lx {lx}") # Pass one integer and one list # to the modify_args function. modify_args(x, lx) print(f" After calling modify_args(): x {x} lx {lx}") def modify_args(n, alist): """Demonstrate that the computer passes a value for integers and passes a reference for lists. Parameters n: A number alist: A list Return: nothing """ print(" modify_args(n, alist)") print(f" Before changing n and alist: n {n} alist {alist}") # Change the values of both parameters. n += 1 alist.append(4) print(f" After changing n and alist: n {n} alist {alist}") # If this file was executed like this: # > python teach_solution.py # then call the main function. However, if this file # was simply imported, then skip the call to main. if __name__ == "__main__": main()
true
3611a9d87ccee04cb95eb25d27b623019b6431ed
byui-cse/cse111-course
/docs/lesson10/example2.py
1,745
4.25
4
# Copyright 2020, Brigham Young University-Idaho. All rights reserved. """ This program reads assignment scores from a text file and computes and prints the average of the test scores. """ import statistics def main(): try: # Get a file name from the user. filename = input("Enter the name of the scores text file: ") # Create an empty list that will store all the scores. scores = [] linenum = 0 with open(filename, "rt") as scores_file: # For each line of text in the file: # Convert the text to a floating point number. # Add the floating point number to the list of scores. for text in scores_file: linenum += 1 score = float(text) scores.append(score) # Call the statistics.mean function # to compute the average score. avg = statistics.mean(scores) # Print the average score rounded to # one digit after the decimal point. print(f"{avg:.1f}") except FileNotFoundError as file_not_found_err: print(f"Error: {filename} does not exist.") except PermissionError as perm_err: print(f"Error: you don't have permission to read {filename}.") except ValueError as val_err: print(f"Error: invalid score in {filename} at line {linenum}.") except ZeroDivisionError as zero_div_err: print(f"Error: {filename} is empty.") except Exception as excep: print(type(excep).__name__, excep, sep=": ") # If this file was executed like this: # > python example.py # then call the main function. However, if this file # was simply imported, then skip the call to main. if __name__ == "__main__": main()
true
ffeecb9523c4fefc59d42723220b0b01ce296d7c
dianafisher/CodeJam
/2015/house_of_pancakes/pancakes.py
2,521
4.125
4
""" At the Infinite House of Pancakes, there are only finitely many pancakes, but there are infinitely many diners who would be willing to eat them! When the restaurant opens for breakfast, among the infinitely many diners, exactly D have non-empty plates; the ith of these has Pi pancakes on his or her plate. Everyone else has an empty plate. Normally, every minute, every diner with a non-empty plate will eat one pancake from his or her plate. However, some minutes may be special. In a special minute, the head server asks for the diners' attention, chooses a diner with a non-empty plate, and carefully lifts some number of pancakes off of that diner's plate and moves those pancakes onto one other diner's (empty or non-empty) plate. No diners eat during a special minute, because it would be rude. You are the head server on duty this morning, and it is your job to decide which minutes, if any, will be special, and which pancakes will move where. That is, every minute, you can decide to either do nothing and let the diners eat, or declare a special minute and interrupt the diners to make a single movement of one or more pancakes, as described above. Breakfast ends when there are no more pancakes left to eat. How quickly can you make that happen? The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line with D, the number of diners with non-empty plates, followed by another line with D space-separated integers representing the numbers of pancakes on those diners' plates. """ input_file_name = 'B-large-practice.in' output_file_name = 'B-large-practice.out' f = open(input_file_name, 'r') outFile = open(output_file_name, 'w') # get T, the number of test cases T = f.readline() T = int(T) for t in range(T): D = f.readline() # D is the number of diners with non-empty plates D = int(D) line = f.readline() plates = line.split() print ('plates', plates) # print (D, line) counts = [0] * 1005 for p in plates: num = int(p) value = counts[num] counts[num] = value+1 # the smallest number of minutes needed to finish breakfast (when pancake count = 0) minutes = 10000 for x in range(1, len(counts)): moves = 0 for i in range(len(counts)): moves += ((i-1)//x) * counts[i] if (moves + x < minutes): minutes = (moves + x) output = 'Case #{}: {}'.format(t+1, minutes) print (output) outFile.write(output + "\n")
true
18d2e0c649fee8a4eb8843f833f2b5cd93dfbc55
HarDhillon/Python-4-Everybody
/If.py
311
4.28125
4
number = input('What is your number') output = float(number) if output > 5 : print ('number is greater than 5') print ('another line of nonsense') print ('a third line of nonsense') if output < 5 : print ('number is less than 5') if output == 5 : print ('Your number IS infact 5')
true
d7f5bac4adf61ad1b97fc3f42fd31e06a861235e
gengletao/learn-python
/1.download/ex3.py
956
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: letao geng <gengletao@gmail.com> # Copyright (C) alipay.com 2011 ''' operation exercise ''' import os import sys def main(): ''' main function ''' #start count chicken print "I will now count my chickens:" #count hen print "Hens", 25 + 30.0 / 6 #count rooster print "Roosters", 100 - 25.0 * 3 % 4 #start count egg print "Now I will count the eggs:" #count(egg) print 3 + 2 + 1 - 5 + 4 % 2 -1.0 / 4 + 6 #compare two numbers print "Is it true that 3.0 + 2 < 5 - 7?" print 3.0 + 2 < 5 - 7 print "What is 3.0 + 2?", 3.0 + 2 print "What is 5.0 - 7?", 5.0 - 7 print "Oh, that's why it's False." #some other exercise print "How about some more." print "Is it greater?", 5.0 > -2 print "Is it greater or equal?", 5.0 >= -2 print "Is it less or equal?", 5.0 <= -2 print 'Done' if __name__ == '__main__': main()
true
a6d10f8c0768f60a29e95b5d017d026e73801f43
diegun99/proyectos
/tuplas.py
1,022
4.34375
4
mi_lista = [1, 2, 3, 4, 5] mi_lista.append(6) mi_lista.insert(0, 10) mi_lista[0] = 0 print(mi_lista) mi_tupla = (1, 2, 3, 4, 5) mi_tupla2 = mi_tupla #mi_tupla.append(6) La tupla no tiene append #mi_tupla.insert(0, 10) La tupla no tiene insert #mi_tupla[0] = 0 mi_tupla = (10, 20, 30) print(mi_tupla) print(mi_tupla2) #No púedo modificar la tupla, pero si puedo acceder a su contenido print("El último elemento de la tupla es", mi_tupla[-1]) #Puedo guardar listas dentro de una tupla mi_tupla3 = ([1, 3, 2], [5, 6, 7, 8], [10, 12, 9, 11]) print(mi_tupla3) print("Puedo acceder a los elementos de las listas dentro de una tupla") print("Lista 2, elemento 1:", mi_tupla3[2][1]) #Dado que las listas son modificables, se pueden modificar los valores de las listas que estén dentro de tuplas mi_tupla3[0].append(4) mi_tupla3[2].insert(2, 13) print(mi_tupla3) mi_tupla3[1].clear() print(mi_tupla3) #Voy a crear una tupla con un solo elemento mi_tupla4 = (5,) print("El primer elemento de la tupla 4 es:", mi_tupla4[0])
false
e2ded8c6091a5438e36bfe9bb5d8b5b42bbe71c2
diegun99/proyectos
/ciclo_while.py
680
4.15625
4
print("este programa seguira solicitando un número hasta que ingrese un cero") numero = float(input("digite un numerito : ")) suma = 0 #acumulador contador = 0#contador while numero !=0 : suma +=numero contador += 1 print(" la suma de los números es: ", suma) promedio = suma / contador print(" el promedio es: ",promedio) if suma >100: print("pasaste de 100") break; numero = float(input("digite un numerito : ")) print(" la suma de los números es: ", suma) if contador > 0 : print(" el promedio es: ",promedio) else: print(" no puede obtener un promedio dado que no ingresaste ningun numero diferente de cero")
false
9c90cec98eb44a78181c65576e33e913b83ed243
fanwen390922198/ceph_pressure_test
/base_lib/ChartDirector/pythondemo/donutwidth.py
1,257
4.3125
4
#!/usr/bin/python from pychartdir import * def createChart(chartIndex) : # Determine the donut inner radius (as percentage of outer radius) based on input parameter donutRadius = chartIndex * 25 # The data for the pie chart data = [10, 10, 10, 10, 10] # The labels for the pie chart labels = ["Marble", "Wood", "Granite", "Plastic", "Metal"] # Create a PieChart object of size 150 x 120 pixels, with a grey (EEEEEE) background, black # border and 1 pixel 3D border effect c = PieChart(150, 120, 0xeeeeee, 0x000000, 1) # Set donut center at (75, 65) and the outer radius to 50 pixels. Inner radius is computed # according donutWidth c.setDonutSize(75, 60, 50, int(50 * donutRadius / 100)) # Add a title to show the donut width c.addTitle("Inner Radius = %s %%" % (donutRadius), "arial.ttf", 10).setBackground(0xcccccc, 0) # Draw the pie in 3D c.set3D(12) # Set the pie data and the pie labels c.setData(data, labels) # Disable the sector labels by setting the color to Transparent c.setLabelStyle("", 8, Transparent) # Output the chart c.makeChart("donutwidth%s.png" % chartIndex) createChart(0) createChart(1) createChart(2) createChart(3) createChart(4)
true
691cdd5d8bb6d670c599ee79cf37c39c3a97a715
PrashantWalunj999/Infosys-Foundation-Program-5.0--Python-
/Module_1/assg_9/assg_9.py
908
4.15625
4
#Execute the following commands and observe the usage of different types of commenting styles. i = 10 # creates an integer variable. This is a single line comment. print("i =", i) # prints 10 ''' Below code creates a Boolean variable in Python(This is a multiple line comment) ''' s = True print("s =", s) #prints True, Here, s is a Boolean variable with value True """ Below code assigns string data to variable 's'. Data type of variable can change during execution, Hence, Python supports Dynamic Semantics.(This is multi-line comment used for documentation) """ s = 24 print("s =", s) #prints 24, Here, s is changed to integer data type with value 24 """ OUTPUT:: PrashantWalunj@PrashantWalunj:/mnt/e/Prashant/infosys/fp5.0_prashantwalunj/module_1/assg_9$ python3 assg_9.py i = 10 s = True s = 24 PrashantWalunj@PrashantWalunj:/mnt/e/Prashant/infosys/fp5.0_prashantwalunj/module_1/assg_9$ """
true
664a0be83960e1ffa64f00a2995ca1e8b178ac76
PrashantWalunj999/Infosys-Foundation-Program-5.0--Python-
/Module_1/assg_11/2.py
351
4.125
4
print("Marks of Student in ABC institute\n") print('Enter the marks of john in three subjects\n') sub1 = input('Enter Marks of subject 1\n') sub2 = input('Enter the marks of subject 2\n') sub3 = input('Enter the marks of subject 3\n') total_marks = ( sub1 + sub2 + sub3 ) print(total_marks) avg_marks = total_marks/3 print('Avg marks are',avg_marks)
false
87a7a4549e907af6fd70b4ed3ca15de757a8611d
RichardTabaka/Value-Checker
/Value_Checker.py
2,713
4.53125
5
#This program will be used to calculate the value, in dollars per hour, of every subscription you have. #It will prompt you for the name of each subscription you have, then the cost for LAST MONTH, then the time #you spent using it LAST MONTH. # #In the future I'd like to add values of non-subscription content like a hard copy of a movie that would take the cost, #length and how many times you have watched it to allow a comparison in usage of bought VS borrowed media #------------------------------------------------------------------------------------------------------------------------ #The following explains the program in the console print("Welcome to the Subscription Value Calculator!") print("") print("First, the program will prompt you to input a name, cost and your total hours using a subscription.") print("Then it will move on to a second, third etc. When you are done entering subscriptions simply") print(" enter 'No' when prompted for another to see the values.") print() subNames = [] subCosts = [] subTime = [] subValue = [] subCounter = [] j = 1 #This part takes your first subscriptions information subNames.append(input("What is the name of your first subscription? ")) subCosts.append(float(input("What is the cost of your first subscription? "))) subTime.append(float(input("How much time did you spend using your first subscription? "))) subCounter.append(0) subValue.append(float(subTime[0] / subCosts[0])) print("") cont = input("Would you like to enter another subscription?('Yes' or 'No') ") print("") #The following allows the user to input as many subscriptions as they would like to check #simply responding with 'No' exits the while loop while cont != "No": subNames.append(input("What is the Name of your next subscription? ")) subCosts.append(float(input("What is the cost of this subscription? "))) subTime.append(float(input("How much time did you spend using this subscription? "))) subCounter.append(j) subValue.append(float(subTime[j] / subCosts[j])) print("") cont = input("Would you like to enter another subscription?('Yes' or 'No') ") j += 1 print("") #This prints the name and value of every subscription entered print("Your Subscriptions:") print("") print(" Name Value(Hours/Dollar Spent)") print(" ---------------------------------------------") print("") sp = " " for i in subCounter: z = str(round(subValue[i], 3)) print(" " + subNames[i] + sp[len(subNames[i]):(len(sp)-5)] + z) print("") input() #Hopefully this helped you re-evaluate your spending habits and cut subscriptions you don't use!
true