blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a9cfa9463756a988acde76df57da14596c800169
DebbyMurphy/project2_python-exercises
/wk4-exercises_lists/python-lists_q3-append.py
487
4.5625
5
# Q3) Ask the user for three names, append them to a list, then print the list. # Input # Izzy # Archie # Boston # Output # ["Izzy", "archie", "Boston"] nameslist = [] firstname = input("Hi, what's your first name?! ") middlename = input(f"Cool, hey {firstname} what about your middle name? ") lastname = input(f"Thanks. And finally - please enter your last name: ") nameslist.insert(0, firstname) nameslist.insert(1, middlename) nameslist.insert(2, lastname) print(nameslist)
true
83e386a5c63cbd9696b0fa7ce04ca9ac248b6555
prabhakarchandra/python-samples
/Question4.py
694
4.28125
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 25 11:08:55 2019 @author: v072306 """ # Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. # Suppose the following input is supplied to the program: # 34,67,55,33,12,98 # Then, the output should be: # ['34', '67', '55', '33', '12', '98'] # ('34', '67', '55', '33', '12', '98') # Hints: # In case of input data being supplied to the question, it should be assumed to be a console input. # tuple() method can convert list to tuple k=input("Enter the list of values: ") y = list(map(int, k.split(","))) t = tuple(y) print(y) print(t)
true
aadcbc2aca1d9f10503bcac93c3e4468b0f39d7c
Daletxt/xiaojiayu
/40classBIF.issubclass.isinstance.hasattr.setattr.getattr.delattr.property.py
2,804
4.3125
4
print('hello,world') #类和对象一些相关的BIF #issubclass(class,classinfo)检查class是否是classinfo的子类,非严格性, #1.一个类被认为是其自身的子类 #2.classinfo可以是类对象组成的元组,只要class是其中任何一个候选类的子类,则返回True class A: pass class B(A): pass print("B是A的子类吗",issubclass(B,A)) print("B是B的子类吗",issubclass(B,B)) print("A是B的子类吗",issubclass(A,B)) print("A是元组(A,B)的子类吗",issubclass(A,(A,B))) print("B是object的子类吗",issubclass(B,object))#object是所有类的一个基类 class C: pass print("B是C的子类吗",issubclass(B,C)) print() #isinstance(object,classinfo)检查一个实例对象object是否属于类classinfo #1.如果第一个参数不是对象,则永远返回False #2.如果参数不是类或者由类对象组成的元组,会抛出一个TypeError异常 b1 = B() print("b1属于B类吗",isinstance(b1,B)) print("b1属于A类吗",isinstance(b1,A)) print("b1属于C类吗",isinstance(b1,C)) print("b1属于元组(A,B,C)吗",isinstance(b1,(A,B,C))) print() #hasattr(object,name)检查一个对象object是是否有指定的‘name’属性(属性名需要“name”) class C: def __init__(self,x=0): self.x = x c1 = C() print("x属性是否在实例化对象d1中",hasattr(c1,'x')) #print("x属性是否在实例化对象d1中",hasattr(c1,x)) #NameError: name 'x' is not defined print("y属性是否在实例化对象d1中",hasattr(c1,'y')) print() #getattr(object,name[,default])返回对象object指定的属性‘name’值 print('实例化对象c1中x属性的值为:',getattr(c1,'x')) #print('实例化对象c1中y属性的值为:',getattr(c1,'y')) #AttributeError: 'C' object has no attribute 'y' print('实例化对象c1中y属性的值为:',getattr(c1,'y','您所访问的属性不存在...')) print() #setattr(object,name,value)设置对象object中指定属性‘name’的值,不存在则创建新的 setattr(c1,'y',['FishC',7]) print('实例化对象c1中y属性的值为:',getattr(c1,'y','您所访问的属性不存在...')) #delattr(object,name)删除对象object中指定的属性‘name’,不存在则抛出异常 delattr(c1,'y') #delattr(c1,'y') #AttributeError: y try: delattr(c1,'y') except AttributeError: print('删除实例化对象的属性y异常') #property(fget=None,fset=None,fdel=None,doc=None)通过属性设置属性 class C: def __init__(self,size=10): self.size = size def getSize(self): return self.size def setSize(self,value): self.size = value def delSize(self): del self.size x = property(getSize,setSize,delSize) c1 = C() print(c1.getSize()) print(c1.x) c1.x = 18 print(c1.x) print(c1.size) print(c1.getSize()) del c1.x print(c1.size)
false
43ebbeacae18cb60f4de3c986033597e2d815dda
shiqing881215/Python
/object&database/inheritence.py
817
4.28125
4
class PartyAnimal : x = 0 name = "" # This is the constructor def __init__(self, name) : self.name = name print "I'm constructing", self.name # method, each python class at least has one variable called self def party(self): self.x = self.x+1 print self.name, " says ", self.x # This is the destructor def __del__(self): print "I'm destructed", self.name # This is how to do the "extends" class FootballFan(PartyAnimal) : points = 0 def touchdown(self) : self.points = self.points + 7 self.party() print self.name, "Points ", self.points s = PartyAnimal("Sally") s.party() j = FootballFan("Jim") j.party() j.touchdown() ''' The result is I'm constructing Sally Sally says 1 I'm constructing Jim Jim says 1 Jim says 2 Jim Points 7 I'm destructed Jim I'm destructed Sally '''
false
4fbb26d010002e088acd3a0297ac9b446961cb30
Manendar/branch-new-data
/trial.py
253
4.125
4
# this function counts vowels in a given string def vowels(s): count=0 vowel = "aeiouAEIOU" for i in s: if i in vowel: count +=1 return count if __name__ == '__main__': print(vowels("aeiou")) print(__name__)
false
1762ec6a2b9a905bd7569d47ef8ad75bfca0fce3
zhxiaozhi/untitled9
/day03/12-赋值运算符的特殊场景.py
700
4.1875
4
# 等号连接的变量可以传递赋值 a = b = c = d = 'hello' print(a, b, c, d) # x = 'yes' = y = z 错误,赋值运算时从右到左。y不能赋值‘yes’ m, n = 3, 5 # 拆包,(3,5)是一个元组 print(m, n) x = 'hello', 'good', 'yes' print(x) # ('hello', 'good', 'yes') # 拆包时,变量的个数和值的个数不一致,会报错 # y,z = 1, 2, 3, 4, 5 # print(y,z) # o, p, q = 4, 2 # print(o, p, q) # *表示可变长度,p是可以变的 # o, *p, q = 1, 2, 3, 4, 5, 6 # print(o, p, q) # 1 [2, 3, 4, 5] 6 # o是可以变的 # *o, p, q = 1, 2, 3, 4, 5, 6 # print(o, p, q) # [1, 2, 3, 4] 5 6 o, p, *q = 1, 2, 3, 4, 5, 6 print(o, p, q) # 1 2 [3, 4, 5, 6]
false
f23e9b415175dffbbe1fb1cae40438cc6612d496
priyam009/Python-Codecademy
/Text Manipulation Examples/x_length_words.py
521
4.125
4
#Create a function called x_length_words that takes a string named sentence and an integer named x as parameters. This function should return True if every word in sentence has a length greater than or equal to x. def x_length_words(sentence, x): sentence = sentence.split() count = 0 for word in sentence: for letter in word: count += 1 if count < x: return False break count = 0 return True print(x_length_words("i like apples", 2)) print(x_length_words("he likes apples", 2))
true
27b08fd75ad185244ddb9a44453d83326fe8d88a
priyam009/Python-Codecademy
/Loops Examples/exponents.py
347
4.375
4
#Create a function named exponents that takes two lists as parameters named bases and powers. Return a new list containing every number in bases raised to every number in powers. def exponents(base, powers): new_lst= [] for i in base: for j in powers: new_lst.append(i ** j) return new_lst print(exponents([2, 3, 4], [1, 2, 3]))
true
9275738c76e060d910ef17a4644f8c21b89ce90f
priyam009/Python-Codecademy
/Loops Examples/max_num.py
276
4.1875
4
#Create a function named max_num that takes a list of numbers named nums as a parameter. The function should return the largest number in nums def max_num(nums): max = nums[0] for i in nums: if i >max: max = i return max print(max_num([50, -10, 0, 75, 20]))
true
81452be56123ee27e4fbd3a1aa371fe39652a9b4
Debashish-hub/Python
/MyCaptain1.py
561
4.40625
4
# Displaying fibonacci series upto n terms n = int(input("Enter the number of terms? ")) # Initialisation of 2 terms n1, n2 = 0, 1 count = 0 # Checking for validation and printing the fibonacci series if n <= 0: print("Please enter a positive integer!") elif n == 1: print("Fibonacci series upto ", n, " terms :") print(n1) else: print("Fibonacci series upto ", n, " terms :") while count < n: print(n1) nth = n1 + n2 # updating values n1 = n2 n2 = nth count += 1
false
4f906ffbb833dbbfa4a806c8f458fde74e98e3f3
tyermercado/python-hacker-rank
/divisible_sum_pair.py
1,857
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 12 22:32:30 2019 @author: bijayamanandhar """ #Github repo: #https://www.hackerrank.com/challenges/divisible-sum-pairs/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign """ You are given an array of integers, and a positive integer. Find and print the number of pairs where and + is divisible by . For example, and . Our three pairs meeting the criteria are and . Function Description Complete the divisibleSumPairs function in the editor below. It should return the integer count of pairs meeting the criteria. divisibleSumPairs has the following parameter(s): n: the integer length of array ar: an array of integers k: the integer to divide the pair sum by Input Format The first line contains space-separated integers, and . The second line contains space-separated integers describing the values of . Constraints Output Format Print the number of pairs where and + is evenly divisible by . Sample Input 6 3 1 3 2 6 1 2 Sample Output 5 Explanation Here are the valid pairs when : """ #!/bin/python3 import math import os import random import re import sys # Complete the divisibleSumPairs function below. def divisibleSumPairs(n, k, ar): #collects number of pairs res = 0 #iterates thru the length - 1 for i in range(n-1): #iterates from i+1 to length, searches for the pairs for j in range(i+1, n): #when sum equals k if (ar[i] + ar[j]) % k == 0: #adds 1 to res res += 1 return res # Test Cases: n = 5 k = 3 ar = [1,2,3,4,1,3,0] print(divisibleSumPairs(n, k, ar) == 3) # True ([ar[0]+ar[1]] = 3)\\//([ar[1]+ar[3] = 3)\\//([ar[1]+ar[4] = 3)
true
a43edd3f97e3c2229fbf824591fc5a5e0a1894b8
KickItAndCode/Algorithms
/DynamicProgramming/UniquePaths.py
1,320
4.34375
4
# 62. Unique Paths # robot is located at the top-left corner of a m x n grid(marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid(marked 'Finish' in the diagram below). # How many possible unique paths are there? # Above is a 7 x 3 grid. How many possible unique paths are there? # Note: m and n will be at most 100. # Example 1: # Input: m = 3, n = 2 # Output: 3 # Explanation: # From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: # 1. Right -> Right -> Down # 2. Right -> Down -> Right # 3. Down -> Right -> Right # Example 2: # Input: m = 7, n = 3 # Output: 28 # 1 1 1 # 1 0 0 def uniquePaths(m, n): # initialize a all zero array dp = [[0 for x in range(n)] for x in range(m)] # set top row at 1's as there is only one direction it can go for i in range(m): dp[i][0] = 1 # set left row vertically as 1 as it has only one direction it can go for i in range(n): dp[0][i] = 1 # add the row above it and the side to calculate for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[m-1][n-1] print(uniquePaths(3, 2)) print(uniquePaths(7, 3))
true
86fd55a2d7264324ad169204d4c28024698d59f8
KickItAndCode/Algorithms
/Graphs, BFS, DFS/2D Board BFS/SurroundedRegions.py
2,413
4.125
4
# 130. Surrounded Regions # Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. # A region is captured by flipping all 'O's into 'X's in that surrounded region. # Example: # X X X X # X O O X # X X O X # X O X X # After running your function, the board should be: # X X X X # X X X X # X X X X # X O X X # Explanation: # Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically. # "Save Every O region " from collections import deque def solve(board): queue = deque([]) # gets every value that is on the edge rows along the boundary for r in range(len(board)): for c in range(len(board[0])): if (r in [0, len(board)-1] or c in [0, len(board[0])-1]) and board[r][c] == "O": queue.append((r, c)) while queue: r, c = queue.popleft() if 0 <= r < len(board) and 0 <= c < len(board[0]) and board[r][c] == "O": board[r][c] = "D" queue.append((r-1, c)) queue.append((r+1, c)) queue.append((r, c-1)) queue.append((r, c+1)) for r in range(len(board)): for c in range(len(board[0])): if board[r][c] == "O": board[r][c] = "X" elif board[r][c] == "D": board[r][c] = "O" def solve1(board): if not any(board): return m, n = len(board), len(board[0]) # gets every value that is on the edge rows along the boundary save = [(i, j) for k in range(max(m, n)) for (i, j) in ((0, k), (m-1, k), (k, 0), (k, n-1))] while save: i, j = save.pop() if 0 <= i < m and 0 <= j < n and board[i][j] == 'O': board[i][j] = 'S' save.extend([(i-1, j), (i+1, j), (i, j-1), (i, j+1)]) # Phase 2: Change every 'S' on the board to 'O' and everything else to 'X'. board[:] = [['X' if c != 'S' else "O" for c in row] for row in board] return board print(solve( [ ["X", "X", "X", "X"], ["O", "O", "O", "X"], ["X", "X", "O", "X"], ["X", "O", "X", "X"] ] )) # result # X X X X # X X X X # X X X X # X O X X
true
70ee7a473dfef293a283af568731e5f637a04d21
KickItAndCode/Algorithms
/Recursion/TowerOfHanoi.py
1,906
4.15625
4
# Program for Tower of Hanoi # Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: # 1) Only one disk can be moved at a time. # 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. # 3) No disk may be placed on top of a smaller disk. # Approach : # Take an example for 2 disks : # Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'. # Step 1 : Shift first disk from 'A' to 'B'. # Step 2 : Shift second disk from 'A' to 'C'. # Step 3 : Shift first disk from 'B' to 'C'. # The pattern here is : # Shift 'n-1' disks from 'A' to 'B'. # Shift last disk from 'A' to 'C'. # Shift 'n-1' disks from 'B' to 'C'. # Image illustration for 3 disks : NUMPEGS = 3 # def computeTowerHanoi(numrings): # def computeTowerHanoiSteps(numrings, src, dst, tmp): # if numrings > 0: # computeTowerHanoiSteps(numrings - 1, src, tmp, dst) # pegs[dst].append(pegs[src].pop()) # results.append([src, dst]) # computeTowerHanoiSteps(numrings - 1, tmp, dst, src) # results = [] # pegs = [list(reversed(range(1, numrings, +1)))] + [[] # for _ in range(1, numrings)] # computeTowerHanoiSteps(numrings, 0, 1, 2) # return results # computeTowerHanoi(3) def TowerOfHanoi(n, from_rod, to_rod, aux_rod): if n == 1: print("Move disk 1 from rod", from_rod, "to rod", to_rod) return TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) print("Move disk", n, "from rod", from_rod, "to rod", to_rod) TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) # Driver code n = 4 TowerOfHanoi(n, 'A', 'C', 'B') # A, C, B are the name of rods
true
4233d6a91fe0b4d2a088cc13bf11a5cc1a0cccee
KickItAndCode/Algorithms
/ArraysListSets/GenerateParentheses.py
2,883
4.125
4
# 22. Generate Parentheses # Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. # For example, given n = 3, a solution set is: # [ # "((()))", # "(()())", # "(())()", # "()(())", # "()()()" # ] # Approach 2 (Directed Backtracking) # The 3 Keys To Backtracking # Our Choice: # Whether we place a left or right paren at a certain decision point in our recursion. # Our Constraints: # We can't place a right paren unless we have left parens to match against. # Our Goal: # Place all k left and all k right parens. # The Key # At each point of constructing the string of length 2k we make a choice. # We can place a "(" and recurse or we can place a ")" and recurse. # But we can't just do that placement, we need 2 critical pieces of information. # The amount of left parens left to place. # The amount of right parens left to place. # We have 2 critical rules at each placement step. # We can place a left parentheses if we have more than 0 left to place. # We can only place a right parentheses if there are left parentheses that we can match against. # We know this is the case when we have less left parentheses to place than right parentheses to place. # Once we establish these constraints on our branching we know that when we have 0 of both parens to place that we are done, we have an answer in our base case. def generateParenthesis(n): def generate(res, left, right, curr): if left == 0 and right == 0: res.append(curr) # At each frame of the recursion we have 2 things we can do: # 1.) Insert a left parenthesis # 2.) Insert a right parenthesis # These represent all of the possibilities of paths we can take from this # respective call. The path that we can take all depends on the state coming # into this call. # Can we insert a left parenthesis? Only if we have lefts remaining to insert # at this point in the recursion if left > 0: generate(res, left - 1, right, curr + "(") # Can we insert a right parenthesis? Only if the number of left parens needed # is less than then number of right parens needed. # This means that there are open left parenthesis to close OTHERWISE WE CANNOT # USE A RIGHT TO CLOSE ANYTHING. We would lose balance. if left < right: generate(res, left, right - 1, curr + ")") # numLeftParensNeeded -> We did not use a left paren # numRightParensNeeded - 1 -> We used a right paren # parenStringInProgress + ")" -> We append a right paren to the string in progress # result -> Just pass the result list along for the next call to use res = [] generate(res, n, n, '') return res print(generateParenthesis(3))
true
3b4f9ea9c6d1257928b6ee539904746f5e7fa6b5
marc-haddad/cs50-psets
/pset6/credit/credit.py
2,388
4.125
4
# Marc Omar Haddad # CS50 - pset6: 'Credit' # September 4, 2019 from cs50 import get_string # This program uses Luhn's algorithm to check the validity and type of credit cards def main(): num = get_string("Number: ") # Repeatedly prompts user for valid numeric input while (num.isdigit() != True): num = get_string("Number: ") # Checks if string is the correct length and if the first 2 chars are valid if ( (len(num) != 13 and len(num) != 15 and len(num) != 16) or (num[0] + num[1] != ("34") and num[0] + num[1] != ("37") and num[0] + num[1] != ("51") and num[0] + num[1] != ("52") and num[0] + num[1] != ("53") and num[0] + num[1] != ("54") and num[0] + num[1] != ("55") and num[0] != ("4")) ): print('INVALID') # Checks the result of custom boolean function luhn() if luhn(num) == False: print('INVALID') return 1 # Passing all previous checks means the provided num is valid # Checks the 'type' of credit card else: if (num[0] == '3'): print('AMEX') elif (num[0] == '4'): print('VISA') else: print('MASTERCARD') return 0 # Boolean function that takes a numeric string as input and applies Luhn's algorithm for validity def luhn(stri): # Initializes the variable that will contain total sum add = 0 # Iterates over the string moving backwards starting from the before-last digit, skipping every other digit for i in range(-2, -(len(stri) + 1), -2): # Converts from char to int and multiplies by 2 x = int(stri[i]) * 2 # If result has 2 digits, add one individual digit to the other if x > 9: x = x % 10 + ((x - (x % 10)) / 10) add += x # If result has 1 digit, add it directly else: add += x # Iterates over the rest of the string backwards for i in range(-1, -(len(stri) + 1), -2): # Converts chars to ints x = int(stri[i]) # Adds digits as-is to total sum add += x # Checks to see if total sum is divisible by 10 (thus satisfying the conditions of Luhn's algorithm) if (add % 10 == 0): return True else: return False if __name__ == "__main__": main()
true
eba970f91a25c886fa95fd5f25f7bc42f214e0a7
dconn20/Random
/Random.py
243
4.21875
4
# program that prints out a random number # between 1 and 10 import random x = int (input("Enter number here: ")) y = int (input("Enter number here: ")) number = random.randint (x,y) print ("Here is a random number {}" .format (number))
false
14f03f53b53fee9132afebbc12ed6b72d75315e6
aaronjrenfroe/Algorithms
/fibonacci_memoize.py
465
4.125
4
# Returns the nth number in the fibonacci sequence def fib_memo(n, memo): if n == 0: return 0 elif memo[n] != None: return memo[n] elif n == 1 or n == 2: memo[n] = 1 else: memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo) return memo[n] # memo initialiseation cen be done differntly # but this is the simplest method that keeps fib_memo clean # inorder to understand what's going on. n = 0 memo = (n+1)*[None] print(fib_memo(n, memo))
true
c54d475ea800479f4cdf5b2a1f95e3e5efde9452
Frijke1978/LinuxAcademy
/Python 3 Scripting for System Administrators/The while Loop.py
2,207
4.6875
5
The while Loop The most basic type of loop that we have at our disposal is the while loop. This type of loop repeats itself based on a condition that we pass to it. Here’s the general structure of a while loop: while CONDITION: pass The CONDITION in this statement works the same way that it does for an if statement. When we demonstrated the if statement, we first tried it by simply passing in True as the condition. Let’s see when we try that same condition with a while loop: >>> while True: ... print("looping") ... looping looping looping looping That loop will continue forever, we’ve created an infinite loop. To stop the loop, press Ctrl-C. Infinite loops are one of the potential problems with while loops if we don’t use a condition that we can change from within the loop then it will continue forever if initially true. Here’s how we’ll normally approach using a while loop where we modify something about the condition on each iteration: >>> count = 1 >>> while count <= 4: ... print("looping") ... count += 1 ... looping looping looping looping >>> We can use other loops or conditions inside of our loops; we need only remember to indent four more spaces for each context. If in a nested context, we want to continue to the next iteration or stop the loop entirely. We also have access to the continue and break keywords: >>> count = 0 >>> while count < 10: ... if count % 2 == 0: ... count += 1 ... continue ... print(f"We're counting odd numbers: {count}") ... count += 1 ... We're counting odd numbers: 1 We're counting odd numbers: 3 We're counting odd numbers: 5 We're counting odd numbers: 7 We're counting odd numbers: 9 >>> In that example, we also show off how to “string interpolation” in Python 3 by prefixing a string literal with an f and then using curly braces to substitute in variables or expressions (in this case the count value). Here’s an example using the break statement: >>> count = 1 >>> while count < 10: ... if count % 2 == 0: ... break ... print(f"We're counting odd numbers: {count}") ... count += 1 ... We're counting odd numbers: 1
true
fdd668609fcd5bf054e8888d5da465a1a971089a
Frijke1978/LinuxAcademy
/Python 3 Scripting for System Administrators/Working with Environment Variables.py
1,809
4.21875
4
Working with Environment Variables By importing the os package, we’re able to access a lot of miscellaneous operating system level attributes and functions, not the least of which is the environ object. This object behaves like a dictionary, so we can use the subscript operation to read from it. Let’s create a simple script that will read a 'STAGE' environment variable and print out what stage we’re currently running in: ~/bin/running #!/usr/bin/env python3.6 import os stage = os.environ["STAGE"].upper() output = f"We're running in {stage}" if stage.startswith("PROD"): output = "DANGER!!! - " + output print(output) We can set the environment variable when we run the script to test the differences: $ STAGE=staging running We're running in STAGING $ STAGE=production running DANGER!!! - We're running in PRODUCTION What happens if the 'STAGE' environment variable isn’t set though? $ running Traceback (most recent call last): File "/home/user/bin/running", line 5, in stage = os.environ["STAGE"].upper() File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'STAGE' This potential KeyError is the biggest downfall of using os.environ, and the reason that we will usually use os.getenv. Handling A Missing Environment Variable If the 'STAGE' environment variable isn’t set, then we want to default to 'DEV', and we can do that by using the os.getenv function: ~/bin/running #!/usr/bin/env python3.6 import os stage = os.getenv("STAGE", "dev").upper() output = f"We're running in {stage}" if stage.startswith("PROD"): output = "DANGER!!! - " + output print(output) Now if we run our script without a 'STAGE' we won’t have an error: $ running We're running in DEV
true
e7c1e57d0061f37a815fa05ea988deef32bf1bc0
jeen-jos/PythonPrograms
/Code/test.py
709
4.375
4
# Follwoing code shows how to print msg = "Hello world" print(msg) print(msg.capitalize()) print(msg.split()) # Taking inputs from user name = input("enter your name : ") print("Hello ",name) # eval() converts entered text into number to evaluate expressions num= eval(input("Enter the number : ")) print(" The value is ",num*num) print("the value of 3+4 is ",3+4) print("5+6 is ",5+6," and 4+7 is ",4+7) #Optional Arguments of print() #------------------------------------- #sep - python insets space between arguments of print() print("the value of 3+4 is ",3+4,".",sep=' ') #end - keeps python print() from advancing automatically to next line print("hello friends",end=' ') print("Have a great day")
true
a9c7bb5f18b5b109b924e0bd5eb0bc2386e6d0eb
rajiarazz/task-2
/day2/day2.py
343
4.3125
4
#1 ) Consider i = 2, Write a program to convert i to float. i=2 print(float(i)) #2 )Consider x="Hello" and y="World" , then write a program to concatinate the strings to a single string and print the result. x="Hello " y="World" print(x+y) #3 ) Consider pi = 3.14 . print the value of pie and its type. pi=3.14 print(pi) type(pi)
true
944469b3af2436ce62b11e22ee43f8bf2a6c0e87
akarnoski/data-structures
/python/data_structures/binheap.py
1,845
4.125
4
"""Build a binary min heap object.""" from math import floor class BinaryHeap(object): """Create a Binary Heap object as a Min Heap.""" def __init__(self): """Initialize the heap list to be used by Binary Heap.""" self._heap_list = [] def push(self, val): """Add new value to heap list and run check heap method.""" self._heap_list.append(val) if len(self._heap_list) == 2: self._small_heap() self._check_heap() def _small_heap(self): heap = self._heap_list if heap[0] > heap[1]: heap[0], heap[1] = heap[1], heap[0] return heap def _check_heap(self): """Check all the children are less than their parents.""" heap = self._heap_list index = floor((len(heap) - 1) / 2) i = 0 while i < index: l = (2 * i) + 1 if heap[i] > heap[l]: heap[i], heap[l] = heap[l], heap[i] try: r = (2 * i) + 2 if heap[i] > heap[r]: heap[i], heap[r] = heap[r], heap[i] except IndexError: # pragma: no cover pass i += 1 return heap def pop(self): """Remove top value of heap and run check heap method.""" try: heap = self._heap_list index = len(heap) - 1 heap[0], heap[index] = heap[index], heap[0] self._heap_list.pop() if len(self._heap_list) == 2: self._small_heap() self._check_heap() return heap except IndexError: raise IndexError('Nothing available to pop') def _display(self): # pragma: no cover """Make it easier during testing.""" for item in self._heap_list: print(item)
false
a32fc4f194acd34c21ef5a5bcfcb3bf9f5d34bc1
akarnoski/data-structures
/python/data_structures/trie_tree.py
2,265
4.1875
4
"""Create a trie tree.""" class Node(object): """Build a node object.""" def __init__(self, val=None): """Constructor for the Node object.""" self.val = val self.parent = None self.children = {} class TrieTree(object): """Create a trie tree object.""" def __init__(self): """Constructor for the trie tree object.""" self.size = 0 self.root = Node('*') def insert(self, string): """Insert string into trie tree.""" curr = self.root string = string + '$' for letter in string: print(letter) if letter in curr.children: curr = curr.children[letter] new = False else: new_letter = Node(letter) new_letter.parent = curr curr.children[letter] = new_letter curr = new_letter new = True if new: self.size += 1 def size(self): """Return size of trie tree.""" return self.size def contains(self, string): """Return true if string is in trie.""" try: self._node_crawler(string) return True except KeyError: return False def _val_crawler(self, string): """Trie tree crawler helper function that returns values of the nodes to help me visualize while testing.""" values = [] curr = self.root values.append(curr.val) string = string + '$' try: for letter in string: curr = curr.children[letter] values.append(curr.val) except KeyError: raise KeyError('Word not in Trie Tree') return values def _node_crawler(self, string): """Trie tree crawler helper function that returns list of the nodes to help me visualize while testing.""" nodes = [] curr = self.root nodes.append(curr) string = string + '$' try: for letter in string: curr = curr.children[letter] nodes.append(curr) except KeyError: raise KeyError('Word not in Trie Tree') return nodes
true
0927de7b023d96a01db8047c1955aedfdcd2a9a1
hillarymonge/class-samples
/fancyremote.py
856
4.25
4
import turtle from Tkinter import * def circle(myTurtle): myTurtle.circle(50) # create the root Tkinter window and a Frame to go in it root = Tk() frame = Frame(root) # create our turtle shawn = turtle.Turtle() # make some simple but fwd = Button(frame, text='fwd', command=lambda: shawn.forward(50)) left = Button(frame, text='left', command=lambda: shawn.left(90)) right = Button(frame, text ='right', command=lambda: shawn.right(90)) penup = Button(frame, text ='penup', command=lambda:shawn.penup()) pendown = Button(frame, text ='pendown', command=lambda:shawn.pendown()) makecircle = Button(frame, text='makecircle', command=lambda:shawn.circle(50)) # put it all together fwd.pack(side=LEFT) left.pack(side=LEFT) frame.pack() right.pack(side=LEFT) penup.pack(side=LEFT) pendown.pack(side=LEFT) makecircle.pack(side=LEFT) turtle.exitonclick()
true
2868818bbaaef980a57267f34e8cec8bd6574018
ShresthaRujal/python_basics
/strings.py
340
4.28125
4
#name = "rujal shrestha"; #print(name); #print(name[0]); #indexing #print(name[3:]) # prints all string after 3rd character #print(name.upper()) #print(name.lower()) #print(name.split(s)) #default is white space #print formatting print("Hello {}, your balance is {}.".format("Adam", 230.2346)) x = "Item One : {}".format("ÏNSERT ME!") print(x)
true
1f8975b5b315aa287404ef91c968a3039274215a
Denzaaaaal/python_crash_course
/Chapter_8/user_album.py
644
4.1875
4
def make_album(name, title, no_of_songs=None): if no_of_songs: album = { 'artist_name': name, 'album_title': title, 'number_of_songs': no_of_songs, } else: album = { 'artist_name': name, 'album_title': title, } return album while True: print ("\n(Enter 'quit' to end the program)") entered_name = input("What is the artist name: ") if entered_name == 'quit': break entered_album = input("What is the albums title: ") if entered_album == 'quit': break print (make_album(entered_name, entered_album))
true
bb1eef8f10a456d560abba511f81c169acacbd5f
Denzaaaaal/python_crash_course
/Chapter_6/cities.py
751
4.34375
4
cities = { 'london': { 'country': 'england', 'population': 8.98, 'fact': 'london is the smallest city in england' }, 'tokyo': { 'country': 'japan', 'population': 9.27, 'fact': 'tokyo for fromally known as "edo" in the 20th century', }, 'malmo': { 'country': 'sweden', 'population': 0.3, 'fact': 'malmo was originally Danish' }, } for city, detail in cities.items(): print (f"\nThis is the city of {city.title()}.") print (f"\tThis is located in the county of {detail['country'].title()}.") print (f"\tThis city has a population size of {detail['population']} Million.") print (f"\tAn interesting fact about the city is {detail['fact']}.")
false
ccc9a226774cc6527f7ffd0212f06c066eda6949
anya92/learning-python
/1.Basics/numbers_and_operators.py
542
4.21875
4
# Numeric types in Python: # - int # - float # - complex 1 # int 3.2 # float print(type(-1)) # <class 'int'> print(type(0.5)) # <class 'float'> # operator | name | example # + | addition | 1 + 2 # 3 # - | subtraction | 15 - 4 # 11 # * | multiplication | 3 * 2 # 6 # / | division | 15 / 3 # 5.0 (always returns a float) # % | modulus | 7 % 2 # 1 # ** | exponentiation | 2 ** 3 # 8 # // | floor division | 15 // 3 # 5 (returns int, always rounds down)
false
5523bdf0039a9d1b2c5a03e00aa8e3a48f6b73d3
udoyen/andela-homestead
/codecademy/advanced_topics/dictionary/sample.py
528
4.15625
4
movies = { "Monty Python and the Holy Grail": "Great", "Monty Python's Life of Brian": "Good", "Monty Python's Meaning of Life": "Okay" } for key in movies: print(key, movies[key]) print("===================================") for key, value in movies.items(): print([(key, value)], end=' ') # print("===================================") # # print(list(filter(lambda x: (movies[x], x), movies))) # # print("===================================") # # print([(key, value) for key, value in movies.items()])
true
ecb27c7716d22c480ac6dc14aca69b6fd25c9d5a
Sombat/Python-Stack
/python_stack/python/OOP/users_with_bank_accounts.py
2,220
4.25
4
# Assignment: Users with Bank Accounts # Objectives: # Practice writing classes with associations class BankAccount: def __init__(self, int_rate=.01, balance=0): self.interest_rate = int_rate self.account_balance = balance def deposit(self, amount): self.account_balance += amount return self def withdraw(self, amount): self.account_balance -= amount return self def display_account_info(self): print(f"Interest Rate: {self.interest_rate}, Balance: ${self.account_balance}") return self def yield_interest(self): print(f"Interest: {self.account_balance*self.interest_rate}") return self # Account1 = BankAccount() # Account1.deposit(100) .deposit(200) .deposit(220) .withdraw(20) .yield_interest() .display_account_info() # Account2 = BankAccount() # Account2.deposit(51) .deposit(49) .withdraw(1) .withdraw(1) .withdraw(1) .withdraw(1) .yield_interest() .display_account_info() class User: def __init__(self, username, email_address): self.name = username self.email = email_address self.account = BankAccount(balance=0, int_rate=0.02) def make_deposit(self, amount): self.account.deposit(amount) return self def make_withdrawal(self, amount): self.account.withdraw(amount) return self def display_user_balance(self): print(f"User: {self.name}, Balance: ${self.account.account_balance}") return self def transfer_money(self, other_user, amount): self.account.account_balance -= amount other_user.account.account_balance += amount return self Sombat1 = User('sombat_1','sombat1@gmail.com') Sombat1.make_deposit(100) .make_deposit(200) .make_deposit(220) .make_withdrawal(20) .display_user_balance() Sombat2 = User('sombat_2','sombat2@gmail.com') Sombat2.make_deposit(51) .make_deposit(49) .make_withdrawal(1) .make_withdrawal(1) .display_user_balance() Sombat3 = User('sombat_3','sombat3@gmail.com') Sombat3.make_deposit(1) .make_deposit(1) .make_deposit(1) .make_withdrawal(3) .display_user_balance() Sombat1.transfer_money(Sombat3, 12) .display_user_balance() Sombat3.display_user_balance()
false
0390536aadf4e563e3e8de60fc26b0ea5fec6cae
loumatheu/ExerciciosdePython
/Mundo 1/Exercicio27.py
758
4.1875
4
#Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro nome e o último nome separadamente. #ex: Ana Maria de Souza # primeiro = Ana # último = Souza cores = {'azul':'\033[1;34m','verde':'\033[1;32m','semestilo':'\033[m', 'vermelho':'\033[1;31m', 'lilas':'\033[1;35m', 'amarelo':'\033[1;33m', 'verdepiscina':'\033[1;36m'} print(f"""{cores['azul']}==================================================================== CHALLENGE 27 ===================================================================={cores['semestilo']}""") nome = input('Qual o seu nome? ').strip() lista = nome.split() print(f'Prazer em conhecê-la(o)! \nO seu primeiro nome é {lista[0]} e o seu último nome é {lista[-1]}.')
false
99edaf310f340ee8612570e49f4945e8c3092a80
loumatheu/ExerciciosdePython
/Mundo 1/Exercicio22.py
1,015
4.40625
4
#Challenge 22 - Crie um programa que leia o nome completo de uma pessoa e mostre: #•O nome com todas as letras maiúsculas; #•O nome com todas as letras minúsculas; #•Quantas letras ao todo (sem considerar espaços); #Quantas letras tem o primeiro nome; cores = {'azul':'\033[1;34m','verde':'\033[1;32m','semestilo':'\033[m', 'vermelho':'\033[1;31m', 'lilas':'\033[1;35m', 'amarelo':'\033[1;33m', 'verdepiscina':'\033[1;36m'} print(f"""{cores['azul']}==================================================================== CHALLENGE 22 ===================================================================={cores['semestilo']}""") nome = str(input('Qual o seu nome completo? ')).strip() print(f'Nome com todas as letras maiúsculas:{nome.upper()}') print(f'Nome com letras minúsculas:{nome.lower()}') print(f'Quantidade de letras que o nome possue:{len(nome.replace(" ", ""))} ') firstname = nome.split() print(f'Quantidade de letras do primeiro nome:{len(firstname[0])}')
false
e7b028c64ca4fb48618d9a41eea2d80b30e62495
ThomasBriggs/python-examples
/Calculator/Calculator.py
287
4.28125
4
def calc(num, num2, operator): if operator == "+": print (num + num2) elif operator == "-": print (num - num2) elif operator == "*": print (num * num2) elif operator == "/": print (num / num2) else: print ("Invalid operator")
false
42db31f4a097ff0c8b38af894441bd4ffe75aa8f
jovyn/100-plus-Python-challenges
/100-exercises/ex16.py
442
4.25
4
''' Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1,2,3,4,5,6,7,8,9 Then, the output should be: 1,9,25,49,81 ''' num_lst = input("Enter a sequence of nos. comma separated: ") num_lst = num_lst.split(",") new_lst = [ str(int(n)*int(n)) for n in num_lst if int(n) % 2 != 0 ] s = "," print(s.join(new_lst))
true
52bdee1e48b1e04565e350c5227db664729b1cf7
prashantravishshahi/pdsnd_github
/User_Input.py
2,512
4.375
4
#definition of input month function. def get_month(): '''Asks the user for a month and returns the specified month. Args: none. Returns: (tuple) Lower limit, upper limit of month for the bikeshare data. ''' months=['january','february','march','april','may','june'] while True: month =input('\nWhich month of year? Choose january, february, march, april, may or june\n') month=month.lower() if(month in months): break print("\nI'm sorry, The month you have entered is incorrect. Please try again.") return month #definition of input day function. def get_day(): '''Asks the user for a day and returns the specified day. Args: none. Returns: (tuple) Lower limit, upper limit of date for the bikeshare data. ''' days=['sunday','monday','tuesday','wednesday','thursday','friday','saturday'] while True: day =input('\nWhich day of week? Choose sunday, monday, tuesday, wednesday, thursday, friday or saturday\n') day=day.lower() if(day in days): break print("\nI'm sorry, The month you have entered is incorrect. Please try again.") return day #definition of filters function def get_filters(): print('Hello! There Let\'s explore some US bikeshare data!') # get user input for city (chicago, New York City, Washingon). citys=['chi','new','was'] while True: city =input('\nPlease choose one of the cities (chicago, new york city, washington)\n You can provide intial 3 letters:- ') city=city.lower() city = city[:3] if(city in citys): break print("\nI'm sorry, The City you have entered is incorrect. Please try once more.") # get user input for filters (Month, Day, Both or not at all) while True: filters=['m','d','b','n'] filter =input('\nDo you wish to filter using\m:Month\nd:Day\nb:Both\nn:No filters\nType m, d, b, or n\n') if(filter in filters): break if(filter=='m'): # get filter criteria of month from user month=get_month() day='all' elif(filter=='d'): # get filter criteria of day from user day=get_day() month='all' elif(filter=='b'): # get filter criteria of month and day from user month=get_month() day=get_day() elif(filter=='n'): day='all' month='all' print('-'*100) return city, month, day
true
ce981daae2eeda0038941778658b09ced578538b
kelv-yap/sp_dsai_python
/ca3_prac1_tasks/section_2/sec2_task4_submission.py
780
4.3125
4
number_of_months = 6 title = "Calculate the average of your last " + str(number_of_months) + "-months electricity bill" print("*" * len(title)) print(title) print("*" * len(title)) print() bills = [] bill_number = 1 while bill_number <= number_of_months: try: input_bill = float(input("Enter Bill #{}: ".format(bill_number))) bills.append(input_bill) bill_number += 1 except ValueError: print("Please enter a numeric value") print("Your electricity bills for the past " + str(number_of_months) + " months are:") bill_str_list = [] for bill in bills: bill_str_list.append("$" + str(bill)) print(*bill_str_list, sep=", ") average = sum(bills) / number_of_months print("The average of your electricity bill is {:.2f}".format(average))
true
e3ac44b37f2f78dac95229051386a20881b61009
Afraysse/practice_problems
/missing_num.py
1,173
4.125
4
""" SOLUTION 1: Simple Solution - O(N) keep track of what you've seen in a seperate list. """ def find_missing_num(nums, max_num): # find what number is missing from the list and return it # there's a way of solving in O(n), but can also solve in O(log N) # list may be in any order seen = [False] * max_num for n in nums: seen[n - 1] = True # the false value is the one not yet seen return seen.index(False) + 1 # SOLUTION RUNTIME: O(N) and requires additional storage -- not ideal """ SOLUTION 2: Sorting Solution - O(N log N) Sort the numbers first, then scan thme to see which one missing. """ def misisng_num(nums, max_num): nums.append(max_num + 1) # adds one larger than the max nums.sort() # sorts list to make more iterable last = 0 for i in nums: if i != last + 1: return last + 1 last += 1 raise Exception("None are missing!") """ SOLUTION 3: add the numbers and subtract from expected sum. """ def missing_num(nums, max_num): expected = sum(range(max_num + 1)) return expected - sum(nums) # will return the missing number
true
355ee501441d3fea748bee9e288d2466fba17afb
alexweee/learn-homework-2_my
/my_date_and_time.py
1,490
4.15625
4
from datetime import datetime, date, timedelta import datedelta """ Домашнее задание №2 Дата и время * Напечатайте в консоль даты: вчера, сегодня, месяц назад * Превратите строку "01/01/17 12:10:03.234567" в объект datetime """ def split_myday(day): #day_split = str(day).split() #yesterday_final = day.date() yesterday_parse = day.strftime('%d.%m.%Y') return yesterday_parse def print_days(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ today = datetime.now() delta = timedelta(days=1) yesterday = today - delta delta_month = datedelta.datedelta(months = 1) last_month = today - delta_month print(split_myday(yesterday)) print(split_myday(today)) print(split_myday(last_month)) def str_2_datetime(string): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ #string_final = string[:-7] date_dt = datetime.strptime(string, '%m/%d/%y %H:%M:%S.%f') return date_dt, type(date_dt) if __name__ == "__main__": print_days() d, t = str_2_datetime("01/01/17 12:10:03.234567") print(d,t)
false
e1771a8446c03835dda14e0f77a779a5c8451ae2
LPisano721/color_picker
/colorpicker.py
1,767
4.21875
4
""" Program: colorpicker.py Author: Luigi Pisano 10/14/20 example from page 287-288 Simple python GUI based program that showcases the color chooser widget """ from breezypythongui import EasyFrame import tkinter.colorchooser class ColorPicker(EasyFrame): """Displays the result of picking a color.""" def __init__(self): """Sets up the window and the widgets.""" EasyFrame.__init__(self, title = "Color Chooser Demo") # Labels and output fields self.addLabel(text= "R", row = 0, column = 0) self.addLabel(text= "G", row = 1, column = 0) self.addLabel(text= "B", row = 2, column = 0) self.addLabel(text= "Color", row = 3, column = 0) self.r = self.addIntegerField(value = 0, row = 0, column = 1) self.g = self.addIntegerField(value = 0, row = 1, column = 1) self.b = self.addIntegerField(value = 0, row = 2, column = 1) self.hex = self.addTextField(text = "#000000", row = 3, column = 1) # Canvas widget with an initial black color background self.canvas = self.addCanvas(row = 0, column = 2, rowspan = 4, width = 50, background = "#000000") # Command button self.addButton(text = "Pick a Color", row = 4, column = 0, columnspan = 3, command = self.chooseColor) # Event handling method def chooseColor(self): """Pops up a color chooser from the OS and outputs the results.""" colorTuple = tkinter.colorchooser.askcolor() if not colorTuple[0]: return ((r, g, b), hexString) = colorTuple self.r.setNumber(int(r)) self.g.setNumber(int(g)) self.b.setNumber(int(b)) self.hex.setText(hexString) self.canvas["background"] = hexString def main(): """Instantiates and pops up the window>""" ColorPicker().mainloop() #Global call to the main function main()
true
2da51b497199b3dd5b65dcf8b63eb1443965f169
Harmonylm/Pandas-Challenge
/budget_v1.py
2,831
4.1875
4
# Budget: version 1 # Run with: python3 budget_v1.py import csv BUDGET_FILE="budget_data.csv" month_count = 0 # number of months read total_pl = 0 # total profit less all losses max_profit = 0 # largest profit increase seen max_profit_month = "" # month string with maximum profit increase max_loss = 0 # largest loss seen max_loss_month = "" # month string with maximum loss last_pl = 0 # last month profit/loss value current_pl = 0 # current month profit/loss value current_month = "" # current month name with open(BUDGET_FILE, "r", newline="") as f: reader = csv.reader(f) header = next(reader) # Make sure first word of header is "Date" if (header[0] != "Date"): print("ERROR: Unexpected data file format.") exit(1) # Read each line of file and perform calculations for row in reader: month_count += 1 # count months current_month = row[0] # this month name current_pl = int(row[1]) # this month profit/loss value # Debugging # print("month_count: ", month_count) # print("current_month: ", current_month) # print("current_pl: ", current_pl) # Check for an increase in profit. # Assume that we must have had a profit - the profit/loss value must be positive. # If we increased profit over last month save the value if largest seen so far. if (current_pl > 0): # had a profit, see if biggest so far if (current_pl > last_pl): # made more than last month size = current_pl - last_pl # how much did we grow over last month if (size > max_profit): max_profit = size max_profit_month = current_month # Check for greatest decrease in profit (decrease between two months). # Test is that profit/loss value is less than last month. # Record value if largest loss seen so far. if (current_pl < last_pl): # had a loss from last month size = current_pl - last_pl # how much of a loss since last month if (size < max_loss): max_loss = size # record the loss max_loss_month = current_month # Total all profits and subtract all losses to determine total revenue total_pl += current_pl # Update last month value for use in next loop last_pl = current_pl # Done - print results. print("Total Months: ", month_count) print("Total profit/loss: ", total_pl) print("Max increase in profit: ", max_profit) print("Max increase in profit month: ", max_profit_month) print("Max decrease in profit: ", max_loss) print("Max decrease in profit month: ", max_loss_month)
true
57b57fc2c25a5fed061a5bbd7d046d234469e6c3
max-web-developer/python-homework-1
/home.py
1,411
4.125
4
# total = int(input("введите количество квартир!: ")) # floors = int(input("введите количество этажей: ")) # apartment = int(input("номер кв вашего друга? ")) # p = (total/floors) # if total % floors > 0 or apartment <= 0 or total < apartment: # print("кол-во квартир не делится на кол-во этажей!") # if total % floors > 0 or apartment >=0 or total > apartment: # print('error!') # n = apartment // (p) or (p) # print("номер этажа вашего друга", n) total = int(input("введите количество квартир!: ")) floors = int(input("введите количество этажей: ")) apartment = int(input("номер кв вашего друга? ")) if apartment > 12: print('квартира на первом этаже!') if apartment < 12 : print('квартира на втором этаже!') if apartment > 24: print('квартира на третьем этаже!') if apartment > 36: print('квартира на 5 этаже') if apartment > 48: print('квартира на 6 этаже') if apartment > 60: print('квартира на 7 этаже') if apartment > 72: print('квартира на 8') if apartment > 80: print('квартира на 9') if apartment > 92: print('квартира на 10')
false
b107cf5cf5f3ab6c4c18fc32fecdc83ab128d6e7
varshini-07/python
/series.py
820
4.1875
4
#sum of series def factorial(num): fact=1 for i in range(1,num+1): fact=fact*i return fact num=int(input("enter the number: ")) sum=0 for i in range(1,num+1): sum=sum+(i/factorial(i)) print("the sum of series: ",sum) #sum of odd n series def factorial(num): fact=1 for i in range(1,num+1): fact=fact*i return fact num=int(input("enter the number: ")) sum=0 for i in range(1,num+1,2): sum=sum+(i/factorial(i)) print(i) print("sum of series:",sum) #sum of even n series def factorial(num): fact=1 for i in range(1,num+1): fact=fact*i return fact # Main num=int(input("enter the number: ")) sum=0 for i in range(2,num+1,2): sum=sum+((i**2)/factorial(i)) print(i) print("sum of series:",sum)
false
d137bb1a2509bd2ab60f39943673485b1e57489f
owili1/BOOTCAMP
/Hello world.py
210
4.125
4
print("Hello World\n"*10) #modifying hello world to prinT nmaes in reverse name1=(input("Enter name")) name2=(input("Enter name")) name3=(input("Enter name")) print("Hi "+name3+","+name2+","+name1+".")
false
db665202fccf5aef49ee276732e2050ffde1306f
thiamsantos/python-labs
/src/list_ends.py
416
4.1875
4
""" Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function. """ def get_list_start_end(initial_list): return [initial_list[0], initial_list[-1]] def main(): a = [5, 10, 15, 20, 25] print(get_list_start_end(a)) if __name__ == "__main__": main()
true
9993766594dea8835043ca71a5e058d4dc8796bf
thiamsantos/python-labs
/src/odd_even.py
525
4.40625
4
"""Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? """ def is_odd(number): return number % 2 == 1 def main(): number = int(input("Type a number: ")) number_is_odd = is_odd(number) if number_is_odd: print("{number} is odd!".format(number=number)) else: print("{number} is even!".format(number=number)) if __name__ == "__main__": main()
true
521a0426f89e4f184ebd5d6800804c8636b46a5e
DSLYL/Python_One_Hundred
/python对象/study_2.py
801
4.21875
4
# 测试私有属性 # 在变量或方法前面加上__(俩个下划线)的时候,就成为私有方法或私有变量, # 要想在类外访问它们,必须使用对象名._类名__变量名或方法名 #访问私有类变量时,是 类名._类名__变量名 #私有的 在类内是可以随意调用的 class Student: __Teacher=1 #私有类变量 def __init__(self, name, age): self.name = name self.__age = age # 私有属性 def __work(self): print("加油!") print(self.__age) e = Student("lui", 23) print(e.name) #下面2个是不对的 # print(e.__age) # print(e.__work()) print(e._Student__age) e._Student__work() print(Student._Student__Teacher) #下面这个打印出变量和方法在内存中的存储名字 print(dir(e))
false
de4a0592197953efe82a51cbaac639f53a238525
ahbaid/kids-code-camp
/lesson-002/Answers/cel2far.py
203
4.25
4
print ("\nCelsius to Farenheit:") print ("========================") t = input("Enter temperature in degrees celsius: ") t = int(t) f = (t*9/5.0)+32 print ("Temperature in Farenheit is: ",f) print ()
false
4fe16b312f72b931743d74d10805aa3446951398
Accitri/PythonModule1
/(4) 06.12.2017/Class work/dataVisualisationWithTurtle.py
2,854
4.1875
4
import turtle myTurtle = turtle.Turtle #defining a function for the basic setup of the turtle def setupTurtle(): myTurtleInsideFunction = turtle.Turtle() myTurtleInsideFunction.penup() myTurtleInsideFunction.setpos(-300, 0) myTurtleInsideFunction.pendown() myTurtleInsideFunction.color('red') myTurtleInsideFunction.pensize(2) myTurtleInsideFunction.speed(100) return myTurtleInsideFunction #calling the setupTurtle function and #store the result in a variable called myTurtle myTurtle = setupTurtle() #define the temperature list averageTemperatureList = [3, 5, 1, -4, -1, 4, 0, -5, -1, -3, 1, 4] numberOfRainyDays = [22, 19, 19, 18, 17, 18, 19, 19, 20, 21, 21, 20] #defining a function that draws a rectangle def drawTempGraphRectangle(): myTurtle.penup() myTurtle.setpos(-300, 0) myTurtle.pendown() for i in range(0, len(averageTemperatureList)): if (averageTemperatureList[i] >= 0): myTurtle.color('green') if (averageTemperatureList[i] < 0): myTurtle.color('red') myTurtle.forward(15) myTurtle.left(90) myTurtle.forward(averageTemperatureList[i] * 10) myTurtle.right(90) myTurtle.forward(15) myTurtle.right(90) myTurtle.forward(averageTemperatureList[i] * 10) myTurtle.left(90) #defining function that draws a rectangle def pulse(height, width): for i in range(0, len(averageTemperatureList)): if (averageTemperatureList[i] >= 0): myTurtle.color('green') if (averageTemperatureList[i] < 0): myTurtle.color('red') myTurtle.left(90) myTurtle.forward(height * 10) myTurtle.right(90) myTurtle.forward(width) myTurtle.right(90) myTurtle.forward(height * 10) myTurtle.left(90) myTurtle.forward(width) def drawGraphCircle(): for i in range(0, len(averageTemperatureList)): if (averageTemperatureList[i] >= 0): myTurtle.color('green') if (averageTemperatureList[i] < 0): myTurtle.color('red') myTurtle.circle(averageTemperatureList[i] * 10) def drawRainGraphRectangle(): myTurtle.penup() myTurtle.setpos(-300, 0) myTurtle.pendown() myTurtle.color('blue') for i in range(0, len(numberOfRainyDays)): myTurtle.forward(20) myTurtle.left(90) myTurtle.forward(numberOfRainyDays[i] * 10) myTurtle.right(90) myTurtle.forward(10) myTurtle.right(90) myTurtle.forward(numberOfRainyDays[i] * 10) myTurtle.left(90) #for temp in averageTemperatureList[i]: #pulse(temp, 25) #drawRainGraphRectangle() #calling the drawGraphRectangle function #to visualise averageTemperatureList #drawTempGraphRectangle() #pulse() drawGraphCircle() turtle.done()
true
a7e4955daf0d8d355bed55be5d43df8fffff872c
HarshaYadav1997/100daychallange
/day-5/matrixtranspose.py
481
4.1875
4
rows = int(input("Enter number of rows in the matrix: ")) columns = int(input("Enter number of columns in the matrix: ")) matrix = [] print("Enter the %s x %s matrix: "% (rows, columns)) for i in range(rows): matrix.append(list(map(int, input().rstrip().split()))) "tranpose of a matrix is" for i in matrix: print(i) tmatrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] print("Transpose of Matrix : ") for i in tmatrix: print(i)
true
f3f5d8f50592f4d4cb642061f6e4bb57bbe74329
gbartomeo/mtec2002_assignments
/class11/labs/my_fractions.py
1,500
4.40625
4
""" fractions.py ===== Create a class called Fraction that represents a numerator and denominator. Implement the following methods: 1. __init__ with self, numerator and denominator as arguments that sets a numerator and denominator attribute 2. __str__ with self as the only argument... that prints out a fraction as numerator/denominator ...for example, 1/2 3. pretty_print with self as the only argument... it prints out: 1 - 2 4. multiply with self and another Fraction as the arguments... it should alter the numerator and denominator of the current fraction, but it's not necessary to reduce 5. (INTERMEDIATE) add with self and another Fraction as the arguments... it should alter the numerator and denominator of the currecnt fraction, but it's not necessary to reduce Some example output from the interactive shell: >>> a = Fraction(1,2) >>> print a 1/2 >>> a.pretty_print() 1 - 2 >>> a.add(Fraction(1,4)) >>> print a 6/8 >>> a.multiply(Fraction(2,3)) >>> print a 12/24 >>> """ class Fraction: def __init__(self,numerator,denominator): self.numerator = numerator self.denominator = denominator def __str__(self): self.pretty_print = "%s\n-\n%s" % (self.numerator, self.denominator) return "%s/%s" % (self.numerator, self.denominator) def multiply(self,f): try: self.x = (self.x*f.x) self.y = (self.y*f.y) except AttributeError: try: self.x = (self.x*f[0]) self.y = (self.x*f[1]) except: raise TypeError("What are you trying to multiply by?!")
true
5e4abdc4bb35aa3cad8a8b740f422f2e4f53b590
gbartomeo/mtec2002_assignments
/class5/greetings.py
580
4.40625
4
""" greetings.py ===== Write the following program: 1. Create a list of names and assign to a variable called names 2. Append another name to this list using append 3. Print out the length of this list 4. Loop through each item of this list and print out the name with a greeting, like "hello", appended before it For example... Hello Dave Hello Sue Hello James """ names = ["Mary", "Jane", "Marth", "Jacob", "Dave", "Sue", "James"] names.append("Kiara") print "There are %d names in this list!" % len(names) i = 0 while i < len(names): print "Hello %s!" % names[i] i += 1
true
2c6f5d75d5a749a332ffafb990764c00e7fd4cb2
wittywatz/Algorithms
/Algorithms Python/validMountain.py
597
4.375
4
def validMountainArray(arr): ''' Returns true if the array is a valid mountain ''' if (len(arr)<3): return False index = 0 arrlen = len(arr) while ((index+1)<=(arrlen-1) and arr[index]<arr[index+1]): index +=1 if(index == arrlen-1 or index==0): return False while((index+1)<=(arrlen-1) and arr[index]>arr[index+1]): index +=1 if(index < arrlen-1): return False else: return True
true
5f6f2d8e3feb52ac48c05ad6b00d4fa52e035487
EmmanuelTovurawa/Python-Projects
/Class_Work/Chapter 4/chapter4_pg_116.py
1,033
4.46875
4
#4.10 pizzas = ['veggie', 'meat', 'cheese', 'BBQ', 'buffalo'] print(f"The first three items in the list are: ") for pizza in pizzas[:3]: print(pizza) print("") print("Three items from the middle of the list are") #get the middle position middle = int(len(pizzas)/2) for pizza in pizzas[middle-1:middle+2]: print(pizza) print("") print("The last three items of the list are") for pizza in pizzas[-3:]: print(pizza) print("") #4.11 my_pizzas = ['veggie', 'meat', 'cheese', 'BBQ'] friend_pizzas = my_pizzas[:] my_pizzas.append('hawaiian') friend_pizzas.append('pepperoni') print("My favourite pizzas are:") for pizza in my_pizzas: print(pizza) print("My friend's favourite pizzas are:") for pizza in friend_pizzas: print(pizza) print("") my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli'] friend_foods = ['pizza', 'falafel', 'carrot cake', 'ice cream'] print("My favourite foods are:") for my_food in my_foods: print(my_food) print("My friend's favourite food are:") for friend_food in friend_foods: print(friend_food)
false
1ae005031a741bb896fdd8a9cf8aee17ed85ee91
EmmanuelTovurawa/Python-Projects
/Class_Work/Chapter 2/chapter2_pg_71.py
601
4.1875
4
# 2.3 name = "Emmanuel" print(f"Hello {name}, would you like to learn some Python today?") # 2.4 name_1 = "Emmanuel" print(name_1.lower()) print(name_1.upper()) print(name_1.title()) # 2.5 print('Dale Carnegie once said, "The successful man will profit from mistakes and try again in a different way"') # 2.6 famous_person = "Dale Carnegie" message = f"{famous_person} once said, 'The successful man will profit from mistakes and try again in a different way'" print(message) # 2.7 my_name = " Emmanuel " my_name = f"{my_name} \n\t{my_name.lstrip()} \n\t{my_name.rstrip()} \n\t{my_name.strip()}" print(my_name)
false
018180c41b27bdd3582dedfa279c0e8f8532fa53
rbunch-dc/11-18immersivePython101
/python101.py
2,768
4.40625
4
# print "Hello, World"; # print("Hello, World"); # print """ # It was a dark and stormy night. # A murder happened. # """ # print 'Hello, World' # print 'Khanh "the man" Vu' print 'Binga O\'Neil\n' # # Variables # # - strings, letters, numbers, or any other stuff # # you can make with a keyboard # # a variable is just a fast way to refer to something else # # variables do not make the program faster. # # They make the program slower! # # Variables make it easier for us to write programs. # # theBestClass = "the 11-18 immersive" # # print theBestClass # # Data Types # # - Programming langauges see different types fo variables # # differently # # - String - English stuff. # # - Number - I think you know what this is. Something with numbers (or - or e) # # # print 3.3e10+"Joe" # # -- float = it has a . in it # # -- integer - has no . # # - Booleans - true or false, on or off, 1 or 0, yes or no, right or left # # - List - list of things. a single variable with a bunch of parts # # - Dictionaries - variable of variables # # - Objects - super dictionaries # # Primitive Data tyes = string, number, boolean # month = "November"; # print type(month) # date = 13 # print type(date) # dateAsFloat = 13.0 # print type(dateAsFloat) # aBool = True # print type(aBool) # aList = [] # print type(aList) # aDictionary = {} # print type(aDictionary) # # concatenate is programming speak for add things together # first = "Robert" # last = "Bunch" # fullName = first + last; # fullName = first + " " + last; # print fullName # fourteen = 10 + 4 # print fourteen # fourteen = "10" + "4" # print fourteen # # fourteen = 10 + "4" # # print fourteen # # cast = change a variable to a new data type # fourteen = int("10") + 4 # fourteen = int("ten") + 4 # Math = +, -, /, *, % # print 2+2 # print 2-2 # print 2/2 # print 2*2 # # % = modulus. Moudulus divides the number and gives you the remainder # print 2%2 # print 2%3 # print 2**3 # print 10**87 # A string and a * and a number = give me X strings # print "--" * 20 # print "Rob"**20+" The world already has too many Robs" # Python does not have a simple incrementer num = 1; # num++ num += 1 # C # C++ # Input # Python 2 = raw_input # Python 3 = input # name = raw_input("What is your name? ") # print type(name) # conditionals # a single = sign, means set the left to whateer is on the right # two = signs, means compare what's on the left, to wahtever is on the right print 2 == 2 print 2 == 1 print 2 == "2" secret_number = 5; if(secret_number == 3): print "Secret number is 3"; else: print "Secret number is not 3."; game_on = True; i = 0; # while(game_on): while(game_on == True): i+= 1 if(i == 10): game_on = False else: print "Game on!!" print "Loop exited!"
true
e50f64e8a117186ebf66b550df6e7a7802b7bdfd
rbunch-dc/11-18immersivePython101
/dictionaries.py
1,559
4.21875
4
# DICTIONARIES # Dictionaries are just like lists # Except... instead of numbered indicies, they # have English indicies greg = [ "Greg", "Male", "Tall", "Developer" ] # If I wanted to know Greg's job, I have to do greg[3] # No one is going to expect that # A dictionary is like a list of variables name = "Greg" gender = "Male" height = "Tall" job = "Developer" # Key:value pair greg = { "name": "Greg", "gender": "Male", "height": "Tall", "Job": "Developer" } # print greg["name"] # print greg["Job"] # Make a new dictionary zombie = {} #dictionary zombies = [] #list # zombies.append() zombie['weapon'] = "fist" zombie['health'] = 100 zombie['speed1'] = 10 print zombie print zombie['weapon'] for key,value in zombie.items(): print "Zombie has a key of %s with a value of %s" % (key, value) # in our game, poor zombie loses his weapon (arm falls off) # we need to remove his "weapon" key del zombie['weapon'] print zombie is_nighttime = True if(is_nighttime): zombie['health'] += 50 # Put lists and dictionaries together!!! zombies = [] zombies.append({ 'name': 'Hank', 'weapon': 'baseball bat', 'speed': 10 }) zombies.append({ 'name': 'Willie', 'weapon': 'axe', 'speed': 3, 'victims': [ 'squirrel', 'rabbit', 'racoon' ] }) # this will get the first zombie in zombies weapon print zombies[0]['weapon'] # this will get the second victim, in the second zomnbies list of victims print zombies[1]['victims'][1] # if we wante to know, zombie1's weapon:
true
6f9d88d25edbbf0303d51140822f8f790e048c44
NaserWhite/STEP2017
/Review.py
504
4.15625
4
age = int(input("Enter your age => ")) # 30 < 3 = False if age < 3: print("Toddler") # 30 > 20 = True and 30 < 30 = False ----- True and False --- False elif age > 20 and age < 30: print("You're in your 20's") # 30 > 30 + True and 30 < 40 = True ----- True and True --- True elif age > 30 and age < 40: print("You're i your 30's")
false
c59556760fce2bdb2cc045b411aebf78e8214b3a
mesaye85/Calc-with-python-intro-
/calc.py
1,171
4.21875
4
def print_menu(): print("-"* 20) print(" python Calc") print("-"* 20) print("[1] add ") print("[2] subtract") print("[3] multiply") print('[4] Division') print("[5] My age") print('[x] Close') opc = '' while( opc!= 'x'): print_menu() opc = input('Please choose an option:') num1 = float(input("First number:")) num2 = float(input("Second number:")) age = int(input("Your Date of Birth")) if(opc == '1'): res = float(num1) + float(num2) print("Result: " + str(res)) elif (opc == '2'): res = float(num1) - float(num2) print("Result: " + str(res)) elif (opc == '3'): res = float(num1) * float(num2) print("Result: " + str(res)) elif (opc == '4'): if (num2 == 0): print("Don't divide by zero, y will kill us ALL") else: res = float(num1) / float(num2) print("Result: " + str(res)) elif (opc == '5'): res = (2020) - int(age) print("Your age is " + str(res)) else: print("Invalid option, please choose a valid option") print('Good bye!')
true
76191c55ec6b572b1c2cd21faf810b3f66052944
TamaraGBueno/Python-Exercise-TheHuxley
/Atividade Continua 2/Média.py
1,017
4.125
4
#descreva um programa que receba as notas e a presença de um aluno, calcule a média e imprima a situação final do aluno. #No semestre são feitas 3 provas, e faz-se a média ponderada com pesos 2, 2 e 3, respectivamente. #Os critérios para aprovação são: #1 - Frequência mínima de 75%. #2 - Média final mínina de 6.0 (calculada com uma casa de precisão). #E devem ser considerados os casos especiais descritos para a impressão dos resultados, com uma mensagem personalizada para cada situação. p1 = float(input()) p2 = float(input()) p3 = float(input()) freq = float(input()) media = round((2*p1 + 2*p2 + 3*p3)/7,1) porcentagem = int(freq*100) print("Frequencia: {}%".format(porcentagem)) print("Media: {:.1f}".format(media)) if porcentagem < 75: print("Aluno reprovado por faltas!") elif media > 9: print("Aluno aprovado com louvor!") elif 6 <= media <= 9: print("Aluno aprovado!") elif 4 <= media < 6: print("Aluno de recupera��o!") else: print("Aluno reprovado!")
false
b65280021b7397d9f85e81ea974600001c8908c1
posguy99/comp660-fall2020
/src/M4_future_value_calculator.py
1,229
4.34375
4
#!/usr/bin/env python3 def calculate_future_value(monthly_investment, yearly_interest_rate, years): monthly_interest_rate = yearly_interest_rate / 12 / 100 months = years * 12 future_value = 0 for i in range(0, months): future_value += monthly_investment monthly_interest_amount = future_value * monthly_interest_rate future_value += monthly_interest_amount return future_value def main(): print('Welcome to the Future Value Calculator\n') # potted choice to make the first pass through the loop work # _while_ evaluates at the *top* of the loop choice = 'y' while choice == 'y': monthly_investment = float(input('enter your monthly investment:\t')) yearly_interest_rate = float(input('Enter yearly interest rate:\t')) years = int(input('Enter number of years:\t\t')) future_value = calculate_future_value(monthly_investment, yearly_interest_rate, years) print('Future value:\t\t\t' + str(round(future_value,2))) # chose to continue at the bottom of the loop... choice = input('Continue? (y or n)\t\t') print('Thank you for using the Future Value Calculator') if __name__ == '__main__': main()
true
1c8c6473e7fe467a4e21bb6707b54ea154764777
posguy99/comp660-fall2020
/src/Module 2 Assignment 3.py
672
4.34375
4
#!/usr/bin/env python3 kg_to_lb = 2.20462 earth_grav = 9.807 # m/s^2 moon_grav = 1.62 # m/s^2 mass = float(input("Please enter the mass in lb that you would like to convert to kg: ")) kg = mass / kg_to_lb print("The converted mass in kg is:", kg) print("Your weight on Earth is:", kg*earth_grav, "Newtons") print("Your weight on the Moon is:", kg*moon_grav, "Newtons") print("The percentage of the weight on the Moon in comparison to what is experienced on Earth:", (kg*moon_grav)/(kg*earth_grav)*100, "%") print("The percentage of the weight on the Moon in comparison to what is experienced on Earth as an integer:", round((kg*moon_grav)/(kg*earth_grav)*100), "%")
true
190bbbc26dd2db956d03a7dbcf9b2edc27bd8599
posguy99/comp660-fall2020
/src/M6_Exercise.py
1,052
4.1875
4
# string traversal fruit = 'Apple' # print forwards index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 # exercise 1 - print in reverse index = len(fruit) while index: letter = fruit[index - 1] # because slice is zero-based print(letter) index = index - 1 # exercise 2 - what is [:] print(fruit[:]) # exercise 3 - def countem(word, char): count = 0 for i in range(len(word)): if word[i] == char: count = count + 1 return count print(countem(fruit, 'p')) # **Exercise 4: There is a string method called count that is similar to the # function in the previous exercise. Read the documentation of this method at: # Write an invocation that counts the number of times the letter a occurs in # “banana”.* print(fruit.count('p')) # exercise 5 - str = 'X-DSPAM-Confidence:0.8475' loc = int(str.find(':')) + 1 # get to char after the colon score = float(str[loc : ]) # from after the colon to the end print('score: ', score)
true
2d52aa2d9101714688f9bbd6498c17a10e7def6d
Pavan1511/python-program-files
/python programs/data wise notes/29 april/default dict ex3.py
797
4.1875
4
#Program: 3 returning a default value if key is not present in defaultdict # creating a defaultdict # control flow --> 1 from collections import defaultdict # control flow --> 5 def creating_defaultdict(): student = defaultdict(func) # ----> invoke func() ---> 8 print(type(student)) student['usn'] = '1rn16scs18' student['name'] = 'Arjun' student['cgpa'] = 7.5 print(student) print(student['name']) # Arjun print(student['sem']) # 8 ##control flow --> 7 # control flow --> 6 def func(): return 8 # control flow --> 4 def main(): creating_defaultdict() # control flow --> 8 # control flow --> 2 if __name__ == "__main__": main() # control flow --> 3 # control flow --> 9 # control flow --> 10 ---os
true
ab2d92b7e16305d3ce343c6926e3cce6508959e2
EricWWright/PythonClassStuff
/aThing.py
1,369
4.125
4
# print("this is a string") # name = "Eric" # print(type(name)) # fact = "my favorite game is GTA 5" # print("my name is " + name + " and I like " + fact) # # or # print("my name is ", name, " and i like ", fact) # # or # message = "my name is " + name + " and I like " + fact # print(message) # # vars # num = 8 # num2 = 14 # print(num+num2) # answer = num - num2 # print(answer) # # vars # word = "sweet" # word1 = "cool" # word2 = "mean" # word3 = "dark" # word4 = "mate" # print("I took a sip of " + word + " tea that was nice and " + word1 + ". With my " + word + " " + word1 + " tea I ate a " + word2 + # " steak that was cooked to perfection. It started to get " + word3 + " so me and my " + word4 + " decided to call it a night.") # update vars to inputs word = input("Type an adjective ") word1 = input("Type a name ") word2 = input("Type another name ") word3 = input("Type a weapon ") word4 = input("Type another weapon ") # new madlib print("On a " + word + " night " + word1 + " was angerd at " + word2 + " because " + word2 + " wasn't being really nice. " + word1 + " decided to pickup a " + word3 + " and proceed to hit " + word2 + " with it. But " + word2 + " didn't like that so " + word2 + " decided to pick up a " + word4 + " and fight " + word1 + " with it. In an epic battle to the death " + word1 + " was victorious.") input()
true
362394abdf87008e69007c7268050b4397e57a08
hkam0323/MIT-6.0001
/Problem set 4a - Permutations.py
1,980
4.5
4
def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all permutations of sequence Example: >>> get_permutations('abc') ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] Note: depending on your implementation, you may return the permutations in a different order than what is listed here. ''' # List of possible permutations permutation = [] # Base case: If only 1 char, return itself (permutation of 1 char is 1 char) if len(sequence) == 1: return ([sequence]) # Recursive case: Find all the different ways to insert first character into # each permutation of remaining characters else: first_char = sequence[0] remaining_char = sequence[1:] remaining_char_permutations = get_permutations(remaining_char) # Adds first_char into remaining_char_permutations for r in remaining_char_permutations: # r = bc, cb # Adds first_char to first and last position of remaining_char_permutations permutation.append(first_char + r) # a, bc permutation.append(r + first_char) # bc, a # Adds first_char to all other positions in remaining_char_permutations for i in range(1, len(r)): # eg. bcd = len 3 --> i = 1, 2 add_permutation = "" add_permutation += r[0:i] + first_char + r[i:] permutation.append(add_permutation) return (permutation) if __name__ == '__main__': example_input = 'abc' print('Input:', example_input) print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) print('Actual Output:', get_permutations(example_input))
true
912b52732d9352aac2720272b97757106a549eff
Fongyitao/_001_python_base
/_008_字符串/_001_字符串常用方法.py
1,957
4.28125
4
name="abcdefg" print(name[0]) print(name[len(name) - 1]) print(name[-1]) str = "hello world itcast and itxxx" index = str.find("world") print(index) # 6 下标为6 index = str.find("dog") print(index) # -1 没有就返回 -1 index = str.rfind("itcast") print(index) # 12 index = str.index("w") print(index) # 6 count = str.count("o") print(count) # 2次 str1 = str.replace("it", "IT") # 原字符串并未发生改变 print(str1) # hello world ITcast and ITxxx print(str) # hello world itcast and itxxx str2 = str.split(" ") # 将字符串,按空格切割,返回一个列表,切割完之后,返回的列表里面就不在有空格了 print(str2) # ['hello', 'world', 'itcast', 'and', 'itxxx'] str3 = str.capitalize() # 将字符串的第一个字母大写 print(str3) # Hello world itcast and itxxx str4 = str.title() # 所有单词的首字母大写 print(str4) # Hello World Itcast And Itxxx startwith = str.startswith("hello") print(startwith) # True endwith = str.endswith("xxx") print(endwith) # True str5 = str.lower() # 全部转换为小写字母 print(str5) # hello world itcast and itxxx str6 = str.upper() # 全部转换为大写字母 print(str6) # HELLO WORLD ITCAST AND ITXXX str7 = "Hello World" str7 = str7.center(30) # 居中p print(str7) # Hello World str8 = str7.strip() # 去除左右两边的空格 print(str8) # Hello World str9 = str.partition("it") # 返回元组 print(str9) # ('hello world ', 'it', 'cast and itxxx') str10 = str.rpartition("it") print(str10) # ('hello world itcast and ', 'it', 'xxx') str11 = str.splitlines() # 按换行符切割,返回列表 str12 = "hello" alpha = str12.isalpha() # 判断一个字符串是否是 纯字母 print(alpha) # True digit = str12.isdigit() # 判断一个字符串是否是 纯数字 print(digit) # False str13 = ["aaa", "bbb", "ccc"] str14 = "--".join(str13) # 把列表元素连接起来 print(str14) # aaa--bbb--ccc
false
582e9d3021b08852ec9e56d72528155992ee6298
Fongyitao/_001_python_base
/_011_递归和匿名函数/_006_seek定位光标位置.py
542
4.34375
4
''' 定位到某个位置: 在读写文件的过程中,需要从另一个位置进行操作的话,可以使用seek() seek(offset,from)有两个参数 offset:偏移量 from:方向 0:表示文件开头 1:表示当前位置 2:表示文件末尾 ''' # demo:把位置设置为:从文件开头偏移5个字节 # 打开一个已经存在的文件 f=open("test.txt","r") str=f.read(10) print("读取的数据是:%s" %str) f.seek(1,0) # 查找当前位置 position=f.tell() print("当前的位置是:%s" %position) f.close()
false
4dd880f4f2423a147bbeb86ff4d7ad545d0b6513
baksoy/WebpageScraper
/WebpageScraper.py
1,155
4.15625
4
import urllib2 from bs4 import BeautifulSoup website = urllib2.urlopen('https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)').read() # print website # html_doc = """ # <html><head><title>The Dormouse's story</title></head> # <body> # <p class="title"><b>The Dormouse's story</b></p> # # <p class="story">Once upon a time there were three little sisters; and their names were # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; # and they lived at the bottom of a well.</p> # # <p class="story">...</p> # """ # soup = BeautifulSoup(website, 'html.parser') # print (soup.prettify()) # print soup.title.string # print soup.h1.span.string # print soup.h2.span.string # for link in soup.find_all('a'): # print (link.get('href')) # Extract all text from a web page # print(soup.get_text()) for link in soup.find_all('a'): print ("===============") print (link.string) print (link.get('href')) print ("===============") print (" ")
true
3652fc5411c75588d37319f9776dbaee6e5044d4
Viktoriya-Pilipeyko/books
/dousonP2.py
1,504
4.3125
4
# Бесполезные факты # # Узнает у пользователя его / ее личные данные и выдает несколько фактов #о нем / ней. Эти факты истинны. но совершенно бесполезны. name = input( "Привет. Как тебя зовут? ") age = input("Сколько тебе лет? ") age = int(age) weight = int(input("Xopoшo. и последний вопрос. Сколько в тебе килограммов?")) print('\nЕсли бы поэт Камминг решил адресовать тебе письмо, он бы обратился к тебе так: ', name.lower()) print('А если бы это был рехнувшийся Каммингс. то так: ', name.upper()) print('\nЕсли бы маленький ребенок решил привлечь твое внимание') print('он произнес бы твое имя так:') print(name * 5) seconds = age * 365 * 24 * 60 * 60 print('\nТвой нынешний возраст - свыше', seconds, 'секунд') moon_weight = weight / 6 sun_weight = weight * 27.1 print('\nЗнаете ли Вы, что на Луне вы бы весили всего', moon_weight, 'кг?') print('А вот находясь на Солнце, вы бы весили', sun_weight, 'кг. (Но, увы, это продолжалось бы недолго...)') input( "\n\nНажмите Enter. чтобы выйти.")
false
44ad837a03b617202d6417f71b911cd4ab5f9add
dpkenna/PracticePython
/Exercise 6.py
254
4.1875
4
# http://www.practicepython.org/exercise/2014/03/12/06-string-lists.html maypal = input('Enter a string: ') backwise = maypal[::-1] if maypal == backwise: print('{} is a palindrome'.format(maypal)) else: print('{} is not a palindrome'.format(maypal))
true
54cbd8559c9106cca85fe8b504e73b52700c9735
amisha-tamang/function
/factorial.py
254
4.1875
4
def factorial(inputValue): if inputValue==0: return inputValue elif inputValue==1: return inputValue else: return inputValue*factorial(inputValue-1) Number = 6 print("factorial of number") print(factorial(Number))
false
0c56bdd6fff73ded84befae2bf975f7910ce62dc
milton-dias/Fatec-Mecatronica-0791721011-Rogerio
/LTP2-2020-2/Pratica03/elife.py
320
4.125
4
numero_secreto = 32 numero_secreto2 = 42 numero_secreto3 = 23 palpite = int(input("Informe um Palpite: ")) if palpite == numero_secreto: print("Acertou") elif palpite > numero_secreto: print("Chute um numero menor") elif palpite < numero_secreto: print("Chute um numero maior") else: print("Caso padrão")
false
7147f9ddac28af4a1faeec6ff3eb5c01d8353e78
rmccorm4/BHSDemo.github.io
/rand.py
246
4.1875
4
#Game to guess a number between 1-10, or any range you choose import random number = str(random.randint(1, 10)) guess = input("Guess a number between 1 and 10: ") print(number) if guess == number: print("You won!") else: print("You lost!")
true
8ec77ebfb0083525c3ad4e39ffcc1430826d6d61
Jueee/PythonStandardLibrary
/lib03.02-threading.py
1,257
4.125
4
''' threading 模块 (可选) threading 模块为线程提供了一个高级接口 它源自 Java 的线程实现. 和低级的 thread 模块相同, 只有你在编译解释器时打开了线程支持才可以使用它. 你只需要继承 Thread 类, 定义好 run 方法, 就可以创建一个新的线程. 使用时首先创建该类的一个或多个实例, 然后调用 start 方法. 这样每个实例的 run 方法都会运行在它自己的线程里. ''' # 使用 threading 模块 import threading import time, random class Counter(object): """docstring for Counter""" def __init__(self): # 使用了 Lock 对象来在全局 Counter 对象里创建临界区(critical section). self.lock = threading.Lock() self.value = 0 def increment(self): self.lock.acquire() self.value = value = self.value + 1 self.lock.release() return value counter = Counter() class Worker(threading.Thread): """docstring for Worker""" def run(self): # pretend we're doing something that takes 10?00 ms value = counter.increment() # increment global counter time.sleep(random.randint(10, 100) / 1000.0) print(self.getName(), '-- task', i, 'finished', value) # try it for i in range(10): Worker().start() # start a worker
false
d7f536b5654e29a431238f19f3b8efcc93c35440
AshaS1999/ASHA_S_rmca_s1_A
/ASHA_PYTHON/3-2-2021/q3sum of list.py
224
4.125
4
sum = 0 input_string = input("Enter a list element separated by space ") list = input_string.split() print("Calculating sum of element of input list") sum = 0 for num in list: sum += int (num) print("Sum = ",sum)
true
48dcf7ecbe7d8761756704c15b08f729520ffdb4
joshuastay/Basic-Login-Code
/login.py
2,942
4.3125
4
import re class LoginCredentials: """ Simple login authentication program includes a method to create a new user stores values in a dictionary """ def __init__(self): self.login_dict = dict() self.status = 1 # method to check if the password meets parameters def check_pass(self, entry): check_upper = False check_lower = False check_length = False check_int = False check_spec = False for each in entry: if each.islower() is True: check_lower = True else: continue for each in entry: if each.isupper() is True: check_upper = True else: continue if re.search("\d", entry): check_int = True if len(entry) >= 8 and len(entry) <= 20: check_length = True if re.search("[!, @, #, $, %]", entry): check_spec = True if check_spec and check_length and check_int and check_upper and check_lower: return True else: return False # new_login prompts user for a new username and password and stores values in the dictionary def new_login(self): make_user = True make_pass = True while make_user is True: print("Enter a new username (limit 25 characters, no spaces) ") username = input("Username: ") if len(username) > 25 or username.count(" ") > 0: print("Invalid Username!") continue elif username in self.login_dict.keys(): print('Username in use!') continue make_user = False while make_pass is True: print("Enter a new password (atleast 8 characters, limit 20. Must include lowercase, uppercase, numbers and" " a special character !, @, #, $, %") password = input("Enter new password: ") passvalid = self.check_pass(password) if passvalid: self.login_dict[username] = password break else: print("Password Invalid!") continue # login method checks the dictionary for a matching username and password def login(self): username = input("Username: ") if self.login_dict.get(username) is not None: attempts = 3 while attempts > 0: password = input("Password: ") if self.login_dict[username] == password: print("Login Successful!") break else: attempts -= 1 print("Login Failed! attempts remaining: ", attempts) else: print("Unrecognized Username!")
true
122addb28d5f13854eca172d0be609d3369bea70
Combatd/Intro_to_Algorithms_CS215
/social_network_magic_trick/stepsfornaive.py
470
4.1875
4
# counting steps in naive as a function of a def naive(a, b): x = a y = b z = 0 while x > 0: z = z + y x = x - 1 return z ''' until x (based on value of a) gets to 0, it runs 2 things in loop. 2a we have to assign the values of 3 variables 3 ''' def time(a): # The number of steps it takes to execute naive(a, b) # as a function of a steps = 0 # your code here steps = 2 * a + 3 return steps
true
b896a796ea172a50137208a7f0adefa10194bfd0
javierlopeza/IIC2233-2015-2
/Tareas/T02/clases/ListaLigada.py
2,804
4.15625
4
class ListaLigada: """ Clase que construye una estructura simulando una lista ligada. """ def __init__(self): """ Se inicializa sin elementos. """ self.e0 = None self.largo = 0 def append(self, valor): """ Agrega el valor en un nuevo atributo de la lista. """ setattr(self, 'e{0}'.format(self.largo), valor) self.largo += 1 def __getitem__(self, item): """ Retorna el elemento de indice item. Se usa igual que las listas de Python, indicando el indice entre corchetes: self[i] """ if str(item).isdigit(): if int(item) < self.largo: valor_item = getattr(self, 'e{0}'.format(item)) return valor_item def __setitem__(self, key, value): """ Permite realizar item assignment en la lista. """ setattr(self, 'e{0}'.format(key), value) def __iter__(self): for i in range(self.largo): yield getattr(self, "e{0}".format(i)) def __len__(self): """ Retorna la cantidad de elementos existentes. """ return self.largo def __add__(self, other): lista_retorno = ListaLigada() for e1 in range(len(self)): lista_retorno.append(self[e1]) for e2 in range(len(other)): lista_retorno.append(other[e2]) return lista_retorno def pop(self): valor_popeado = getattr(self, "e{0}".format(self.largo - 1)) delattr(self, "e{0}".format(self.largo - 1)) self.largo -= 1 return valor_popeado def remove(self, value): i_remover = None for n in range(self.largo): if getattr(self, "e{0}".format(n)) == value: i_remover = n break if i_remover is not None: for i in range(i_remover, self.largo - 1): setattr(self, "e{0}".format(i), getattr(self, "e{0}".format(i + 1))) delattr(self, "e{0}".format(self.largo - 1)) self.largo -= 1 def extend(self, other): for e in range(len(other)): self.append(other[e]) def contiene(self, valor): """ Retorna True si la lista contiene valor. """ for a in range(self.largo): if getattr(self, 'e{0}'.format(a)) == valor: return True return False def __repr__(self): """ Imprime la lista ligada de manera simple y comprensible. """ if self.largo == 0: return "[]" rep = '[' for a in range(self.largo): rep += '{0}, '.format(getattr(self, 'e{0}'.format(a))) rep = rep[:-2] rep += ']' return rep
false
5c3ff785d5fe122e97fe146ba170d1021f8ddb4d
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 3 Estruturas Compostas/Desafios/desafio082.py
556
4.15625
4
number_list = [] even_list = [] odd_list = [] while True: number = int(input('Input a number: ')) number_list.append(number) if number % 2 == 0: even_list.append(number) else: odd_list.append(number) answer = '' while answer != 'Y' and answer != 'N': answer = input('Do you want to continue [Y/N]? ').strip().upper()[0] if answer == 'N': break print(f'The inserted numbers are {number_list}') print(f'The inserted even numbers are {even_list}') print(f'The inserted odd numbers are {odd_list}')
false
4a38e180aabadcdb26f7ec2814ae2ae876f9e7a6
henriqueumeda/-Python-study
/MIT/600.1x - Introduction to Computer Science and Programming Using Python/Unit 3/Tuples and Lists/odd_tuples.py
319
4.21875
4
def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' odd_tuple = () for number, element in enumerate(aTup): if number % 2 == 0: odd_tuple += (element, ) return odd_tuple aTup = ('I', 'am', 'a', 'test', 'tuple') print(oddTuples(aTup))
false
ce1a001e3dde4aa6bb413ad884cea077d526ecfc
StephTech1/Palindrome
/main.py
341
4.28125
4
#Add title to code print ("Is your word a Palindrome?") #Ask user for word input = str(input("What is your word?")) palin = input #create a function to check if a string is reversed #end to beginning counting down by 1 if palin == palin [::-1] : #print answers based on input print("Yes!") else: print("No!") print("Thanks for playing!")
true
ecacdeb6cd2c390e04e834191197100135c3d374
convex1/data-science-commons
/Python/filter_operations.py
2,074
4.1875
4
import pandas as pd import numpy as np """ create dummy dataframe about dragon ball z characters earth location and other information """ data = {"name": ["goku", "gohan"], "power": [200, 400], city": ["NY", "SEA"]} dragon_ball_on_earth = pd.DataFrame(data=data) """ ~~ABOUT~~ Use vectorization instead of using for loops to assign new values. You can use them to filter values easily. Try to do it whenever possible. It will be possible in most cases except a few minor complicated cases where for loop might be required. Vector operation is better than Scala operations. """ """ Common filter values: These are some common ways to filter your dataframe """ dragon_ball_on_earth[dragon_ball_on_earth['name'] == "goku"] dragon_ball_on_earth[dragon_ball_on_earth['name'].isnull()] dragon_ball_on_earth[dragon_ball_on_earth['name'].notnull()] dragon_ball_on_earth[dragon_ball_on_earth['name'].isna()] dragon_ball_on_earth[dragon_ball_on_earth['name'] < "a"] """ create new series (column) by using vectorization there is one single condition and one single outcome except the default """ dragon_ball_on_earth['is_goku'] = np.where(dragon_ball_on_earth['name'] == "goku", 1, 0) characters_with_power_100_or_more = np.where((dragon_ball_on_earth['name'].notnull()) & (dragon_ball_on_earth['power'] > 100), 1, 0) #you can also just get the indices of the rows that satisfy your condition dataframe_indices = np.where(dragon_ball_on_earth['name'] == "goku") """ How to assign the series column based on multiple conditions? Use np.select() instead of np.where() np.select() can take multiple conditions and multiple outcomes """ conditions =[[dragon_ball_on_earth['name'] == "goku"], [dragon_ball_on_earth['name'] == "gohan"], [dragon_ball_on_earth['power_level'].isin([100, 200, 400])]] outcomes = [1,2] #conditions and outcomes are from the assigned variables above #zero below is the default value to be assigned in case the conditions are not satisfied dragon_ball_on_earth['coded_name'] = np.select(conditions, outcomes, 0)
true
34f8bc7975b9905230efab2ff7f143d26fe0ecda
AlexandreInsua/ExerciciosPython
/exercicios_parte03/exercicio06.py
1,355
4.375
4
# 6) Utilizando la función range() y la conversión a listas genera las siguientes listas dinámicamente: # Todos los números del 0 al 10 [0, 1, 2, ..., 10] # Todos los números del -10 al 0 [-10, -9, -8, ..., 0] # Todos los números pares del 0 al 20 [0, 2, 4, ..., 20] # Todos los números impares entre -20 y 0 [-19, -17, -15, ..., -1] # Todos los números múltiples de 5 del 0 al 50 [0, 5, 10, ..., 50] # Pista: Utiliza el tercer parámetro de la función range(inicio, fin, salto). print("~~ Creando listas ~~") lista1 = [] lista2 = [] lista3 = [] lista4 = [] lista5 = [] for i in range(0,11): lista1.append(i) for i in range(-10,1): lista2.append(i) for i in range(0,21,2): lista3.append(i) for i in range(-19,0,2): lista4.append(i) for i in range(0,51,5): lista5.append(i) print("Números do 0 ao 10: ", lista1) print("Números do -10 ao 0: ", lista2) print("Números pares do 0 ao 20: ", lista3) print("Números impares do -20 ao 0: ", lista4) print("Números múltiplos de 5 do 0 ao 50: ", lista5) # solución de Ángel print("Números do 0 ao 10: ", list(range(0,11))) print("Números do -10 ao 0: ", list(range(-10,1))) print("Números pares do 0 ao 20: ", list(range(0,21,2))) print("Números impares do -20 ao 0: ", list(range(-19,0,2))) print("Números múltiplos de 5 do 0 ao 50: ", list(range(0,51,5)))
false
aa5ae68154e8d3a480bf8aba0900c88f60ce0a01
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio29.py
2,248
4.1875
4
# Ejercicio 29 # Crea un programa en python que sirva para convertir monedas. # * Primero pedirá (mediante un menú) que se indique el tipo de divisa inicial que vas a usar (ej: dólar, euro, libra, …) # * Luego pedirá un valor numérico por pantalla (float), que será la cantidad de esa divisa. # * Por último se pedirá (mediante un menú) a qué tipo de divisa deseas convertir. ej(a dólares, euros, libras, …) # Nota: si se eligió como tipo de divisa inicial el euro, no te pedirá que la conviertas a euros (no tiene sentido) def calcularConversion(tipoDivisaOrigen, cantidad, tipoDivisaDestino): if(tipoDivisaOrigen == 1): #euro if(tipoDivisaDestino == 1): #euro return cantidad elif(tipoDivisaDestino == 2): #dolar return cantidad*1.124 elif(tipoDivisaDestino == 3): # libras return cantidad*0.87 else: #error return -1 elif(tipoDivisaOrigen == 2): #dolar if(tipoDivisaDestino == 1): #euro return cantidad*0.89 elif(tipoDivisaDestino == 2): #dolar return cantidad elif(tipoDivisaDestino == 3): # libras return cantidad*0.77 else: #error return -1 elif(tipoDivisaOrigen == 3): # libra if(tipoDivisaDestino == 1): #euro return cantidad*1.15 elif(tipoDivisaDestino == 2): #dolar return cantidad*1.30 elif(tipoDivisaDestino == 3): # libras return cantidad else: #error return -1 else: # error return -1 print("Selecciona la divisa de origin") print("1- Euro") print("2- Dolar") print("3- Libra") print("4- Salir") tipoDivisaOrigen = int(input("Seleccina opción:")) if(tipoDivisaOrigen == 4): exit() cantidad = float(input("Cantidad de esa divisa:")) print("Selecciona la divisa a la cual convertir") if(tipoDivisaOrigen != 1): print("1- Euro") if(tipoDivisaOrigen != 2): print("2- Dolar") if(tipoDivisaOrigen != 3): print("3- Libra") print("4- Salir") tipoDivisaDestino = int(input("Seleccina opción:")) if(tipoDivisaDestino == 4): exit() resultado = calcularConversion(tipoDivisaOrigen, cantidad, tipoDivisaDestino) print(resultado)
false
3d292e18c4200a4f2809f1c9668da62a1c54f6c4
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio02.py
281
4.125
4
# Pide constantemente numeros ata que se introduce -1. Logo mostra a súa suma. print("Suma de números (-1 para finalizar)") num = 0 acumulator = 0 while num != -1: num = float(input("Introduza un número: ")) acumulator += num print("A suma dos número é: ", acumulator)
false
c892d4b1f235510f6695392342f8e6a8495fa1c5
AlexandreInsua/ExerciciosPython
/exercicios_parte01/exercicio05.py
856
4.28125
4
#5) La siguiente matriz (o lista con listas anidadas) debe cumplir una condición, # y es que en cada fila, el cuarto elemento siempre debe ser el resultado de sumar los tres primeros. # ¿Eres capaz de modificar las sumas incorrectas utilizando la técnica del slicing? #Ayuda: La función llamada sum(lista) devuelve una suma de todos los elementos de la lista ¡Pruébalo! # orixinal matriz = [ [1, 1, 1, 3], [2, 2, 2, 7], [3, 3, 3, 9], [4, 4, 4, 13] ] print("Matriz orixinal: ") for fila in matriz: print("\t", fila) print("\nMatriz modificada") for fila in matriz: fila[3] = sum(fila[:3]) print("\t", fila) # Ángel usa os slicing desde o final: # o 4º elemento = suma dos 3 primeiros [:-1] desde o principio até o final, excluído este. # matriz[1][-1] = sum(matriz[1][:-1]) # matriz[3][-1] = sum(matriz[3][:-1])
false
92c9a9d6d247507651eb9be5d34d3508b6a144b5
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio23.py
262
4.375
4
# Realiza un programa en python que pida la anchura de un triángulo # y lo pinte en la pantalla (en modo consola) mediante asteriscos. anchura = int(input("inserte a anchura do lado: ")) aux = "*" for i in range(anchura): print(aux) aux = aux + "*"
false
d3c4297906e7eee347f7b49baa4274c37f6bba6f
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio30.py
1,367
4.34375
4
# Programa (en python) que calcule áreas de: cuadrados(en función de su lado), # rectángulos(en función de sus lados, circunferencias(en función de su radio) y triángulos # rectángulos(en función de su base y su altura). # Primero se pedirá el objeto que se va a calcular(cuadrado, rectángulo, circunferencia o triangulo # rectangulo. # Luego se pedirán los datos necesarios de esa figura y se mostrará el valor del area por pantalla. print("Selecciona tipo de figura") print("1- Cuadrado") print("2- Rectángulo") print("3- Circunferencia") print("4- Triangulo rectángulo") print("5- Salir") tipo = int(input("Seleccona opción:")) if tipo == 5: exit() print("Introduce los datos necesarios") if tipo == 1: lado = float(input("Introduce el lado de cuadrado:")) area = lado * lado elif tipo == 2: base = float(input("Introduce la base del rectangulo:")) altura = float(input("Introduce la altura del rectangulo:")) area = base * altura elif tipo == 3: radio = float(input("Introduce el radio de la circunferencia:")) area = 3.141519 * radio * radio elif tipo == 4: base = float(input("Introduce la base del triangulo:")) altura = float(input("Introduce la altura del triangulo:")) area = base * altura / 2.0 else: area = 0 print("ERROR EN LA OPCIÓN SELECCIONADA") print("Area:" + str(area))
false
530de8ff2ed5d46e819d098591c2deb56e081623
Psuedomonas/Learn-Python-3
/Strings.py
508
4.15625
4
str1 = '''This is a multi-line string. This is the first line. This is the second line. "What's your name?," I asked. He said "Bond, James Bond." ''' str2 = 'What\'s your name?' str3 = "What's your name?" str4 = "This is the first sentence.\ This is the second sentence." str5 = '''Yubba dubba. \n The grass is greener \t after the rain.''' print(str1, str2, str3, str4, str5) age = 25 name = 'Sawroop' print('{0} is {1} years old'.format(name, age)) print('Why is {0} playing with that python?'.format(name))
true
e8b37ca27deb3bc5997c06b9d840ddb5239edc63
reidpat/GeeringUp
/oop.py
809
4.125
4
# creates a class class Dog: # ALL dogs are good good = True # runs when each "Dog" (member of Class) is created def __init__ (self, name, age): self.name = name self.age = age self.fed = False # function exclusive to Dog def bark(self): print(self.name + " starts to bark!") # create a function outside of class def feed(dog): dog.fed = True def isDogFed(dog): if (dog.fed == True): return True elif (dog.fed == False): return False else: # how do we get here? print("Dog is confused.") # return dog.fed # ----------- create some dogs ------------------- doggo = Dog("Bowser", "7") # b = Dog() # ----------- play with our dogs! ---------------- doggo.bark() # bark() print(isDogFed(doggo)) feed(doggo) print(isDogFed(doggo)) print(doggo.good)
true
0b07faeed17c71745c16e7131ddcc19bca79dd7b
yeeshenhao/Web
/2011-T1 Python/yeesh_p02/yeesh_p02_q06.py
609
4.59375
5
## Filename: yeesh_p02_q06.py ## Name: Yee Shen Hao ## Description: Write a program that sorts three integers. The integers are entered from standard input and ##stored in variables num1, num2, and num3, respectively. The program sorts the numbers ##so that num1 > num2 > num3. The result is displayed as a sorted list in descending order # User input num1 = int(input("Enter 1st integer:")) num2 = int(input("Enter 2nd integer:")) num3 = int(input("Enter 3rd integer:")) #Create list sort = [num1,num2,num3] #Print print("In descending order:", sorted(sort, reverse=True)) end = input("Press ENTER to exit")
true
c3b4bb152fe1aac639fc8c0767a44fae9e119cb8
gusun0/data-structures
/dictionaries.py
352
4.1875
4
mydict = {"name": "max", "age": 28, "city": "New York"} print(mydict) for key, value in mydict.items(): print(key, value) ''' try: print(mydict["lname"]) except: print('error') ''' ''' mydict2 = dict(name="mary", age=27, city="boston") print(mydict2) value = mydict['name'] print(value) mydict["lastname"] = "roger" print(mydict) '''
false
a26f57626165a2dec8c1ab86e68d862d6e1639f3
UgeneGorelik/Python_Advanced
/ContexManagerStudy.py
1,623
4.40625
4
from sqlite3 import connect #with means in the below example: #open file and close file when done #means with keyword means start with something #and in the end end with something with open('tst.txt') as f: pass #we declare a class that will runn using context manager type implementation class temptable: def __init__(self,cur): self.cur=cur #this will happen on instantiating the class def __enter__(self): print("__enter__") #sqllite create table self.cur.execute('create table points(x int, y int)') #this happen when instantation ends def __exit__(self, exc_type, exc_val, exc_tb): print("_exit_") #sqllite drop table self.cur.execute('drop table points') with connect('test.db') as conn: #declare Sqllite cursor for running DB queries cur = conn.cursor() #here we start instantiationg the temptable class so __enter__ from the temptable class will run with temptable(cur): #run insert to DB query cur.execute('insert into points (x, y) values(1, 1)') cur.execute('insert into points (x, y) values(1, 2)') cur.execute('insert into points (x, y) values(2, 1)') cur.execute('insert into points (x, y) values(2, 2)') # run select to DB query for row in cur.execute("select x, y from points"): print(row) for row in cur.execute('select sum(x * y) from points'): print(row) # here we end instantiationg the temptable class so exit from the temptable class will run
true
5e28de8f0613ba5ae0f50dc0c019c8716e6e4e09
mdimovich/PythonCode
/Old Tutorial Code/pythonTut27 (Recursion).py
602
4.1875
4
# Recursive Functions in Python # Recursive Factorial Function def factorial(num): if num <= 1: return 1 else: result = num * factorial(num-1) return result print(factorial(4)) # 1, 1, 2, 3, 5, 8, 13 # Fibonacci Sequence: Fn = Fn-1 + Fn-2 # Where F0 = 0 and F1 = 1 def fibonacci(num): if num == 0: return 0; elif num == 1: return 1; else: result = fibonacci(num-1)+fibonacci(num-2) return result amount = int(input("Enter the numer of fibonacci numbers you want: ")) for i in range(1, amount+1): print(fibonacci(i))
true
e0a3095c64fd1e4fddb49f2dff25ef0b1b829e04
mdimovich/PythonCode
/Old Tutorial Code/pythonTut4.py
737
4.34375
4
#Enter Calculation: 5 * 6 # 5*6 = 30 #Store the user input of 2 numbers and the operator of choice num1, operator, num2 = input("Enter Calculation ").split() #Convert the strings into integers num1 = int(num1) num2 = int(num2) # if + then we need to provide output based on addition #Print result if operator == "+": print("{} + {} = {}".format(num1, num2, num1+num2)) elif operator == "-": print("{} - {} = {}".format(num1,num2,num1-num2)) elif operator == "*": print("{} * {} = {}".format(num1, num2, num1 * num2)) elif operator == "/": print("{} / {} = {}".format(num1,num2, num1/num2)) elif operator == "%": print("{} % {} = {}".format(num1,num2, num1%num2)) else: print("Use either + - * / or % next time")
true
1730623fc10aa70a47b2e1cc3fe5aa42ac08ee59
mdimovich/PythonCode
/Old Tutorial Code/pythonTut3.py
328
4.25
4
#Problem: Receive Miles and Convert To Kilometers #km = miles * 1.60934 #Enter Miles, Output 5 Miles Equals 8.04 Kilometers miles = input ("Enter Miles: ") #Convert miles to integer miles = int(miles) #Kilometer Equation kilometers = miles * 1.60934 #Data Output print("{} Miles equals {} Kilometers".format(miles, kilometers))
true
5956dee8f7bd60bfcddd0f74bd487ae132c70547
devSubho51347/Python-Ds-Algo-Problems
/Linked list/Segrate even and odd nodes in a linked list.py
1,884
4.125
4
## Creation of a node of linked list class Node: def __init__(self,data): self.data = data self.next = None # Method to create the linked list def create_linked_list(arr): head = None tail = None for ele in arr: newNode = Node(ele) if head is None: head = newNode tail = newNode else: tail.next = newNode tail = newNode return head # Method to print the linked list def print_linked_list(head): while head is not None: if head.next is None: print(head.data) break else: print(head.data, end = " ->") head = head.next def sort_even_odds(head): first_odd_node = None prev_even_node = None head1 = head if head.next is None: return head if head1.data % 2 != 0: first_odd_node = head1 prev = None current = None while head.next is not None: prev = head current = prev.next if (current.data % 2 != 0) and (prev.data % 2 == 0): prev_even_node = prev first_odd_node = current head = head.next elif (prev.data % 2 != 0) and (current.data % 2 == 0): if head1.data % 2 != 0: prev.next = current.next current.next = first_odd_node head1 = current prev_even_node = current else: prev.next = current.next current.next = first_odd_node prev_even_node.next = current prev_even_node = current else: head = head.next return head1 arr = [int(x) for x in input().split()] head = create_linked_list(arr) print_linked_list(head) new_head = sort_even_odds(head) print("Even and Odd Linked List") print_linked_list(new_head)
true
aeae7d9948ca357f80b8c955e078b3f8dd227677
devSubho51347/Python-Ds-Algo-Problems
/Linked list/AppendLastNToFirst.py
1,644
4.1875
4
# Description ''' You have been given a singly linked list of integer along with an integer 'N'. Write a function to append the last 'N' nodes towards the front of the singly linked list and returns the new head to the list. ''' # Solved question using two pointer approach def AppendLastToFirst(head,n): ptr1 = head ptr2 = head head1 = head head2 = head while head.next is not None: if n > 0: ptr1 = head.next head = head.next n = n - 1 elif n == 0: ptr1 = head.next ptr2 = head1.next head = head.next head1 = head1.next if n > 0: return head2 ptr1.next = head2 head = ptr2.next ptr2.next = None return head class Node: def __init__(self,data): self.data = data self.next = None # Method to create the linked list def create_linked_list(arr): head = None tail = None for ele in arr: newNode = Node(ele) if head is None: head = newNode tail = newNode else: tail.next = newNode tail = newNode return head # Method to print the linked list def print_linked_list(head): while head is not None: if head.next is None: print(head.data) break else: print(head.data, end = " ->") head = head.next arr = [int(x) for x in input().split()] n = int(input()) head = create_linked_list(arr) print_linked_list(head) print("New Linked List") new_head = AppendLastToFirst(head,n) print_linked_list(new_head)
true
c98a67c653cf3adfad0b2d1274a33f396fc6c8ac
mallikasinha/python-basic-programs
/stringFormatting.py
926
4.21875
4
age = 24 print("My age is" + str(age) + "years")#str convert integer to string print("My age is {0} year".format(age)) #replacement field print("there are {0} days in {1} ,{2} {3} {4}".format(31, "jan", "feb", "march", "may")) print("""Jan: {2} Feb: {0} March: {2} April: {1} June: {1} July: {2} August: {2} September: {1} October: {2} November: {1} December: {2} """.format(28,30,31)) print("My age is %d year" % age) print("My age is %d %s, %d, %s" %(age, "year" , 6,"month")) #used in python 2 for i in range(1, 12): print("No. %2d squared is %4d and cubed is %d"%(i, i**2, i**3)) print("PI is approximately %12.50f" %(22 / 7)) for i in range(1, 12): print("No. {0:2} squared is {1:4} and cubed is {2:3}".format(i, i**2, i**3)) print("PI is approximately {0:12.50}".format(22 / 7)) for i in range(1, 12): print("No. {} squared is {} and cubed is {}".format(i, i**2, i**3))
false