blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6ecd8195277e4bc8e338cfe4a09012c94797c9dc
jayrore/warmup-exercises
/python/palindromeCheck.py
263
4.25
4
def palindromeCheck(string): """ Returns Bool if a string is a palindrome by checking the reverse string with the original """ reversedString = "" for i in reversed(range(len(string))): reversedString += string[i] return reversedString == string
true
4767f05b0d0eabf6b5102e297c1f9d63d9731cc2
ypeels/python-tutorial
/5.5-dictionaries.py
1,698
4.15625
4
print ''' Dictionaries are like hashes in Ruby. Keys can be any immutable type: strings, numbers, and tuples without any mutable elements. Evidence that dictionaries are more primitive than sets: - {} creates an empty dictionary, NOT an empty set - dict: del d[key] vs. set: s.remove(elem) [well, sets ain't iterable] ''' print "dict() constructor can operate on any iterable of iterable pairs? (list and tuple both seem to work)" print "dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) =", \ dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) # {'sape': 4139, 'jack': 4098, 'guido': 4127} print "dict((('sape', 4139), ('guido', 4127), ('jack', 4098))) =", \ dict((('sape', 4139), ('guido', 4127), ('jack', 4098))) # {'sape': 4139, 'jack': 4098, 'guido': 4127} print "dict((('sape', 4139), ['guido', 4127], ('jack', 4098))) =", \ dict((('sape', 4139), ['guido', 4127], ('jack', 4098))) # {'sape': 4139, 'jack': 4098, 'guido': 4127} print "dict([('sape', 4139), ['guido', 4127], ('jack', 4098)]) =", \ dict([('sape', 4139), ['guido', 4127], ('jack', 4098)]) # {'sape': 4139, 'jack': 4098, 'guido': 4127} print "etc." print ''' Keyword arguments also automagically work, for keys that are simple strings: >>> dict(sape=4139, guido=4127, jack=4098)''' print dict(sape=4139, guido=4127, jack=4098) # {'sape': 4139, 'jack': 4098, 'guido': 4127} print ''' Finally, DICT COMPREHENSIONS are created just like you would expect, using { key: value for... if... } >>> {x: x**2 for x in (2, 4, 6)}''' print {x: x**2 for x in (2, 4, 6)} # {2: 4, 4: 16, 6: 36}
true
e9db4753d94eeae697d05c6e3987300581f43095
ypeels/python-tutorial
/5.1.3-filter-map-reduce.py
829
4.125
4
# 5.1.3 Functional Programming Tools def f(x): return x % 2 != 0 and x % 3 != 0 # lookee, an "inline" function #def g(x, y): return x + y > 10 print "filter:" print filter(f, range(2, 25)) # [5, 7, 11, 13, 17, 19, 23] #print "filter (2 sequences):", filter(f, range(1,8), range(1, 8)) print "" def cube(x): return x**3 # FORTRAN-STYLE EXPONENTIATION WORKS def add(x, y): return x+y print "map:" print map(cube, range(1, 11)) # [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] print map(add, range(1, 11), range(1, 11)) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] - multiple arguments for map() only, NOT filter() or reduce() print "" print "reduce:" print reduce(add, range(1, 11)) # 55 print reduce(add, range(1, 11), 10) # optional third argument = accumulator initial value
true
32ca834444b9cd88d259f17f2384ba59ae934bf6
sourav4455/Python
/find_superDigit_using_recursion.py
2,611
4.3125
4
## # We define super digit of an integer x using the following rules: # # Given an integer, we need to find the super digit of the integer. # # If x has only 1 digit, then its super digit is x. # Otherwise, the super digit of x is equal to the super digit of the sum of the digits of x. # # For example, the super digit of will be calculated as: # # super_digit(9875) 9+8+7+5 = 29 # super_digit(29) 2 + 9 = 11 # super_digit(11) 1 + 1 = 2 # super_digit(2) = 2 # # You are given two numbers n and k. The number p is created by concatenating the string n k times. Continuing the above example where n = 9875, assume your value k = 4. Your initial p = 9875 9875 9875 9875 (spaces added for clarity). # # superDigit(p) = superDigit(9875987598759875) # 5+7+8+9+5+7+8+9+5+7+8+9+5+7+8+9 = 116 # superDigit(p) = superDigit(116) # 1+1+6 = 8 # superDigit(p) = superDigit(8) # # All of the digits of p sum to 116. The digits of 116 sum to 8. 8 is only one digit, so it's the super digit. # # Function Description # Complete the function superDigit in the editor below. It must return the calculated super digit as an integer. # # superDigit has the following parameter(s): # n: a string representation of an integer # k: an integer, the times to concatenate n to make p # # Sample Input 0 # 148 3 # # Sample Output 0 # 3 # # Explanation 0 # Here n = 148 and k = 3, so P = 148148148. # # super_digit(P) = super_digit(148148148) # = super_digit(1+4+8+1+4+8+1+4+8) # = super_digit(39) # = super_digit(3+9) # = super_digit(12) # = super_digit(1+2) # = super_digit(3) # = 3. # # Sample Input 1 # 9875 4 # # Sample Output 1 # 8 # # Sample Input 2 # 123 3 # # Sample Output 2 # 9 # # Explanation 2 # super_digit(P) = super_digit(123123123) # = super_digit(1+2+3+1+2+3+1+2+3) # = super_digit(18) # = super_digit(1+8) # = super_digit(9) # = 9 # ######################################################################### #!/bin/python import math import os import random import re import sys # Complete the superDigit function below. def superDigit(n, k): sum_p = sum(map(int,str(n))) * k if len(str(sum_p)) == 1: return sum_p else : return superDigit(sum_p, 1) if __name__ == '__main__': fptr = open('/tmp/out.txt', 'w') nk = raw_input().split() n = nk[0] k = int(nk[1]) result = superDigit(n, k) fptr.write(str(result) + '\n') fptr.close()
true
dbe25893825971abb6c4a87dac829069cd3d0821
sourav4455/Python
/Data_Structures_and_Algorithm/6_Searching_Sorting/Bubble_Sort.py
492
4.46875
4
## The Bubble sort makes multiple passes through a list. It compares adjacent items and exchanges ## those that are out of order. Each item "bubbles" up to the location where it belongs. def bubble_sort(arr): for n in range(len(arr)-1,0,-1): #print 'This is the n: ',n for k in range(n): #print 'This is the k index check: ',k if arr[k] > arr[k+1]: temp = arr[k] arr[k] = arr[k+1] arr[k+1] = temp
true
23f4de39a96f2dc0a2c9f0b27a4e4410f7396657
PrateekCoder/Python_RECAP
/01_Introduction/05_Division.py
529
4.25
4
''' Task Read two integers and print two lines. The first line should contain integer division, // . The second line should contain float division, / . You don't need to perform any rounding or formatting operations. Input Format The first line contains the first integer, . The second line contains the second integer, . Output Format Print the two lines as described above. Sample Input 4 3 sample Output 1 1.3333333333333333 ''' first = float(input()) second = float(input()) print(first//second) print(first/second)
true
fba93e962e4567958ea60b46bcc000087e56c346
CSpencer11/cs114
/TheGuessingGame.py
993
4.15625
4
"""The Guessing Game""" from time import sleep import random print ('!!!!!!!!!!Welcome to the Guessing Game!!!!!!!!!!') sleep (2) print ('You will get 5 chances to guess what number Im thinking about!') sleep (3) print ('Hope you dont!') sleep (1) print ('WAIT FOR IT!!!!!!') sleep (2) print ('Waittt.....') sleep (2) print ('██████▌▄▌▄▐▐▌███▌▀▀██▀▀') print ('████▄█▌▄▌▄▐▐▌▀███▄▄█▌') print ('▄▄▄▄▄██████████████▀') sleep (2) print ('LOL!Good Luck! ^.^') sleep (4) print ('Pick a number between 1-99, type it, and push Enter.') n = random.randint(1, 99) guess = int(raw_input("Enter an integer from 1 to 99:")) while 5 != "guess": print ('Guess is low') guess = int(raw_input("Enter an integer from 1 to 99:")) elif guess > "34": print ('Guess is high') guess = int(raw_input("Enter an integer from 1 to 99:")) else: print ('You guessed it!')
true
bfb81e1cec844e5f5136480a60b1b0580a3e29db
mdAshrafuddin/python
/p_code/simpleCalculator.py
1,300
4.5
4
# Programming make a sample calculator # This function add two numbers def add(num1, num2): return num1 + num2 # Function to substract two number def sub(num1, num2): return num1 - num2 # This functions multipication two number def mul(num1, num2): return num1 * num2 # This functions divide two number def div(num1, num2): return num1 / num2 # This functions exponentiation def raisePower(num1, num2): return num1 ** num2 print("Operation to perform:"); print("1. Addition"); print("2. Subtraction"); print("3. Multiplication"); print("4. Division"); print("5. Raising a power to number"); # This 3 variable assign choice = int(input("Enter number: ")) num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) # This addition function if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) # This subtraction function elif choice == '2': print(num2, '-', num2, '=', sub(num2, num2)) # This multipication function elif choice == '3': print(num1, '*', num2, mul(num1, num2)) # This division function elif choice == '4': print(num1, '/', num2, div(num1, num2)) # This Exponentiation function elif choice == '5': print(num1, '**', num2, raisePower(num1, num2)) else: print("Please select a valid input")
true
f01725baf2fe96779a32388076a50e73e01eb5d2
ankatrostnikova/pythonicessays
/loops.py
1,255
4.25
4
#!/usr/bin/python # Name: Anna Trostnikova # Section: 1 # Date:23/07/2013 # loops.py # Transfer fractions like 1/n in range 1/2-1/10 to decimals. Print the result. for n in range(2,11): k = 1.0/n print k #Prints a countdown from the given number to 0. print "Countdown" num = raw_input("Enter a non negative number:") num = int(num) while num < 0: print "This is not a valid input. Please try again" num = input("Enter a non negative number") while num > 0: print num - 1 num = num-1 # Calculate the exponent, using base and exponent value. base = raw_input("Enter the exponent base, please: ") base = int(base) exp = raw_input("Enter the exponent, please: ") exp = int(exp) if exp<0: print "This is not a valid input" else: c= 1 for x in range(0,exp): c = c*base print c #Asks user to enter an even number, if an odd number is entered prints a witty message and makes user enter another number. Runs till the even number is entered# num = raw_input("Enter a number, divisable by two ") num = int(num) while num%2!= 0: print "Learn your math! This is not a number, divisable by two." num = raw_input("Enter another number ") num = int(num) print "You are clever. This is an even number. Congratulations"
true
3f41abff893209ca2f0045efed9901d74bd80c21
Chencheng78/python-learning
/checkio/fizz_buzz.py
442
4.21875
4
''' "Fizz Buzz" if the number is divisible by 3 and by 5; "Fizz" if the number is divisible by 3; "Buzz" if the number is divisible by 5; return the number if neither. ''' def checkio(num): if (num % 3 == 0 and num % 5 == 0): return('Fizz Buzz') elif num % 3 ==0: return('Fizz') elif num % 5 ==0: return('Buzz') else: return(str(num)) print(checkio(15)) print(checkio(6)) print(checkio(5)) print(checkio(7)) print(checkio(20))
true
ef2fa434e980840cba3723a0e0ca484077f16c7e
ziolkowskid06/grokking_algorithms
/dijkstras_algorithm.py
1,741
4.21875
4
""" Calculate the shortest path for weighted graph. """ # Hash table to represent all nodes and weights graph = {} graph["start"] = {} graph["start"]["a"] = 6 graph["start"]["b"] = 2 graph["a"] = {} graph["a"]["finish"] = 1 graph["b"] = {} graph["b"]["a"] = 3 graph["b"]["finish"] = 5 graph["finish"] = {} # Hash table to store costs for each node infinity = float("inf") costs = {} costs["a"] = 6 costs["b"] = 2 costs["finish"] = infinity # Hash table for the parents parents = {} parents["a"] = "start" parents["b"] = "start" parents["finish"] = None # Keep track of all nodes, which has been already processed. processed = [] # Find the lowest-cost node, that haven't been processed def find_lowest_cost_node(costs): lowest_cost = float("inf") lowest_cost_node = None # Go through each node. for node in costs: cost = costs[node] if cost < lowest_cost and node not in processed: lowest_cost = cost lowest_cost_node = node return lowest_cost_node node = find_lowest_cost_node(costs) # Check all nodes while node is not None: cost = costs[node] neighbors = graph[node] # Go through all the neighbors of this node for n in neighbors.keys(): new_cost = cost + neighbors[n] # If it is cheaper to get this neighbor if costs[n] > new_cost: costs[n] = new_cost # Update the cost for this node parents[n] = node # This node become parent for this neighbor # Mark node as processed processed.append(node) # Find the next node to process, and loop node = find_lowest_cost_node(costs) # Show the cheapest path print(costs)
true
b9ce20c050a97a178349efec3cf59ef358c8fd03
nico1988/Python_lxf
/advanced_featrue/iteration.py
506
4.15625
4
# -*- coding:utf-8 -*- # iteration 迭代 # python 的 迭代通过 for in 完成 # for in 可以迭代 list tuple dict # 判断是否可以迭代 L = list(range(100)) from collections import Iterable print(isinstance('a',Iterable)) print(isinstance([1,2,3],Iterable)) print(isinstance((1,2),Iterable)) print(isinstance(123,Iterable)) # 整数不能迭代 print(L) for i,v in enumerate(L): print(i,v) # 循环两个变量 for x,y in [(1,1),(2,3),(3,9)]: print(x,y) # 寻找最小值和最大值
false
25aab596bcce5895735fe03e6864fce6d4c3a067
csheare/python_tricks
/blankbale/section2/tuples.py
512
4.5625
5
# Idiom 1: Use tuples to unpack data foods = ['Banana', 'Apple', 'Coffee'] (one, two, three) = foods print('{0}, {1}, {2}'.format(one, two, three)) # Idiom 2: Use _ as a placeholder for data in a tuple that should be ignored (one, two, _) = ['Banana', 'Apple', 'Coffee'] print('{0}, {1}'.format(one, two)) # Idiom 3: Avoid using a temporary variable in Python. We can use tuples to make our intertion more clear. foo = 'Foo' bar = 'Bar' (foo, bar) = (bar, foo) assert(foo == 'Bar') assert(bar == 'Foo')
true
b22dd47bbc2bc936099411e1891885a3c93a238e
csheare/python_tricks
/blankbale/section1/for.py
535
4.1875
4
# Idiom 1: use enumerate instead of creating an index my_fruits = ['Apple', 'Pear', 'Banana'] for index, fruit in enumerate(my_fruits): print(f'{index}, {fruit}') # Idiom 2: Use the in keyword to iterate over an iterable for fruit in my_fruits: print(fruit) # Idiom 3: Use else to execute code after a for loop concludes my_friends = [('Madision', 22),('Alyssa', 26), ('Debby', 68 )] for friend in my_friends: print(friend) if friend[1] > 65: print("old gal pal") break else: print("you are a hip young lady, Courtney Shearer")
true
b8f0fb7aaad3ff82faca2af8f63229d26702d70c
janhak/python-solution-to-advent-of-code-2017
/day_12_digital_plumber.py
2,664
4.1875
4
""" --- Day 12: Digital Plumber --- Walking along the memory banks of the stream, you find a small village that is experiencing a little confusion: some programs can't communicate with each other. Programs in this village communicate using a fixed system of pipes. Messages are passed between programs using these pipes, but most programs aren't connected to each other directly. Instead, programs pass messages between each other until the message reaches the intended recipient. For some reason, though, some of these messages aren't ever reaching their intended recipient, and the programs suspect that some pipes are missing. They would like you to investigate. You walk through the village and record the ID of each program and the IDs with which it can communicate directly (your puzzle input). Each program has one or more programs with which it can communicate, and these pipes are bidirectional; if 8 says it can communicate with 11, then 11 will say it can communicate with 8. You need to figure out how many programs are in the group that contains program ID 0. For example, suppose you go door-to-door like a travelling salesman and record the following list: 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5 In this example, the following programs are in the group that contains program ID 0: - Program 0 by definition. - Program 2, directly connected to program 0. - Program 3 via program 2. - Program 4 via program 2. - Program 5 via programs 6, then 4, then 2. - Program 6 via programs 4, then 2. Therefore, a total of 6 programs are in this group; all but program 1, which has a pipe that connects it to itself. How many programs are in the group that contains program ID 0? """ # Brute force Quick Find Eager # p and q are connected if they have the same id connections = list(range(2000)) def union(p, q): pid = connections[p] for i, c in enumerate(connections): if c == pid: connections[i] = connections[q] def lines_from_file(a_file): with open(a_file, 'rt') as f: for l in f: yield l.strip() def connections_from_line(line): origin, destinations = line.split('<->') origin = int(origin) destinations = map(int, destinations.split(',')) return [(origin, d) for d in destinations] if __name__ == '__main__': lines = lines_from_file('day_12_data.txt') for l in lines: for origin, dest in connections_from_line(l): union(origin, dest) print('First program is connected to ', sum(1 for c in connections if c == connections[0])) print('There are {} groups'.format(len(set(connections))))
true
8264e1cf2659cb3eed22934202f809172115a996
hcastor/ranger
/tools/utilities.py
1,017
4.25
4
def convert_to_number(value): """ Used to blindly convert any number to correct data type '-', '' = None 1,000 = 1000 1,000.00 = 1000.00 1.2M = 1200000.00 """ if value == '' or value == '-': return None stripped_value = value.replace(',', '').strip() try: return int(stripped_value) except ValueError: pass try: return float(stripped_value) except ValueError: pass try: powers = {'b': 10 ** 9, 'm': 10 ** 6, 't': 10 ** 12} return float(stripped_value[:-1]) * powers[stripped_value[-1].lower()] except (KeyError, ValueError): pass return value def clean_key(value): """ Used to provide consistent key formats in mongo """ replacements = [ ('.', ''), ('$', ''), (' ', '_'), (':', ''), ('(', ''), (')', '') ] value = value.lower().strip() for replacee, replacer in replacements: value = value.replace(replacee, replacer) return value
true
4a7d86ed4f4e0f783224b223793989c9524e2f67
Renittka/Web_2020
/week8/problems/hackerrank/1.py
439
4.34375
4
# Given an integer, , perform the following conditional actions: # If is odd, print Weird # If is even and in the inclusive range of 2 to 5, print Not Weird # If is even and in the inclusive range of to , print Weird # If is even and greater than , print Not Weird a = int(input()) if a % 2 != 0: print("Weird") elif a in range(2,6): print('Not Weird') elif a in range(6, 21): print('Weird') else: print('Not Weird')
true
180a02a0cd0b98857808bb1269622e6219f5e2ee
Renittka/Web_2020
/week8/problems/informatics/functions/B.py
303
4.15625
4
# Напишите функцию double power (double a, int n), вычисляющую значение a^n. def power(a, n): s = 1 for i in range(n): s *= a return s a = input().split() # for i in range(len(a)): # a[i] = int(a[i]) print(int(power(float(a[0]), int(a[1]))))
false
674cbde1c1ca86f4c9e80153b5534beeb7c1d4f7
Renittka/Web_2020
/week8/problems/hackerrank/9.py
771
4.21875
4
# You have a record of students. Each record contains the student's name, and their percent marks in Maths, # Physics and Chemistry. The marks can be floating values. The user enters some integer followed by the names # and marks for students. You are required to save the record in a dictionary data type. # The user then enters a student's name. Output the average percentage marks obtained by that student, # correct to two decimal places. if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() score=student_marks[query_name] print("{0:.2f}".format(sum(score)/len(score)))
true
b4f16984368a40820e671af4730fb5930d5263d3
cqz5858/HogwartsSDET17
/Python/test_object.py
1,276
4.21875
4
class Person: # 定义类变量,可变 name = "default" age = 0 gender = "default" weight = 0 def __init__(self, name, age, gender, weight): # 定义实例变量,可变 self.name = name self.age = age self.gender = gender self.weight = weight def act(self): print(f"{self.name} act") def sing(self): print(f"{self.name} sing") # 类方法 @classmethod def think(cls): print(f"{cls.name} think") # # 类型变量和实例变量区别: # # 类变量classname.访问,实例变量要创建实例后才能访问,编写框架时使用,类不需要实例化的情况下使用 # # 类变量和实例变量的值可变 # print(Person.name) # Person.name = '陈大' # print(Person.name) # zs = Person('张三', 33, '男', 133) # print(zs.name) # zs.name = '张山' # print(zs.name) # 类方法和实例方法区别: # 类不能直接访问实例方法,需要加装饰器@classmethod Person.think() # zs = Person('张三', 33, '男', 133) # zs.think() # 类的实例化,创建一个实例 # zs = Person('张三', 33, '男', 133) # print(zs.name, zs.age, zs.gender, zs.weight) # print(f"名字:{zs.name}\n年龄:{zs.age}\n性别:{zs.gender}\n体重:{zs.weight}\n")
false
af7024d7c65dc74c2a4f746cc284986433ec6cca
walajadi/coding_tricks
/inheritance.py
563
4.125
4
class A(object): def __init__(self): print('A constructor') class B(A): def __init__(self): print('B constructor') super(B, self).__init__() class C(A): def __init__(self): print('C constructor') super(C, self).__init__() class D(C, B): def __init__(self): print('D constructor') super(D, self).__init__() if __name__ == '__main__': d = D() """ What's the output ? 1. D constructor C constructor B constructor A constructor 2. D constructor B constructor C constructor A constructor 3. D constructor 4. D constructor C constructor """
false
257ed55a80e88b9e46cf42fbd3c615677ec7dce8
Anithakm/study
/while3.py
207
4.125
4
'''Print multiplication table of 24, 50 and 29 using loop.''' i=1 while(i<=10): print(24*i) i=i+1 i=1 while(i<=10): print(50*i) i=i+1 i=1 while(i<=10): print(29*i) i=i+1
false
798371809e24442f9af55d5039cb2f1334e515a3
Anithakm/study
/level1.1.py
607
4.28125
4
#Take input of length and breadth of a rectangle from user and print area of it. print("enter length") x=int(input()) print("enter breadth") y=int(input()) area=x*y print(area) #Ask user to give two float input for length and breadth of a rectangle #and print area type casted to int. print("enter length") x=float(input()) print("enter breadth") y=float(input()) area=x*y print(area) #Take side of a square from user and print area and perimeter of it. print("enter sides") side=int(input()) area=side*side perimeter=4*side print("area is",area) print("perimeter is ",perimeter)
true
fcb10c37364db95e18eb17600b8ee8c72951d70a
Anithakm/study
/dici.3.py
362
4.125
4
#A shop will give discount of 10% if the cost of #purchased quantity is more than 1000. #Ask user for quantity #Suppose, one unit will cost 100. #Judge and print total cost for user. print("enter quantity") quantity=int(input()) if (quantity*100>1000): print("cost is",((quantity*100)-(.1*quantity*100))) else: print("cost is",(quantity*100))
true
423a996c59f06abff2b2bdeb4f2066ebcd7fa53f
TeemosCode/Python
/PM2.5/pandasForPM2.5.py
2,820
4.15625
4
import pandas as pd #building dataframe df = pd.DataFrame({"teemo": [3,22,18], "trist": [22,3,6], "urgot": [13,6,14]}) # or data = [[3,22,18], [22,3,6], [13,6,14]] index = ["Teemo", "Trist", "Urgot"] columns = ["Kills", "Deaths", "Assists"] df = pd.DataFrame(data, columns = columns, index = index) #changing the attributes of the data frame #df.columns = new_col df.index = new_index index[0] = "TEETO" df.index = index columns[2] = [3,3,3] df.columns = columns #getting data of data frame COLUMNS #df["column_name"] df["Kills"] # if needed more than 1 COLUMNS of data, need to pass a list of lists --> ([ [ ] ]) df[["Kills", "Deaths"]] #it could also contain logic during the choosing process of the data frame #df[df.attribute > x] df[df.Kills >= 10] df.values # acquires ALL data, represented in a 2 dimensional list [[]] df.values[0] # here, we are getting TEETO's KDA (data) df.values[0][1] # getting TEETO's Deaths data value # the down part of using the DataFrame "values" attribute is that we needa know the EXACT INDEX of our data we want to acquire # so the better usage for acquiring data is the "loc" attribute df.loc["TEETO", : ] # df.loc[row_name, column_name] use " : " to mean "ALL" data df.loc[("TEETO", "Trist"), : ] df.loc[("TEETO", "Trist"), ("Kills", "Deaths")] #more than one certain data, use '()' to put em together df.loc["TEETO":"Urgot", "Deaths" : "Assists"] # what to (:) what df.loc[ : "Urgot", "Deaths" : ] #start to(:) what, something to(:) End #the "iloc" attribute uses (row, column) df.iloc[1, : ] df.iloc[1][1] #.iloc is the exact same usage as .loc, but it uses the exact index df.ix[] # works exactly like the same as the previous two, but a combination of both, can use index and names at the same time df.head(10) # list out the from 10 data of the data frame df.tail(5) # list our the last 5 data of the data frame #to change the data of the data frmae df.ix["TEETO"]["Deaths"] = 333 df.ix["Urgot", : ] = 10 # change all of its value to 10 #SORT DATAFRAME VALUES #var = df.sort_values(by = column_name [, ascending = Boolean]) df1 = df.sort_values(by = "Deaths", ascending = False) # sort by index, column name #var = df.sort_index(axis = row_column_value (0 or 1, 0 : sort by ROW_Title, 1 : sort by COL_Title) [, ascending = Boolean]) df2 = df.sort_index(axis = 0) #Deleting Values in Pandas #using .drop # df = df.drop(column_or_row_name [, axis = 0 or 1]) df1 = df.drop("TEETO") #deleting TEETO's KDA, all data df2 = df.drop("Deaths", axis = 1) #dropping the kills column, all of it df3 = df.drop(["Deaths", "Assists"], axis = 1) # droping more then one, use brackets to put em all in [] df4 = df.drop(df.index[1:3]) # droping a whole bunch of characters from where to where with their index df5 = df.drop(df.columns[0:2], axis = 1) #dropping column data
true
5a6ffc349052afa3026cce2d6c6a84a85c985707
kdraeder/python_tutorial
/mysci/readdata.py
1,524
4.15625
4
# def read_data(columns, types{}, filename="data/wxobs20170821.txt"): def read_data(columns, types, filename="data/wxobs20170821.txt"): # ^ keyword argument; don't have to enter it # Docstring: """ Read the data from CU Boulder weather station file Parameters: columns: a dictionary of column names mapping to column indices types: dict of col names mapping to the types to which to convert each col of data filename: a string path pointing to the CU Boulder Weather Station data file """ # initialize data variable # a dicionary, will populate later # init each list to empty data = {} for column in columns: # empty list data[column] = [] with open(filename, 'r') as datafile: # read the first 3 lines (header) # v a place holder variable (instead of i, j ...) indicates we'll never use the variable for _ in range(3): # could have said 'for i in [0,3]' # print(_) datafile.readline() # Read and parse the rest of the file # each line is a string for line in datafile: # split along white space split_line = line.split() # add datum to the list 'data' for column in columns: i = columns[column] t = types.get(column, str) value = t(split_line[i]) data[column].append(value) return data
true
311fbe68751dcd65f9902f77e0dbb4df8952fc76
simofleanta/Coding_Mini_Projects
/Python_exercises/Circle_class.py
656
4.125
4
# Create a circle class and initialize it with radius. # Make two methods get_area and get_circumference inside this class. class Circle: def __init__(self, radius,area=0,circumference=0): self.radius=radius self._circumference=circumference self._area=area def get_area(self): return self._area def set_area(self,a): self._area=a def get_circumference(self): return self._circumference def set_circumference(self,a): self._circumference=a p=Circle(20) #set stuff p.set_area(0.5) p.set_circumference(360) #get stuff print(p.get_area()) print(p.get_circumference())
true
0bc3756f6fdadd7c122a0fb604b5cc5124ebd8b7
simofleanta/Coding_Mini_Projects
/Python_exercises/dictionary_ex.py
872
4.21875
4
# Using keys and indexing, grab the 'hello' from the following dictionaries: d1 = {'simple_key': 'hello'} d2 = {'k1': {'k2': 'hello'}} d3 = {'k1': [{'nest_key': ['this is deep', ['hello']]}]} d=d1.get('simple_key') print(d) d=d2['k1']['k2'] print(d) d=d3['k1'][0]['nest_key'][1] print(d) """Below are the two lists convert it into the dictionary""" #use dict #use zip keys = ['Ten', 'Twenty', 'Thirty'] values = [10, 20, 30] d=dict(zip(keys,values)) print(d) #--------------------------------------------- """Access the value of key ‘history’""" #nested dict sampleDict = { "class":{ "student":{ "name":"Mike", "marks":{ "physics":70, "history":80 } } } } s=sampleDict['class']['student']['marks']['history'] print(s) #-------------------------------------------------------------
false
d2288353aa82828f2a475d8c8bca2a2c0d0d55e1
Tower5954/Python_revision_bmi_1_test
/main.py
330
4.15625
4
# 🚨 Don't change the code below 👇 height = input("enter your height in m: ") weight = input("enter your weight in kg: ") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 height_input = float(height) weight_input = float(weight) result = weight_input / (height_input ** 2) print(int(result))
true
4384c101fcb240b474a851308c96ecd20008396b
RafaelNogBac/Main
/Teste área.py
1,235
4.125
4
Largura_Garagem = float(input("Largura da Garagem (m): ")) Profundidade_Garagem = float(input("Profundidade da Garagem (m): ")) #calculo da área da garagem Area_Garagem = Largura_Garagem*Profundidade_Garagem Largura_Terreno = float(input("Largura do Terreno (m): ")) Profundidade_Terreno = float(input("Profundidade do Terreno (m): ")) #calculo da área do terreno Area_Terreno = Largura_Terreno*Profundidade_Terreno #calculo do percentual de ocupação Percentual = ((Area_Garagem)/(Area_Terreno))* 100 #entrada da zona de localização do terreno Zona = input("Coloque a localização do terreno aqui: Sul=S, Norte=N, Leste=L, Oeste=O : ") #relatorios e mensagens print("Imóvel localizado na zona: ", Zona) print("Percentual de ocupação: ", Percentual) #tomada de decisões if Zona == "N" and Percentual <=25: print("Projeto atende a norma de zoneamento do plano diretor") elif Zona == "L" or Zona == "O" and Percentual <=30: print("Projeto atende a norma de zoneamento do plano direto") elif Zona == "S"and Percentual <=40: print("Projeto atende a norma de zoneamento do plano direto") else: print("REVISE AS MEDIDAS! Elas não atendem as normas de zoneamento")
false
de15e85892e3251d9494eb90971b8f681234e474
ziednamouchi/Python_programming
/basics/in_out.py
726
4.34375
4
#basic python commands #Input/output int_one = int(raw_input("give me a number: ")) print int_one str_one = raw_input("give me a string: ") print str_one type str_one # type string #print formatting str1 = "this" str2 = "string" print str1 + str2 # >>this string #str1 = "our number is : " #str2 = 5 #print str1 + str2 #this will cause error because we can not concatenate a string object with an integer object #Print Formatting: print "%format" % corresponding_data str1 = "our number is : %d" str2 = 5 print str1 %(str2) # >> our number is : 5 str1 = int(raw_input("number : ")) str2 = int(raw_input("number : ")) str3 = int(raw_input("number : ")) print "You entered %d\t%d\t%d" %(str1,str2,str3) # >> You entered ...
true
7f1ac32ab4a6adaf6dc9bb487f21bdfcebe55bd9
ziednamouchi/Python_programming
/class/overloadedOperatorPlus.py
1,437
4.21875
4
#The Dog Class with Overloaded Addition class Dog: #constructor def __init__(self, name, month, day, year, speakText): self.name = name self.month = month self.day = day self.year = year self.speakText = speakText #speakText accessor def speak(self): return self.speakText #Name accessor def getName(self): return self.name #birthdate accessor def birthDate(self): return str(self.month) + "/" + str(self.day) + "/" + str(self.year) #speakText mutator def changeBark(self,bark): self.speakText = bark # When creating the new puppy we don’t know it’s birthday. Pick the first dog’s birthday plus one year. #The speakText will be the concatenation of both dog’s text. The dog on the left side of the + operator is the object referenced by the "self" parameter. #The "otherDog" parameter is the dog on the right side of the + operator. def __add__(self,otherDog): return Dog("Puppy of " + self.name + " and " + otherDog.name, \ self.month, self.day,self.year + 1,\ self.speakText + otherDog.speakText) def main(): boyDog = Dog("Mesa", 5, 15, 2004, "WOOOOF") girlDog = Dog("Sequoia", 5, 6, 2004, "barkbark") print(boyDog.speak()) print(girlDog.speak()) print(boyDog.birthDate()) print(girlDog.birthDate()) boyDog.changeBark("woofywoofy") print(boyDog.speak()) puppy = boyDog + girlDog print(puppy.speak()) print(puppy.getName()) print(puppy.birthDate()) if __name__ == "__main__": main()
true
34acd4750ade90b4c77f21d71f6739458c39fef3
xaviinform95a/stuff2
/Exercici18.py
571
4.28125
4
"""Programa que escriu una nota alfabetica i et diu la nota que has tret""" NOTA = int(input("Escriu la nota alfabetica:")) if NOTA == "Molt Deficient": print("La nota que has tret es un 1.5") if NOTA == "Insuficient": print("La nota que has tret es un 4.0") if NOTA == "Suficient": print("La nota que has tret es un 5.5") if NOTA == "Bé": print("La nota que has tret es un 6.5") if NOTA == "Notable": print("La nota que has tret es un 8.0") if NOTA == "Excel·lent": print("La nota que has tret es un 9.5")
false
72d1d1da7bdf09f87de974a3f2f34c557ec7cc70
LittleFee/python-learning-note
/day03/9-practice-2.py
1,017
4.28125
4
# 对于下面列出的各种测试, # 至少编写一个结果为True 和False 的测试。 #  检查两个字符串相等和不等。 #  使用函数lower()的测试。 #  检查两个数字相等、不等、大于、小于、大于等于和小于等于。 #  使用关键字and 和or 的测试。 #  测试特定的值是否包含在列表中。 #  测试特定的值是否未包含在列表中。 baby='FYX' if baby=='FYX' : print('True') if baby=='QW' : print('True') else: print('False') if baby.lower()=='fyx': print('True') baby='QW' if baby.lower()!='qw': print('True') else: print('False') num_1=23 if num_1==23: print('=23') if num_1 > 0: print('>0') if num_1 < 24 : print('<24') if num_1<=23 : print('<=23') if num_1>=23: print('>=23') if (num_1>1) and (num_1<24): print('1<num_1<24') if (num_1>0) or (num_1<23): print('true') lists=['baby','fyx','qw'] if 'fyx' in lists : print('in') if 'pop' not in lists: print('not in')
false
8348c9c7d0347b1c034511c9a2bca354c836a9ba
LittleFee/python-learning-note
/day02/3-practice-for.py
1,332
4.53125
5
# 比萨:想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for # 循环将每种比萨的名称都打印出来。 #  修改这个for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对 # 于每种比萨,都显示一行输出,如“I like pepperoni pizza”。 #  在程序末尾添加一行代码,它不在for 循环中,指出你有多喜欢比萨。输出应包 # 含针对每种比萨的消息,还有一个总结性句子,如“I really love pizza!”。 pizzas=['beef','apple','orange','onion'] for pizza in pizzas : print('I like '+pizza+' pizza') print('I really like pizza') # 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中, # 再使用for 循环将每种动物的名称都打印出来。 #  修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great # pet”。 #  在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these # animals would make a great pet!”这样的句子。 animals = ['dog','cat','monkey','penguin'] for animal in animals : print(animal) print('I really like a '+animal+' to be my pet !\n') print('I wolud like any of these anymals to be my pet !')
false
8defce901d9b5e8dbbc40738c74b3725e2a99f0a
LittleFee/python-learning-note
/day01/list-sort.py
1,467
4.5625
5
# Python方法sort() 让你能够较为轻松地对列表进行排序 # 值得注意的是sort对列表的排序是永久性的 car=['toyota','honda','bmw','ducati'] print(car) car.sort() print(car) print('===========================') # 如果给sort一个reverse=True的参数,则按照字母顺序倒序排列 car.sort(reverse=True) print(car) print('===========================') # 要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数sorted() 。 # 函数sorted() 让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。 car=['toyota','honda','bmw','ducati'] print("This is new list order:\n") print(sorted(car)) print("this is origin list:\n") print(car) # 如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted() 传递参数reverse=True print("this is reverse list:\n") print(sorted(car,reverse=True)) print(car) print('===========================') # 要反转列表元素的排列顺序,可使用方法reverse() 。 # 注意,reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序 print('Origin:\n') print(car) print('After reverse()\n') car.reverse() print(car) # 方法reverse() 永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse() 即可。 print('==========================')
false
9482d808c253b030d105413ca292b3312454301f
peskin55/PythonProgramming1
/assignment3.2.py
2,902
4.3125
4
#!/usr/bin/env python file_name = input("Please enter a file name: ") # Number of lines, excluding the header is counted below line_count = len(open(file_name).readlines()) - 1 data_load = open(file_name,"r") # Text file is open for reading and is ready to have its data imported data = [] imported_terms = [] converted_data = [] # Don't need to import the header line skip_header = data_load.readline() for i in range(line_count): # Importing each line of the text file as a list # Stripping any regex from the data line = data_load.readline()[:-1] data.append(line.split("\t",1)) imported_terms.append(line.split("\t",1)[0]) add_more = input("There are 10 terms in this vocabulary list.\nWould you like to add more terms (Y/N)? ") while add_more in ["Yes","Y","yes","y"]: amount = input("How many would you like to add? ") try: # Only allowing positive integers as a valid input, question repeats until # a valid input is received int_amount = int(amount) if int_amount <= 0: print("Error. Please enter a positive number.") continue else: for i in range(int_amount): # User will have the ability to edit data from imported file term = input("Term #" + str(i + 1) + ": ") if term in imported_terms: update = input("Warning! This term is already in the vocabulary list. Update definition (Y/N)? ") if update in ["Yes","Y","yes","y"]: term_index = imported_terms.index(term) data.pop(term_index) dest = input("Destination #" + str(i + 1) + ": ") data.insert(term_index, [term, dest]) continue else: continue else: dest = input("Destination #" + str(i + 1) + ": ") data.append([term, dest]) imported_terms.append(term) continue except ValueError: # If a non integer is inputted, the progran will not exit # It will print an error message and request a valid input print("Error. Please enter an integer.") continue # User will have the option to end loop below add_more = input("Would you like to add more terms (Y/N)? ") print("There are " + str(len(data)) + " terms in the new vocabulary list.\n") for j in range(len(data)): # Data is joined and printed in a reader friendly format converted_data.append(data[j][0] + " - " + data[j][1] + "\n") print(converted_data[j][:-1]) save_file = input("\nWhat would you like to save the file as? ") data_export = open(save_file,"w") data_export.writelines("term - definition\n") for k in range(len(converted_data)): # Consolidated data is written to file of user's choice data_export.writelines(converted_data[k])
true
110e7a5a1f7ca31ce15105964264b00a7215c080
Jayprakash-SE/Engineering
/Semester4/PythonProgramming/Prutor/Week5/Q2.py
730
4.25
4
""" Write a simple python function to generate a series of floating-point numbers by declaring and updating the global values of the variable and use it to produce the desired range of floating-point numbers by taking input from the user. # The required output is as: Please input the starting for your series Please input the d for your series The series produced by this method is 0.25, 1.0, 1.75, 2.5, 3.25, 4.0, 4.75, 5.5, 6.25, 7.0, """ C=0 def generateNext(d,num): global C return C C=float(input("Please input the starting for your series\n")) s=float(input("Please input the d for your series\n")) print ("The series produced by this method is") for i in range(1,11): print(generateNext(s,C), end=", ") C += s
true
d2393c795360448e3feda55adeb040bdb424b4f5
insalt-glitch/RCT_Comm
/data_handling.py
2,757
4.59375
5
"""Module for handling the conversions of different types that come from the device """ def to_string_conv(data): """Converts the from a int to a string. This method assumes the input is a ascii string and converts it to a default python string. Args: data: The input to the function. This has to be an integer. Returns: str_data: The input interpreted as a string. """ str_data = '' for _ in range(len(hex(data))//2): str_data += chr(data & 0xFF) data >>= 8 return str_data def to_float_conv(n, sgn_len=1, exp_len=8, mant_len=23): """ Converts an arbitrary precision Floating Point number. Note: Since the calculations made by python inherently use floats, the accuracy is poor at high precision. :param n: An unsigned integer of length `sgn_len` + `exp_len` + `mant_len` to be decoded as a float :param sgn_len: number of sign bits :param exp_len: number of exponent bits :param mant_len: number of mantissa bits :return: IEEE 754 Floating Point representation of the number `n` """ if n >= 2 ** (sgn_len + exp_len + mant_len): raise ValueError("Number n is longer than prescribed parameters allows") sign = (n & (2 ** sgn_len - 1) * (2 ** (exp_len + mant_len))) >> (exp_len + mant_len) exponent_raw = (n & ((2 ** exp_len - 1) * (2 ** mant_len))) >> mant_len mantissa = n & (2 ** mant_len - 1) sign_mult = 1 if sign == 1: sign_mult = -1 if exponent_raw == 2 ** exp_len - 1: # Could be Inf or NaN if mantissa == 2 ** mant_len - 1: return float('nan') # NaN return sign_mult * float('inf') # Inf exponent = exponent_raw - (2 ** (exp_len - 1) - 1) if exponent_raw == 0: mant_mult = 0 # Gradual Underflow else: mant_mult = 1 for b in range(mant_len - 1, -1, -1): if mantissa & (2 ** b): mant_mult += 1 / (2 ** (mant_len - b)) return sign_mult * (2 ** exponent) * mant_mult def data_conversion(data, d_type): """Data conversion from int to the specified type. This function converts the input parameter "data" into the given d_type which can be string, float, uint8, uint16, uint32, boolean. Args: data: The input (integer) that is to be converted into the proper format. d_type: The type as a string that the input is to be converted into. Returns: data: The given input in the proper format. """ if d_type == 'string': data = to_string_conv(data) elif d_type == 'float': data = to_float_conv(data) elif 'uint' in d_type: pass elif d_type == 'bool': data = bool(data) return data
true
e8cb659a871daabc3a166b2360fc6dfdd9996856
Muntaser/PythonExploration
/lab_7/remove.py
229
4.125
4
# # Muntaser Khan #remove.py # HTT9 Exercise 8: Write a function that removes all occurrences of a given letter from a string # def squeeze(s,ch): return s.replace(ch,"") def main(): print(squeeze("absolutely", 'b')) main()
true
cdc526af1c739f9d72611f08e225a45663631f84
Muntaser/PythonExploration
/HTT_6/http4_6.py
632
4.4375
4
# # Python program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon # # Author: Muntaser Khan # import turtle numSides = int(input("Enter the number of sides in polygon: ")) lengthSide = float(input("Enter the length of the side: ")) color = input("Enter the color of the polygon: ") fillColor = input("Enter the fill color of the polygon: ") wn = turtle.Screen() alex = turtle.Turtle() alex.begin_fill() for i in range(numSides): alex.color(color) alex.forward(lengthSide) alex.left(360/numSides) alex.color(fillColor) alex.end_fill() wn.exitonclick()
true
a50c06a333fd23e65472b8f2d988ca2c52611cff
rafaeltorrese/slides_programming-lecture
/03_executing-programs/05_recursive/exercise51.py
303
4.1875
4
def factorial_iterative(n): result = 1 for i in range(1, n + 1): result *= i return result def factorial_recursive(n): return 1 if n == 1 else n * factorial_iterative(n - 1) if __name__ == "__main__": print(factorial_iterative(5)) print(factorial_recursive(5))
false
89bc02f34b145b348f658e88a6b967af67d4daf3
PeihongKe/pythonRecipes
/oo/class_t.py
2,040
4.46875
4
import util class B(object): a = 'B.a' b = 'B.b' def __init__(self, a=0): """ """ self.a = a def f(self): return 'B.f()' def g(self): return 'B.g()' class C(B): b = 'C.b' c = 'C.c' def __init__(self, a=0, d=0): """ call base class's ctor; super(type[, object-or-type])""" # way 1: old style class B.__init__(self, a) # way 2: python 2 super(C, self).__init__(a) # way 3: python 3 What super does is: it calls the method from the next class in MRO (method resolution order). super().__init__(a) self.d = d def g(self): return 'C.g()' def h(self): return 'C.h()' class TestClassHierarchy(util.TestCaseBase): """ """ def test_data_attr_override(self): """ subclass override data attribute in super class """ c = C() self.assertEqual(c.b, 'C.b') def test_method_attr_override(self): """ subclass override callable attribute in super class""" c = C() self.assertEqual(c.g(), 'C.g()') def test_super_basic(self): pass def test_super_multi_inheritance(self): # https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance pass class TestInheritantFromBuiltIn(util.TestCaseBase): """ test inheritance with built in types """ def test_inherit_from_list(self): """ a class can inherit from built in types""" class MyList(list): """ inherit from builtin list""" def my_special_method(self): return "my special method" my_list = MyList() self.assertEqual(my_list.my_special_method(), 'my special method') def test_inherit_from_dict_list(self): """ multiple base classes have instance lay-out conflct""" with self.assertRaises(TypeError) as err: class MyListDict(dict, list): pass print(str(err.exception), 'multiple bases have instance lay-out conflict')
false
c33d9d0920c9729d71b67460500bb2195df56dfe
tiagniuk/sandbox
/luhn-checksum/luhn-checksum.py
734
4.15625
4
#!/usr/bin/env python # # Checks the validity of an input card number using the Luhn algorithm. # # Examples: # $ python luhn-checksum.py # Card number: 4561261212345467 # Card number is OK def split_d(strn): return list(map(int,strn)) def get_luhn_checksum(digits): odd_indexes = [x for i, x in enumerate(digits) if i % 2 != 0] even_indexes = [x*2 for i, x in enumerate(digits) if i % 2 == 0] return sum(odd_indexes) + sum(map(lambda x: x - 9 if x > 9 else x, even_indexes)) # checksum must be a multiple of 10 def is_valid(checksum): return checksum % 10 == 0 card_n = raw_input("Card number: ") print "Card number is " + (is_valid(get_luhn_checksum(split_d(card_n))) and "OK" or "Wrong") # -*- python -*-
true
eda8415ff922aa6df5ea70a6c4202b5b740529e5
royparth20/MyCaptain
/lession2.py
521
4.125
4
list1 = [1, 2, 3, 4, 5, 6] print(list1) list2 = [1, 2, 3, "Parth Roy", 5, [1515, "dasd"]] print(list2) tuple1 = tuple(list1) print(tuple1) tuple2 = tuple(list2) print(tuple2) tuple3 = ("Parth", "Roy", 1234, 489, [2, 3, 4, 5, "Roy"]) print(tuple3[1]) print(tuple3[4]) print(tuple3[0:-1]) dict1 = {"Name": "Parth Roy", "Address": "Surat,Gujarat", 1: "Temp123", "list": [20, 10, "ABCXYZ"]} print(dict1) dict1.pop("Address") print("Remove Address : ") print(dict1) del dict1["list"] print("Remove list : ") print(dict1)
false
95da169ff0d3c732b3c692d11727eb07663ac94f
MANI3415/WebDevelopmentUsingDjango-internship-SRM-University
/17-06-2021/files.py
765
4.15625
4
# Files # open(filename, mode) # create # open("file1.txt",'x') # write() - write data into the given file(if the file is already exist) # if the file is not there in the location, then write() will create a new file f = open("file2.txt","w") f.write("Python Programming\n") f.write("SRM University") f.close() # read() - to read the data in a file f = open("file1.txt","r") data1 = f.read(10) print(f.tell()) f.seek(2) print(f.tell()) data2 = f.read() print(f.tell()) print("Data1:",data1) print("Data2:",data2) f.close() # readlines() f = open("file1.txt","r") lines = f.readlines() print(lines) f.close() # append f = open("file1.txt","a") f.write("This is the new data") f.close()
true
529cc950330c513c5de1e79fef5e43fb0740382c
MANI3415/WebDevelopmentUsingDjango-internship-SRM-University
/18 june 2021/list_comprehension.py
435
4.21875
4
# list comprehension # calcualte the sum of these 3 digits # input= 123 # output = 6 n = input('enter a 3 digit value: ') #result_list = [] #for digit in n: # print(type(digit)) # digit_int = int(digit) # result_list.append(digit_int) #print('sum of the 3 digits: ',sum(result_list)) # syntax #[expression(t_var) for t_var in iterator] print('sum of the 3 digits: ', sum([int(digit) for digit in n]))
true
9dc9097ceabc9888e342e0cd0b44e6a0b423ac60
MANI3415/WebDevelopmentUsingDjango-internship-SRM-University
/15 june 2021/6_cubes_of_average_evennums.py
370
4.1875
4
# write a func to return average of cubes of all even numbers in between range #upper limit is inclusive def cubes_of_avg(lv,uv): s = 0 c = 0 for i in range(lv,uv+1): if i%2 == 0: s = s+i**3 c += 1 return s//c lv = int(input('lower limit: ')) uv = int(input('upper limit: ')) print(cubes_of_avg(lv,uv))
false
95786baefe6fa982a59ea42cf2816a6758c3e100
JohnSteck9/AlgorithmsPart3-Labworks
/Lab_2/sorting_algo.py
2,144
4.1875
4
# This function takes last element as pivot, places # the pivot element at its correct position in sorted # array, and places all smaller (smaller than pivot) # to left of pivot and all greater elements to right # of pivot # from typing import List class Sort: @staticmethod def partition(array: list, low: int, high: int) -> int: i = (low - 1) # index of smaller element pivot = array[high] # pivot for j in range(low, high): # If current element is smaller than or # equal to pivot if array[j] <= pivot: # increment index of smaller element i = i + 1 array[i], array[j] = array[j], array[i] array[i + 1], array[high] = array[high], array[i + 1] return i + 1 # The main function that implements QuickSort # arr[] --> Array to be sorted, # low --> Starting index, # high --> Ending index # Function to do Quick sort @staticmethod def quick_sort(array: list, low: int, high: int) -> list: if len(array) == 1: return array if low < high: # pi is partitioning index, arr[p] is now # at right place pi = Sort.partition(array, low, high) # Separately sort elements before # partition and after partition Sort.quick_sort(array, low, pi - 1) Sort.quick_sort(array, pi + 1, high) # return array @staticmethod def insertion_sort(array): # print(array) for i in range(1, len(array)): # Set key: key = array[i] j = i - 1 while j >= 0 and array[j] > key: # Swap: array[j + 1] = array[j] array[j] = key # Decrement 'j': j -= 1 # return array if __name__ == '__main__': # Driver code to test above arr = [10, 7, 8, 5, 9, 1, 5, 5] print(arr) Sort.quick_sort(arr, 0, len(arr) - 1) print(arr) # print("Sorted array is:") # for i in range(n): # print("%d" % arr[i])
true
73b56bf7ff7b9626cb20a01c09797f36ce939da5
mreishus/aoc
/2017/03/python_day03/day03.py
2,062
4.15625
4
#!/usr/bin/env python3 from collections import defaultdict """ Advent of Code 2037 Day 03. """ """ directions we want to travel in order: dx dy RIGHT 1 0 UP 0 1 LEFT -1 0 DOWN 0 -1 To get the next value: dx = -1 * old_dy dy = old_dx """ class Day03: """Main module for solving Day03.""" @staticmethod def should_rotate(x, y): if x == 0 and y == 0: return False # Top right and bottom left corners if x == y: return True # Bottom right if x > 0 and x * -1 == y - 1: return True # Top Left if x < 0 and x == -y: return True return False @staticmethod def part1(target): x = -1 y = 0 delta_x = 1 delta_y = 0 for _ in range(0, target): if Day03.should_rotate(x, y): # print("rotating") delta_x, delta_y = delta_y * -1, delta_x x += delta_x y += delta_y return abs(x) + abs(y) def neighbor_sum(grid, x, y): if x == 0 and y == 0: return 1 sum = 0 for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: if dx == 0 and dy == 0: continue sum += grid[(x + dx, y + dy)] return sum def part2(target): grid = defaultdict(lambda: 0) grid[(0, 0)] = 1 x = -1 y = 0 delta_x = 1 delta_y = 0 while 1: if Day03.should_rotate(x, y): # print("rotating") delta_x, delta_y = delta_y * -1, delta_x x += delta_x y += delta_y neighbor_sum = Day03.neighbor_sum(grid, x, y) grid[(x, y)] = neighbor_sum if neighbor_sum > target: return neighbor_sum # print(f"x{x} y{y} sum{neighbor_sum}") if __name__ == "__main__": print("Part1: ") print(Day03.part1(265149)) print("Part2: ") print(Day03.part2(265149))
true
52411c9b478f4189917c89b28c4052cd5572b1e7
CarlosViniMSouza/Python-BackEnd-Django
/PyBeginner/01_Lists.py
1,906
4.4375
4
# About Lists: countries = ['BRA', 'CHI', 'ARG', 'URU', 'PAR'] # create a list. print(countries[2]) # return the initials 'ARG' print(countries[2][1]) # return the word 'R' of word 'ARG' print(countries[2:]) # return the words: ['ARG', 'URU', 'PAR'] print(countries[1:3]) # return the words: ['CHI', 'ARG'] print(type(countries)) # return: <class 'list'> countries[0] = 'CAN' # replaces 'BRA' by 'CAN' print(countries) print(countries[-1]) # print the last word in the list = PAR print(countries[-2]) # print the second-last word in the list = URU var = list(('Carlos', 20, 'M', 100.5)) # using method list() for create a list. # similar to: var = ['Carlos', 20, 'M', 100.5] print(var, "\n", type(var)) # Methods List: var_test1 = list((1, 5, 10)) var_test2 = list(("Pencil", "Book", "Pen")) var_test1.extend(var_test2) # 1 -> extend() : Add 2 lists in only 1 list. print(var_test1) var_test2.append("NoteBook") # 2 -> append() : Add 1 new element in selected list. print(var_test2) print(len(var_test1)) # 3 -> len() : return the length of list. var_test2.insert(1, "PDFs") # 4 -> extend() : Add 1 new object in the position that you chose. print(var_test2) # -> In this case, the element "PDFs" was add in position var_test2[1]. var_test1.remove(5) # 5 -> remove() : Remove 1 element selected of list. print(var_test1) var_test2.clear() # 6 -> clear() : remove all elements of list. print(var_test2) print(var_test1.index('Book')) # 7 -> index() : return the position of element in list. var_test3 = [1, 10, 5, 20, 15, 30] # a new list called var_test3. var_test3.sort() # 8 -> sort() : rearranges elements in descending order. print(var_test3) var_test3.reverse() # 9 -> reverse() : invert the list. print(var_test3) var_test3.pop(2) # 10 -> pop() : delete a element in the position specific # similar to: del var_test3[2] print(var_test3) # In next session: Tuples in python!
true
85d0b81a77158cfc09e1b8ed51bcee0f6110d894
maithili16/MyCaptain-project
/l1.py
591
4.28125
4
#Assigning elements to different lists l1=[] l2=[] l1.append(1) l1.append(2) l1.append("mango") print(l1) l2.append("John") print(l2) l2.extend(["Ron",6,7]) print("l2=",l2) l1.extend([10,11,12,"apple"]) print("l1=",l1) #Accessing Elements from a tuple tup1=(1,2,3,"hello","python") print(tup1[1]) print(tup1[4]) print(tup1[0:])#accessing all the elements of a tuple #Deleting different dictionary elements dict1={1:"a",2:"b",3:"c",4:"d"} print(dict1.items()) print(dict1.values()) print(dict1.pop(4)) print(dict1) dict1.popitem() print(dict1)
false
f6808b3b717d6e56e62eab405710535a0eff54c3
Shubham2227/hacktoberfest2021-3
/list.py
509
4.78125
5
# Python program to demonstrate # Creation of List # Creating a List List = [] print("Blank List: ") print(List) # Creating a List of numbers List = [10, 20, 14] print("\nList of numbers: ") print(List) # Creating a List of strings and accessing # using index List = ["Geeks", "For", "Geeks"] print("\nList Items: ") print(List[0]) print(List[2]) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [['Geeks', 'For'] , ['Geeks']] print("\nMulti-Dimensional List: ") print(List)
false
e4133533b3c0da52a61cd3a3aa47b2e5a880a65a
cindygao93/adjacency-list-matrix
/intuit.py
1,887
4.21875
4
##intuit python ## this project takes two csv files, one of a list of employees, with their employee id, name, and department, ## the second csv file denotes pairs of friends within the company based on their employee ids. ## The programs prints off an adjacency list of employees and their corresponding friends at the company based off of these two files. import csv ## parses the csv file and returns a list of lists. Each individual list in the list represents a line from the csv file. def parser(csvfile_name, aList): with open(csvfile_name, 'rb') as csvfile: reader = csv.reader(csvfile) for row in reader: aList.append(row) aList = aList[1:] return aList ## this function takes two lists of lists as parameteres, which were the outputs from parsing the csv files ## it returns an adjacency matrix string that prints the employee id as the first column and subsequent ## numbers in the row as the employee's friends' id ## example output: ## 1: 2, 3 ## 2: 1, 4 ## 3: 1 ## 4: 2 ## 6: None def friend_matrix(employ, friend): friendList = [] matrix = "" for record in employ: matrix = matrix + record[0] + ": " friend_connect = [] for item in friend: if record[0] == item[0]: friend_connect.extend(item[1]) elif (record[0] == item[1]): friend_connect.extend(item[0]) if friend_connect == []: matrix = matrix + 'None' + '\n' else: i=0 while i<len(friend_connect) - 1: matrix = matrix + friend_connect[i] + ', ' i = i+1 matrix = matrix + friend_connect[i] + '\n' friendList.append(friend_connect) return matrix ## using the example csv files files in the same directory, this main function prints off the adjacency matrix mentioned in the beginning def main(): employees = parser('employees.csv', []) friendships = parser('friendships.csv', []) print friend_matrix(employees, friendships) main()
true
451a4d1b331be040b9703e061c3ef765a22d7939
snehal2841/DivisibilityTestPrograms
/Python/TestFor3.py
654
4.625
5
def test_for_3(quotient): """Divisibility test to check if the quotient is a multiple of 3, without using the modulo operator. This can be done, by checking if the digit sum, is 3, 6, or 9, once it gets to be a single digit.""" digit_sum = int(quotient) while digit_sum > 9: digits = str(digit_sum) total = 0 for digit in digits: total += int(digit) digit_sum = total if digit_sum in [0, 3, 6, 9]: return True else: return False # Test to check that the function behaves properly for i in range(100): print("{} divisible by 3 {}".format(i, test_for_3(i)))
true
1691b6ab9c0528c9888afac60da3837846b132ce
snehal2841/DivisibilityTestPrograms
/Python/TestFor_any_number_list.py
522
4.375
4
# Python Program to find numbers divisible by thirteen from a list using anonymous function my_list = [] size = int(input("Enter size of list: \t")) for n in range(size): numbers = int(input("Enter any number: \t")) my_list.append(numbers) # for adding num to list x = int(input("\nEnter the number for division: ")) # Take a list of numbers # use anonymous function to filter result = list(filter(lambda y: (y % x == 0), my_list)) # display the result print("Numbers divisible by entered number is",result)
true
afd7adaaa0d1d264ae541df29ba03ce4a843ec95
nonnikb/verkefni
/Lokapróf/2Decisions and booleans/Leap year.py
644
4.25
4
"""Here is an algorithm to determine whether a year is a leap year. 1. If the year is evenly divisible by 4, go to step 2, otherwise go to step 5 2. If the year is evenly divisible by 100, go to step 3, otherwise go to step 4 3. If the year is evenly divisibele by 400, go to step 4. Otherwise go to step 5 4. The year is a leap year (has 366 days) 5. The year is not a leap year ( has 365 days) """ year = input("Enter a year: ") year = int(year) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("True") else: print("False") else: print("True") else: print("False")
true
889a7fa398829b265dca04f28f69d74f01d5f74d
nonnikb/verkefni
/æfinar.py
266
4.125
4
name = input("Input a date: ") if name = ("january 1""june 17""december 25"): first, last = name.split(' ') fnam = last flname = first print("Month: ", flname) print("Day: ", fnam) print("National holiday") else: print("Not a holiday")
false
4aba376d60cb172cc1399fe7f012561bcc21fc67
nonnikb/verkefni
/Lokapróf/2Decisions and booleans/Largest integer.py
254
4.46875
4
"""Write a program that reads in 3 integers and prints out the maximus of the three""" num1 = input("Enter number 1: ") num2 = input("Enter number 2: ") num3 = input("Enter number 3: ") nums = [num1, num2, num3] print("Biggest number is :", max(nums))
true
52a575e7140c1fb32a8ab8a129200a09da1a4a9f
nonnikb/verkefni
/Lokapróf/6 Strings/Collect digits.py
450
4.125
4
"""Given a string of any length, extract the numbers and print them on one line without spaces. Hint 1: start with an empty string. Hint 2: isdigit[] is your friend. For example, given this string. some 1! likes 2 put 14 digits, in 3 strings the output will be : 12143""" my_str = "some 1! likes 2 put 14 digits, in 3 strings" #input("Input a string: ") digit = [] for i in my_str: if i.isdigit(): digit.append(i) print(''.join(digit))
true
1647028503c0e43aa48e99dcb232066a07b6152d
nonnikb/verkefni
/Lokapróf/6 Strings/Indexing.py
265
4.375
4
"""Given a string of any length named s. Extract and then print the first and last characters of the string (with one space between them) For example, given s ='abcdef' the output will be 'a f' """ my_str = input("Input a string: ") print(my_str[0]+""+my_str[-1])
true
70e1c55302cf07894040cb6adb6a84d6e70b19e2
nonnikb/verkefni
/Lokapróf/6 Strings/Integer to binary.py
539
4.25
4
"""Write a Python program that reads an integer from the user and prints out the binary equivalent value. How do we get a binary string from an integer? The easiest method uses integer division by 2 on successive quotients and then collects the remainders. It is best illustrated by an example. """ my_int = int(input("Give me an int >=0: ")) """binary = [] if my_int % 2 == 0: binary.append(0) elif my_int % 2 == 1: binary.append(1) print(binary)""" bstr = "{0:b}".format(my_int) print("the binary of", my_int, "is", bstr)
true
a9014acf3d03cbe46d1e49ff2b9673abea31c2b7
saashimi/ks-personal
/wk1/wk1.0_factorial.py
246
4.21875
4
def factorial_(n): """Returns the factorial of n.""" count = 1 for elem in range(1, n+1): count *= elem return count if __name__ == "___main___": n = eval(input("Please enter a number: ")) print(factorial_(n))
true
3f02d42dbeedadfbddb91d59e986fe8ae805b05d
bardayilmaz/270201019
/lab3/example2.py
254
4.21875
4
num1 = int(input("Type first num: ")) num2 = int(input("Type second num: ")) num3 = int(input("Type third num: ")) if num1 < num2 and num1 < num3: print(num1) elif num2 < num1 and num2 < num3: print(num2) elif num3 < num1 and num3 < num2: print(num3)
false
318f01f633a20b689a6aeece38422f3891d0999a
Jedidiah0546/Python-Assign...
/zellers.py
1,572
4.40625
4
# zeller_congruence.py # 10/28/17 # Zeller's congruence is an algorithm # developed by Christian Zeller to # calculate the day of the week. name= input("Enter your name") year = int(input('Enter year(e.g. 2015): ')) month = int(input('Enter month(1-12): ')) day = int(input('Enter day of the month(1-31): ')) # If January or February is entered you must add # 12 to the month and minus 1 from the year. This # puts you in month 13 or 14 of previous year. if month == 1: month = month + 12 year = year - 1 elif month == 2: month = month + 12 year = year - 1 century = (year // 100) century_year = (year % 100) # Day of the week formula dotw = (day + ((26 * (month + 1)) // (10)) + century_year + ((century_year) // \ (4)) + ((century) // (4)) + (5 * century)) % 7 if dotw == 0: print("Your name is {} and the day of the week you were born on is Saturday".format(name)) elif dotw == 1: print('Your name is {} and the day of the week you were born on is Sunday'.format(name)) elif dotw == 2: print('Your name is {} and the day of the week you were born on is Monday'.format(name)) elif dotw == 3: print('Your name is {} and the day of the week you were born on is Tuesday'.format(name)) elif dotw == 4: print('Your name is {} and the day of the week you were born on is Wednesday'.format(name)) elif dotw == 5: print('Your name is {} and the day of the week you were born on is Thursday'.format(name)) elif dotw == 6: print("Day of the week is Friday".format(name))
false
b802e10cccb688aa0d7b478221586d321cb07b28
RiKjess/SololearnPY
/3. Control Structures/Let'sDance.py
772
4.34375
4
""" if Statements You have been asked to coordinate the dance school competition․ The terms of the competition are as follows: - if the score is 80 or more the participant gets a certificate - if the score is 90 or more the participant gets a certificate and also is admitted to the school. The given program takes the score as input. Task Complete the program that will output "certificate" if the score is greater than or equal to 80. On top of that, the program should also output "admitted" if the score is greater than or equal to 90. Sample Input 91 Sample Output certificate admitted Hint Use nested if statements to handle all the conditions. """ score = int(input()) if score >= 80: print("certificate") if score >= 90: print("admitted")
true
ca4ee31cbffdcdb77917bf383d08d18826da9738
RiKjess/SololearnPY
/8. OOP/StaticMethods.py
411
4.21875
4
""" Static Methods Complete the given code to define a static add() method for the Calculator class, which returns the sum of its parameters. The code takes two numbers as input, and should return their sum using the Calculator class's add() method. """ class Calculator: @staticmethod def add(n1, n2): return n1+n2 n1 = int(input()) n2 = int(input()) print(Calculator.add(n1, n2))
true
32e261772329501e3d8d7acbd6876d95a63cc6ca
RiKjess/SololearnPY
/10. Pythonicness & Packaging/EggSandwich.py
609
4.53125
5
""" Default Values You are given a function for a hotel booking service. The First argument is the number of people staying in the hotel room, the second is the number of days, and the third is for breakfast option choice. Taking into account that visitors do not always mention their breakfast choice, we need to set the "Egg Sandwiches" option as the default. Complete the function so that the given code works correctly. """ def book(people, days, breakfast = "Egg Sandwiches"): print("People:", people) print("Days:", days) print("Breakfast:", breakfast) book(5,3, "Peanut Butter Bites") book(4,5)
true
5a76bcaf159679c4aa56097feefb4cfdbfcc02c3
RiKjess/SololearnPY
/3. Control Structures/DatePicker.py
483
4.15625
4
""" Range You are making a date picker for a website and need to output all the years in a given period. Write a program that takes two integers as input and outputs the range of numbers between the two inputs as a list. The output sequence should start with the first input number and end with the second input number, without including it. Sample Input 2005 2011 Sample Output [2005, 2006, 2007, 2008, 2009, 2010] """ a = int(input()) b = int(input()) print(list(range(a,b)))
true
1894951c434854a148c8f72e217cf9a4783aa7d4
RiKjess/SololearnPY
/3. Control Structures/ToPythagorasOrNotTo.py
842
4.28125
4
""" Else Statement Pythagoras theorem says: In a right-angled triangle, the square of the hypotenuse side is equal to the sum of squares of the other two sides. Write a program that takes lengths of triangle sides as inputs, and output whether our triangle is right-angled or not. If the triangle is right-angled, the program should output "Right-angled", and "Not right-angled" if it's not. Sample Input 3 4 7 Sample Output Not right-angled """ side1 = int(input()) side2 = int(input()) side3 = int(input()) if int(side1 ** 2 + side2 ** 2) == int(side3 ** 2): print("Right-angled") else: if int(side1 ** 2 + side3 ** 2) == int(side2 ** 2): print("Right-angled") else: if int(side2 ** 2 + side3 ** 2) == int(side1 ** 2): print ("Ringt-angled") else: print ("Not right-angled")
true
4683463e6ad2f96a55eb01c4675cb8f0cd9ce171
RiKjess/SololearnPY
/8. OOP/BankAccounts.py
623
4.46875
4
""" Operator Overloading The __add__ method allows for the definition of a custom behavior for the + operator in our class. The provided code is trying to add together two BankAccount objects, which should result in a new object with the sum of the balances of the given accounts. Fix the code to make it work as expected and output the resulting account balance. """ class BankAccount: def __init__(self, balance): self.balance = balance def __add__(self, other): return BankAccount(self.balance + other.balance) a = BankAccount(1024) b = BankAccount(42) result = a + b print(result.balance)
true
032a9b3d3ae3dfc90a95e55d1bbd09c29e0a28fb
RiKjess/SololearnPY
/6. More Types/NamesAndAges.py
329
4.625
5
""" String Formatting The .format() method provides an easy way to format strings. Take as input a name and an age, and generate the output "name is age years old". Sample Input James 42 Sample Output James is 42 years old """ name = input() age = int(input()) msg = "{y} is {x} years old".format(y=name, x=age) print(msg)
true
1000165270a136f40ecac7f2d2634bf4ef3fa00d
Bala13102002/Hacktoberfest2021-
/Dog Years.py
939
4.21875
4
""" Some say that every one year of a human’s life is equivalent to seven years of a dog’s life. Hence, I decided to write a function called dog_years that has two parameters named name and age. This function computes the age in dog years and return your dog name and dog_years age. condition: 1. Dog name is consider of letters only. 2. Dog age must be whole number and more than 0 """ def dog_years(name, age): return "{}, you are {} years old in dog years".format(name, age*7) print("This is a dog year program which calculates a dog’s age in dog years.\n") while True: name = input("Please enter your dog name: ") if name.isalpha(): break print("invalid name. please re-type your dog name.\n") while True: age = input("Please enter your dog age: ") if age.isnumeric() and int(age) >= 0: break print("invalid age. please re-type your dog age.\n") print(dog_years(name, int(age)))
true
932447ad6a29db6bd76e65c2eb09e71ed40f0c37
LuccaMS/LearningPython
/undo redo.py
1,276
4.1875
4
if __name__ == '__main__': print("Opção 1 : Adicionar Tarefa") print("Opção 2 : Listar Tarefas") print("Opção 3 : Desfazer ") print("Opção 4 : Refazer ") print("Opção 5 : Sair do programa ") lista_tarefas = [] lista_auxiliar = [] while True: op = input("Digite uma opção: ") if not op.isnumeric(): print("A opção digitada não é numerica, digite novamente ") else: if op == '1': aux = input("Digite uma tarefa: ") lista_tarefas.append(aux) elif op == '2': for i, x in enumerate(lista_tarefas): print(f'Tarefa de número {i + 1} , conteúdo : {x}') elif op == '3': lista_auxiliar.append(lista_tarefas[-1]) lista_tarefas.pop() elif op == '4': try: last = lista_auxiliar.pop() lista_tarefas.append(last) except IndexError: print("Nenhum elemento foi excluido até o momento ou todos já foram recuperados") elif op == '5': break else: print("Opção inexistente")
false
6812c882f4bbc794ef45d5a7e47a26e84fbf9bb7
anandology/pygame-workshop
/game1.py
784
4.59375
5
""" Simple pygame program to draw a circle on the screen. PROBLEMS: Problem 1: * Change the color of the ball to red, blue and gray * Try changing the RGB Problem 2: Move the ball to the top-right corner. Will the ball stay in the top-right corner if the size is changed to something else? Problem 3: Draw balls in all the 4 the corners. Problem 4: Draw a row full of balls. Problem 5: Fill the screen with balls. """ import pygame pygame.init() # Set the window size size = 400, 400 screen = pygame.display.set_mode(size) color = 255, 255, 0 # R G B center = (200, 200) radius = 25 pygame.draw.circle(screen, color, center, radius) # display whatever is drawn so far pygame.display.flip() # wait for 3 seconds so that we can see the window pygame.time.wait(3000)
true
709a232b70f36c3d18598fd893cbdb3af25c47db
krenevych/oop
/source/P_03/L27_SystRecur2.py
602
4.125
4
def rec(N, a, b): """ Знаходження елементів послідовності використовуючи рекурентні співвідношення :param N: Номер члена послідовності, що необхідно знайти :param a: Параметр :param b: Параметр :return: Знайдений член послідовності. """ S = x = 1 for n in range(1, N + 1): x = a * x S = b * S + x N = int(input("N = ")) a = float(input("a = ")) b = float(input("b = ")) print(rec(N, a, b))
false
bd7953e8865cb55fcd00de3eb63cdd6cc00d817b
sqq0216/testLearn
/pythonLearn/python/test/classlearn.py
1,838
4.25
4
class Student(object): def __init__(self, name, age, love): self.name = name self.age = age self.__love = love # 数据封装:在类内部定义方法来处理数据 #与普通函数不同,类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数 def getName(self): return self.name def getAge(self): return self.age #实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问 def getLove(self): return self.__love def setLove(self,love): self.__love = love qianqian = Student('aqian', 24, 'tianyu') print(qianqian.getAge()) print(qianqian.getName()) print(qianqian.getLove()) #print(qianqian.__love)#无法访问————————访问限制 class Tianyu(Student): # 当子类和父类都存在相同的getName()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。这样,我们就获得了继承的另一个好处:多态。 #覆盖重写不需要的方法,其它可以直接拿来用 def getName(self): print('创建子类成功') return self.name tian = Tianyu('tianyu', 25, 'qianqian') print(tian.getName()) print(tian.getAge()) # 可以通过实例变量或者self给实例绑定属性 tian.hign = 170 print(tian.hign) # 也可以给类本身绑定一个属性,其实例都可以访问该属性 #test:实例自动加1 class Students(object): count = 0 def __init__(self, name): self.name = name Students.count += 1 print(Students.count) zhang = Students('zhang') print('zhang_count', zhang.count) li = Students('li') print('li_count:', li.count) print(Students.count)
false
f45221a10790cc7debea237ae956eae790f465dd
wzhrj1234/book_coding
/python/core_python_programming/unit8/8-7,8.py
397
4.125
4
# -*- coding: utf-8 -*- """ 8-8,8-9 阶乘,斐波那耶数 """ def factorial(num): i=1 result=1 while i<=num: result*=i i+=1 return result def fbny(num): result=[1,1] if num in (1,2): return 1 i=3 while i<=num: result.append(result[i-2]+result[i-3]) i+=1 return result[num-1] print factorial(5) print fbny(5)
false
411164cd2f06d3beb2fb3700d67ab0da49e89860
aruntonic/Scribble
/LRU.py
2,786
4.1875
4
class Node(): """ Node class defines an object in double linked list to maintain the cache """ def __init__(self, key, data): self.data = data self.key = key self.prev = None self.nxt = None class LRUCache(): def __init__(self, size): self.size = size self.hash_table = dict() self.head = None self.end = None def __add(self, node): """ Function adds the node to the top of the cache making it as the MRU element :param node: the node which needs to be added :return: None """ if self.head: self.head.prev = node node.nxt = self.head self.head = node else: self.head = node self.end = node def __remove(self, node): """ Function removes the element from cache :param node: node which needs to be removed :return: None """ if self.head == self.end and self.head == node: self.head = None self.end = None elif self.head == node: self.head.nxt.prev = None self.head = self.head.nxt elif self.end == node: self.end.prev.nxt = None self.end = self.end.prev else: node.prev.nxt = node.nxt node.nxt.prev = node.prev def get(self, key): """ get function - to retrieve the value based on the key :param key: :return: the data value for the requested key ; None - if key not found """ if key in self.hash_table: get_node = self.hash_table[key] if self.head == get_node: pass else: self.__remove(get_node) self.__add(get_node) return get_node.data def put(self, key, data): """ Add the key and data to the cache. if key already exists , the data is updated and object is made the MRU element :param key: key of the data to be added to cache :param data: corresponding data object to be added to the cache :return: None """ if key in self.hash_table: get_node = self.hash_table[key] if self.head == get_node: pass else: self.__remove(get_node) self.__add(get_node) get_node.data = data return # if Cache size is full, remove the LRU element if len(self.hash_table) == self.size: del self.hash_table[self.end.key] self.__remove(self.end) new_node = Node(key, data) self.__add(new_node) self.hash_table[key] = new_node
true
f0d98ffe7ec95c15c5b6ec87e655f26d1ecefb2d
HausCloud/Holberton
/holbertonschool-higher_level_programming/0x07-python-test_driven_development/5-text_indentation.py
577
4.3125
4
#!/usr/bin/python3 """ Module to indent text depending on certain characters """ def text_indentation(text): """ function to indent stuff """ if type(text) is not (str): raise TypeError("text must be a string") x = 0 for char in text: if char is " " and x == 0: continue if char is not " " and x == 0: x = -1 if char is not "." and char is not "?" and char is not ":": print(char, end="") else: print(char, end="") print() print() x = 0
true
7b3ed25621e0bf387f951846b4f61333519deb80
FatChicken277/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,727
4.25
4
#!/usr/bin/python3 """This module has a function that divides all elements of a matrix. """ def matrix_divided(matrix, div): """Divides all elements of a matrix. Arguments: matrix (list) -- matrix of lists. div (int/float) -- divisor. Raises: TypeError: matrix must be a matrix (list of lists) of integers/floats. TypeError: div must be a numbe. ZeroDivisionError: division by zero. TypeError: matrix must be a matrix (list of lists) of integers/floats. TypeError: Each row of the matrix must have the same size. TypeError: matrix must be a matrix (list of lists) of integers/floats. Returns: list -- returns a new matrix with all divisions """ if type(matrix) is not list or len(matrix) == 0: raise TypeError( "matrix must be a matrix (list of lists) of integers/floats") if type(div) not in [int, float]: raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") lon = [] array = [] for items in matrix: if type(items) is not list or len(items) == 0: raise TypeError( "matrix must be a matrix (list of lists) of integers/floats") if lon == []: lon.append(len(items)) if lon[-1] == len(items): lon.append(len(items)) else: raise TypeError("Each row of the matrix must have the same size") for item in items: if type(item) not in [int, float]: raise TypeError("matrix must be a matrix\ (list of lists) of integers/floats") array.append([round(x / div, 2) for x in items]) return array
true
61048880d4c32e7b3218a23ea57803a7c4364204
FatChicken277/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
662
4.21875
4
#!/usr/bin/python3 """This module contains a function that reads n lines of a text file (UTF8) and prints it to stdout. """ def read_lines(filename="", nb_lines=0): """Reads n lines of a text file (UTF8) and prints it to stdout. Keyword Arguments: filename {str} -- file name (default: {""}) nb_lines {int} -- lines to read (default: {0}) """ with open(filename, mode="r", encoding="utf-8") as file: if nb_lines <= 0: print(file.read(), end="") else: for idx, line in enumerate(file): if idx == nb_lines: break print(line, end="")
true
749a627564f62216a30b67da55be983fe4d2529f
FatChicken277/holbertonschool-higher_level_programming
/0x06-python-classes/3-square.py
765
4.625
5
#!/usr/bin/python3 """Create and define the class "Square". This module creates an class called "Square" that defines a square. Typical usage example: var = Square() or var = Square(arg) """ class Square: """Defines a Square. Defines a square and its values subject to certain conditions. Attributes: __size: size of the square. """ def __init__(self, size=0): """Inits Square with a size subject to certain conditions.""" if size != int(size): raise ValueError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") self.__size = size def area(self): """Returns the current square area.""" return self.__size * self.__size
true
10cbcc282443b4a62c5cb804364dd17155d7ab4f
adamdrucker/python-median-calculator
/median.py
1,067
4.1875
4
# The median is the value at the middle point of a list of numbers # Arrange the numbers in sequential order, then locate the the value # in the middle. If there the list is even, and there is no definite # middle value, add up the two values in the middle and find their mean. def median(): # Enter a number, or 'q' to quit iVal = input("Enter a number for median calculation (q to quit): ") iList = [] # Init empty list # Append input to list while iVal != 'q': iList.append(int(iVal)) iVal = input("Enter a number for median calculation (q to quit): ") # Main stuff iLen = len(iList) # Calculate list length iList.sort() # Sort list # Calculate median iPos = int((iLen - 1) / 2) print(iList) # Check what the list looks like # If list length is odd if iLen % 2 != 0: print(f"Median: {iList[iPos]}") # If list length is even else: iMedian = (iList[iPos] + iList[iPos + 1]) / 2 print(f"Median: {iMedian}") median()
true
c72abf19fe8ee845a667eebb0a3cf451056178ba
irinaignatenok/Python
/week6/day1/ExerciseXP.py
1,876
4.59375
5
#Print the following output in one line of code: #Hello world #Hello world #Hello world #Hello world print("Hello world \nHello world \nHello world\nHello world ") #Exercise2 #(99^3) * 8 print((99^3) * 8) #Exercise 3 : What Is The Output ? #Predict the output of the following code snippets: 5 < 3 #False 3 == 3 #True 3 == "3" #True "3" > 3 #False "Hello" == "hello" #False #Exercise 4 : Your Computer Brand computer_brand = "macbook_air" print(f"I have a {computer_brand} computer") #Exercise 5: Your Information name = "Irina" age = 30 shoe_size = 39 info = f"Hi my name is Irina, I live in Tel Aviv.I am {age} years old.Unfortunately I have a {shoe_size} shoe size" print(info) #Exercise 6: Odd Or Even #Write a script that asks the user for a number and #determines whether this number is odd or even. number = int(input("Please,enter a number: ")) if (number%2 == 0): print("The number is even") else: print("The number is odd") #Exercise 7 : What’s Your Name ? #Write a script that asks the user for his name and determines #whether or not you have the same name, #print out a funny message based on the outcome my_name = "Sarah" name = input("Please, write me your name: ") if name == my_name: print("You stole my name...") else: print(f"Actually, the name {my_name} would suit you") #Exercise 8 : Tall Enough To Ride A Roller Coaster #Write a script that will ask the user for their height #in inches, print a message if they can ride a roller #coaster or not based on if they are taller than 145cm #Please note that the input is in inches and you’re #calculating vs cm, you’ll need to convert your data accordingly #1 in = 2.54 cm height = int(input("Please write your height in inches")) print(height) if (height/2.54) > 145: print("You can ride a roller coaster") else: print("Unfortunately You're not tall enought")
true
bb49c8b504078dea81a60d39e3c3d61f9d823500
irinaignatenok/Python
/week6/day1/XPNinja.py
752
4.25
4
my_text = ''' Lorem ipsum dolor sit amet,consectetur adipiscing elitsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamcolaboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ''' print(len(my_text)) #Exercise 5: Longest Word Without A Specific Character sentence = input("Please write a long sentence without letter a: ") sentence.lower() letter_a = sentence.find("a") print(letter_a) if letter_a == -1: print("congratulation!") else: input("Try again")
false
8688b7d86a50b02f626278ef30c37749c3239626
mengsince1986/coding_bat_python
/warmup-2/array123.py
557
4.1875
4
def array123(nums): """ Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere. >>> array123([1, 1, 2, 3, 1]) True >>> array123([1, 1, 2, 4, 1]) False >>> array123([1, 1, 2, 1, 2, 3]) True """ found_123 = False i = 0 while not found_123 and i + 2 < len(nums): if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3: found_123 = True i += 1 return found_123 if __name__ == '__main__': import doctest doctest.testmod()
true
de8bbf4e6755ac8c1a3bc3c47c38a80ee0286745
mengsince1986/coding_bat_python
/string-2/end_other.py
773
4.34375
4
""" def end_other(a, b): a = a.lower() b = b.lower() return (b.endswith(a) or a.endswith(b)) """ def end_other(a, b): """ Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string. >>> end_other('Hiabc', 'abc') True >>> end_other('AbC', 'HiaBc') True >>> end_other('abc', 'abXabc') True """ if len(a) < len(b): result = b[-len(a):].lower() == a.lower() else: result = a[-len(b):].lower() == b.lower() return result if __name__ == '__main__': import doctest doctest.testmod()
true
11b13936cc0fc48a7d92da652805def6fca34c8a
vaibhavvats/codes-1
/exponentiationBySquaring.py
511
4.5
4
#!/usr/bin/env python ''' This method is used to efficiently find x^n in log(n) time''' def exponentiationBySquaring(x, n): if n == 1: return x elif n % 2 == 0: return exponentiationBySquaring(x * x, n / 2) else: return x * exponentiationBySquaring(x * x, (n - 1) / 2) def main(): x = int(raw_input("Enter a number: ")) n = int(raw_input("Enter the power: ")) print str(x) + '^' + str(n) + ' = ' + str(exponentiationBySquaring(x, n)) if __name__ == '__main__': main()
false
f7712d21721d637c1da8486e72ad323522968597
brunolcarli/maradona
/core/room.py
1,298
4.15625
4
from random import randint class Room3D: """ Uma sala é representada por um espaço cartesiano XY. Uma sala deverá ter um nome de referência. Por padrão as salas tem dimensão 5x5 podendo ser alterado """ def __init__(self, name, max_size_x=5, max_size_y=5): self.name = name self.max_size_x = max_size_x self.max_size_y = max_size_y self._map = self.build() def build(self): """ Inicializa a sala com 0s e 1s. """ return [[randint(0, 1) for _ in range(self.max_size_x)] for _ in range(self.max_size_y)] def __str__(self): return f'Room {self.name}' def __getitem__(self, index): return self._map.__getitem__(index) def __delitem__(self, index): self._map.__delitem__(index ) def insert(self, index, value): self._map.insert(index, value) def __setitem__(self, index, value): self._map.__setitem__(index, value) def __getitem__(self, index): return self._map.__getitem__(index) def show(self): print('\t N\n') for row in self._map: line = ' '.join(str(i) for i in row) print(f'\t[ {line} ]') print('\n\t S') print('-------------------------------')
false
a84ab266c2294403199167638a46fb7268132609
lallaw8809/Controller
/Raspberry_Pi/Led/led.py
522
4.28125
4
# Program to blink the LED at regular intervel. # Author : Lal Bosco Lawrence # Date : 30/12/2017 import RPi.GPIO as GPIO # Import GPIO library import time LED_PIN = 7 # GPIO pin Number TIME_DELAY = 1 # Time delay in sec GPIO.setmode(GPIO.BOARD) # Use board pin numbering GPIO.setup(LED_PIN, GPIO.OUT) # Setup GPIO Pin 7 to Output # Blink the LED while True: GPIO.output(LED_PIN,True) # Turn ON GPIO pin 7 time.sleep(TIME_DELAY) GPIO.output(LED_PIN,False) # Turn OFF GPIO pin 7 time.sleep(TIME_DELAY)
true
e2a55755695e1c3ca9439c79b90558a94298e138
dejac001/DataStructures
/sorting_algorithms/merge_sort.py
1,036
4.1875
4
def merge(l1: list, i, istop, jstop): """Merge two *sorted* lists. - jstop is *not* part of the second list - istop is *not* part of the first list """ start = i j = istop newlist = [] while i < istop: if j == jstop or l1[i] < l1[j]: newlist.append(l1[i]) i += 1 elif j < jstop: newlist.append(l1[j]) j += 1 # copy back to original sequence for ii in range(len(newlist)): l1[start + ii] = newlist[ii] def sort(my_list: list, i_start: int, i_end: int): """Merge sort in-place""" if i_start >= i_end - 1: # if i == j - 1, length of list is 1 (first list has len 1 and other list has len 0) # need > b/c when call w/ i_mid+1 below, dont check if larger than j # thus, below, we will only be sorting two lists, each of length 1 return i_mid = (i_end + i_start)//2 sort(my_list, i_start, i_mid) sort(my_list, i_mid, i_end) merge(my_list, i_start, i_mid, i_end)
true
f562f6c622294326e268526cf025facef0f0ac56
LukeDaigneault/Python-Beginners-Course
/data_structures/list_unpacking.py
226
4.125
4
numbers = [1, 2, 3, 4, 4, 4, 4] first, second, *other, last = numbers print(first, last) print(other) first = numbers[0] second = numbers[1] third = numbers[2] def multiply(*numbers): print(numbers) multiply(1, 2, 3)
true
11a68c2f24569437d8dab232ac45d43690211cc7
sm1rnoff/dot_py
/Python OOP/5_polymorphism/lab/3_shapes.py
972
4.125
4
from math import pi from abc import ABC, abstractmethod class Shape(ABC): def __str__(self): return f'Area: {self.calculate_area()}, Perimerter: {self.calculate_perimeter()}' @abstractmethod def calculate_area(self): pass @abstractmethod def calculate_perimeter(self): pass class Circle(Shape): def __init__(self, radius): self.__radius = radius def calculate_area(self): return self.__radius ** 2 * pi def calculate_perimeter(self): return 2 * self.__radius * pi class Rectangle(Shape): def __init__(self, height, width): self.__height = height self.__width = width def calculate_area(self): return self.__height * self.__width def calculate_perimeter(self): return 2 * (self.__height + self.__width) sh = [ # Shape(), Circle(5), Rectangle(2, 3) ] def print_shape(s: Shape): print(s) [print_shape(s) for s in sh]
false
d1b7c856a89422650de474439680daa5376d27ad
sterroso/DCP-2021-03-10
/main.py
872
4.15625
4
''' This problem was recently asked by Google. Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? ''' from typing import List def is_the_sum_of_two(k: int, list_of_numbers: List[int]) -> bool: # The list of numbers **must** have, at least, two elements. if len(list_of_numbers) <= 1: return False for i in range(len(list_of_numbers) - 1): for j in range(i + 1, len(list_of_numbers)): if list_of_numbers[i] + list_of_numbers[j] == k: return True return False if __name__ == "__main__": k = 17 l = list([10, 15, 3, 7]) print('Is {} the sum of two in {}?'.format(k, l)) print('{}'.format(is_the_sum_of_two(k, l)))
true
a511590bad4987e0ba5d8190b5d43f2bae4ce368
khalillakhdhar/chaines_python
/chaine.py
1,158
4.375
4
s = "hey python! c'est quoi une chaine?" print("longueur est s = %d" % len(s)) print("la premiere occurence de c = %d" % s.index("c")) print("c se répéte %d fois" % s.count("c")) print("Les cinques premier caractéres sont '%s'" % s[:5]) # Commence de 5 print("The les cinque prochain sont '%s'" % s[5:10]) # 5 à 10 print("The le treizième caractére est '%s'" % s[12]) # seulement 12 #print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing) print("les cinqs dernier sont '%s'" % s[-5:]) # 5th-from-last to end # Convert everything to uppercase print("La chaine majuscule devient: %s" % s.upper()) # Convert everything to lowercase print("La chaine miniscule devient: %s" % s.lower()) # Check how a string starts if s.startswith("Str"): print("phrase commence par 'Str'. Good!") else: print("phrase ne commence pas par 'Str'!") # Check how a string ends if s.endswith("chaine?"): print("la phrase finit par 'chaine!'. Good!") # Split the string into three separate strings, # each containing only a word print("chaque mot sans espace: %s" % s.split(" ")) #convert first letter into capital print(s.capitalize())
false
a2bdfc3f4a895c6ff6fc414d74d3b8e3bb4673c8
IrmaGC/Mision-04
/Triangulos.py
1,326
4.125
4
#Irma Gómez Carmona, A01747743 #Determinar segun las medidas si se trata de un triangulo, y si lo es, definir que tipo de triangulo es def determinarSiEsTriangulo(lado1, lado2, lado3): #Es un tringulo si la suma de dos de sus lados es mayor a la del tercero if lado1+lado2>lado3 and lado1+lado3>lado2: return True return False def determinarQueTrianguloEs (lado1,lado2,lado3):#Compara sus lados para determinar que tipo de triangulo es if lado1==lado2 and lado1==lado3: tipo="Equilatero" elif lado1==lado2 or lado1==lado2 or lado2==lado3: tipo="Isosceles" elif (lado1**2+lado2**2)**0.5==lado3 or (lado2**2+lado3**2)**0.5==lado1 or (lado1**2+lado3**2)**0.5==lado2: tipo="Rectangulo" else: tipo="Escaleno" return tipo def main (): #Obtener valores, llamar a las otras funciones y mostrar resultados lado1 = int(input("Medida del lado 1:")) lado2 = int(input("Medida del lado 2:")) lado3 = int(input("Medida del lado 3:")) valido= determinarSiEsTriangulo(lado1,lado2,lado3) if valido==True: tipo= determinarQueTrianguloEs(lado1,lado2,lado3) print("Tipo de triánngulo: ", tipo) else: print("Estos lados no corresponden a un triangulo") main ()
false
d06c756eee4988e827bf8501015f3fb461fd1534
CYZZ/LearningPython-100day
/Day01-15/code/Day02/strings.py
630
4.125
4
""" 字符串string的常用操作符 2019-06-17 """ str1 = 'hello,world!' print('字符串的长度是:',len(str1)) print('单词首字母大写:',str1.title()) print('字符串转大写:',str1.upper()) print('字符串是不是大写:',str1.isupper()) print('字符串是不是以hello开头:',str1.startswith('hello')) print('字符串是不是以hello结尾:',str1.endswith('hello')) print('字符串是不是以感叹号!开头:',str1.startswith('!')) print('字符串是不是以感叹号!结尾:',str1.endswith('!')) str2 = '- \u9a86\u660c' str3 = str1.title() + ' ' + str2.lower() print('str3 = ',str3)
false
5084fb16f95eecaec7fa41c8be0f742282403916
ArgirisD/PythonBasics1
/Exercise38.py
216
4.15625
4
x = int(input("Please provide a number:")) y = int(input("Please provide a second number:")) def multiplication(x,y): f = (x+y)**2 return f print("({} + {})^2 = {}".format(x,y,multiplication(x,y)))
false
4b45048796ca3ecd4aa596c4d09a80a5781c760f
ArgirisD/PythonBasics1
/Exercise12.py
561
4.28125
4
import calendar year = int(input("Enter the year for which you want to see the month:")) month = int(input("Enter the month you want to see:")) print(calendar.month(year, month)) day = int(input("Enter the day you want to see:")) dayname = calendar.weekday(year, month, day) if dayname == 0: print("Monday") elif dayname == 1: print("Tuesday") elif dayname == 2: print("Wednesday") elif dayname == 3: print("Thursday") elif dayname == 4: print("Friday") elif dayname == 5: print("Saturday") else: print("Sunday")
true