blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
6ca27cb7812b97cfe3e1cbaefbbca44b299a0e71
Ariful42/My_First_Python_Exercises
/04 ' if ' Statements.py
2,919
4.28125
4
'''Conditional Tests: Write a series of conditional tests Print a statement describing each test and your prediction for the results of each test ''' cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) Pizzas = ['tuna', 'sardin', 'hemonta', 'fish'] for Pizza in Pizzas: if Pizza == 'fish': print(Pizza.upper()) else: print(Pizza.title()) ''' Imagine an alien was just shot down in a game Create a variable called alien_color and assign it a value of 'green', 'yellow', or 'red': • Write an if statement to test whether the alien’s color is green If it is, print a message that the player just earned 5 points • Write one version of this program that passes the if test and another that fails (The version that fails will have no output ) • If the alien’s color is green, print a statement that the player just earned 5 points for shooting the alien. • If the alien’s color isn’t green, print a statement that the player just earned 10 points. • Write one version of this program that runs the if block and another that runs the else block. ''' alien_colors = ['green', 'red', 'yellow'] if "green" in alien_colors: print('The Player has earned 5 ponits') if "orrange" not in alien_colors: print('The player has earned 10 points') if 'blue' in alien_colors: print("Player has upgraded") else: print('sorry, you are unable\n \n') if 'green' not in alien_colors: print('nothing') else: print('The player has earned 5 points') if 'red' in alien_colors: print('The player has earned 10 points') if 'yellow' not in alien_colors: print('nothing') elif 'yellow' in alien_colors: print('The player has earned 15 points\n \n') '''Write an if-elif-else chain that determines a person’s stage of life Set a value for the variable age, and then: • If the person is less than 2 years old, print a message that the person is a baby • If the person is at least 2 years old but less than 4, print a message that the person is a toddler • If the person is at least 4 years old but less than 13, print a message that the person is a kid • If the person is at least 13 years old but less than 20, print a message that the person is a teenager • If the person is at least 20 years old but less than 65, print a message that the person is an adult • If the person is age 65 or older, print a message that the person is an elder''' age = 65 if age < 2: print('The person is a baby') elif age < 4: print('The person is a Tadler') elif age < 13: print('The person is a Kid') elif age < 20: print('The person is a Teenager') elif age < 65: print('The person is an Adult') elif age >64: print('The person is a Elder')
true
483e1e2774a0fecc1d47f5b01e04abb235a948a9
MorisDe/Python
/Finding the numbers in a matrix.py
641
4.1875
4
# importing libraiers import pandas as pd import numpy as np a = [[1,3,3,4,3], [2,3,1,3,3], [3,1,2,7,1], [3,4,4,3,3]] # converting them into an readable format rc=pd.DataFrame(a) print(rc) # renaming the col in order to better execute the solution col=['R0','R1','R2','R3','R4'] rc.columns=col print(rc) # calculating the sum of 3's in the column column=np.sum(rc==3) column_answer=list(column) print("The total number of 3's in a column are: ",column_answer) # calculating the sum of 3's in the rows rows=(np.sum(rc==3,axis=1)) rows_answer=list(rows) print("The total number of 3's in a row are: ",rows_answer)
true
54f6c8f4574ea18a89d32e1ffd42e10ce294a4e0
vyasshivam/python-practice
/ex2.py
1,050
4.46875
4
# -*- coding: utf-8 -*- """ 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? Extras: 1. If the number is a multiple of 4, print out a different message. 2. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. """ number = int(input('Enter any number : ')) if(number % 4 == 0): print('%s is multiple of 4'% (str(number))) elif(number % 2 == 0): print('%s is even number'% (str(number))) else: print('%s is odd number'% (str(number))) num = int(input('Enter another number : ')) check = int(input('Enter a number you would like to divide above number with : ')) if(num % check == 0): print('%s is evenly divided by %s' % (str(num), str(check))) else: print('%s is not evenly divided by %s' % (str(num), str(check)))
true
56624cf9d9dc1547170faeae6a44626c651ebd43
vyasshivam/python-practice
/ex13.py
714
4.5
4
# -*- coding: utf-8 -*- """ Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate. (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) """ def get_integer(): return int(input('Enter a number : ')) a = [] for x in range(0,get_integer()): if(x==0): a.append(1) elif(x==1): a.append(1) else: a.append(a[-1] + a[-2]) print(a)
true
9b0fdb55cffff020ca80cb2c8f892c5e20308ddc
vpatov/ProjectEuler
/python/projecteuler/complete/01-50/p009.py
681
4.21875
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ import time startTime = time.perf_counter() a = 1 b = 2 found = False while (a < 1000 and not found): while (b < 1000): if (a**2 + b**2 == (1000-b-a)**2) : #print(a,b,(1000-b-a)) print(a * b * (1000-b - a)) found = True break b += 1 a += 1 b = a + 1 endTime = time.perf_counter() print("Time elapsed:", '{:0.6f}'.format(endTime - startTime), "seconds.")
true
86580e770462cb204c4a504128912f2ccfc0f790
ilealm/data-structures-and-algorithms-python
/dsa/challenges/quick_sort/quick_sort.py
2,433
4.21875
4
''' code references: https://www.youtube.com/watch?v=WaNLJf8xzC4 https://visualgo.net/en/sorting https://www.geeksforgeeks.org/python-program-for-quick_sort/ ''' def quick_sort(arr, start_index, end_index): if start_index < end_index: pivot = partition(arr,start_index, end_index) print('pivot', pivot, start_index, end_index) quick_sort(arr, start_index, pivot-1) # taking all from the pivot to the left quick_sort(arr, pivot+1, end_index) # taking all from the pivot to the right return arr # returns the next position of the lowest founded value def partition(arr,start_index, end_index): pointer_left = ( start_index-1 ) # index of smaller element, that I already visited pivot = arr[end_index] for pointer_right in range(start_index , end_index): # swap values if arr[pointer_right] <= pivot: pointer_left = pointer_left + 1 arr[pointer_left],arr[pointer_right] = arr[pointer_right],arr[pointer_left] arr[pointer_left+1],arr[end_index] = arr[end_index],arr[pointer_left+1] # print(i+1) return ( pointer_left + 1 ) def quick_sort_craking(arr, left, right): index = partition_craking(arr, left, right) # sort left half if left < index-1: quick_sort_craking(arr, left, index-1) # sort right half if index < right: quick_sort_craking(arr, index, right) def partition_craking(arr, left, right): pivot = arr[(left + right) // 2] # pivot while left <= right: # find the element on left that should be on the right (greater than pivot) # aka find the possition of the first element that is GRATER than the pivot, from the LEFT while (arr[left] < pivot): left += 1 # find the element on the right that should be on the left (lower than pivot) # aka find the possition of the first element that is LESS than the pivot, from the RIGHT while (arr[right] > pivot): right -= 1 #swap elements arr[left],arr[right] = arr[right],arr[left] # Move right indices left += 1 right -= 1 # how do I know I need to return left?. # left is the middle always return left if __name__ == "__main__": # print(quick_sort([10, 5, -3, 12, 1, 30, 7],0, 6) ) array =[10, 15, -3, 12, 1, 30, 7] quick_sort_craking(array,0, len(array)-1) print(array)
true
e44b45f9d5d7475567bf93ac6a8f8beaa57a636c
jayeshkrt/pythondatastructures
/linked_list_reversal.py
1,044
4.21875
4
# reverse a singly linked list class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): current = self.head if self.head is None: self.head = Node(data) return else: while current.next: current = current.next newNode = Node(data) current.next = newNode def reverse(self): currentnode = self.head prev = None while currentnode: nxt = currentnode.next currentnode.next = prev prev = currentnode currentnode = nxt self.head = prev def printList(self): current = self.head while current: print(current.data) current = current.next if __name__ == "__main__": ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) ll.append(4) ll.reverse() ll.printList()
false
0c76b5e9dc8dfecb8c3628ede74eb19c7661b746
rupikarasaili/Exercise
/LabFour/six.py
289
4.28125
4
''' write a Python program to count the number of even and odd numbers from a series of numbers. ''' x= [2,4,5,6,9,11,13] count_even=0 count_odd=0 for i in x: if i%2==0: count_even+= 1 else: count_odd+= 1 print(f"odd numbers: {count_odd} even number: {count_even}")
true
97f39b3e9e1c68cf867d3039d20b91a05b308419
rupikarasaili/Exercise
/LabFour/ten.py
352
4.1875
4
''' Write a Python program that accepts a string and calculate the number of digits and letters ''' string=input("enter a string: ") count_digit=0 count_letter=0 for i in string: if i.isdigit(): count_digit+= 1 elif i.isalpha(): count_letter+=1 print(f"the number of digits: {count_digit} the number of letters: {count_digit}")
true
129b07b34f84fbdd8842da1bc512cb7409d2bce8
rupikarasaili/Exercise
/LabFour/three.py
468
4.28125
4
''' Write a Python program to guess a number between 1 to 9. Note : User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, user will get a "Well guessed!" message, and the program will exit. ''' import random random_num=random.randint(1,9) guess= int(input("enter a guess: ")) i = 1 while random_num!=guess: guess=int(input("guess again: ")) i= i+1 print("well guessed!")
true
7db186a645f3d8299c5632136dd98d6cbbd05282
rupikarasaili/Exercise
/LabThree/eleven.py
491
4.3125
4
''' Write a python program to check whether the number is Armstrong number or not using function: [Hint: 153 - 1*1*1 + 5*5*5 + 3*3*3] ''' def armstrong(digit): sum = 0 # find the sum of the cube of each digit n = num while n > 0: digit = n % 10 sum += digit ** 3 n //= 10 # display the result if num==sum: return True else: return False # take input from the user num = int(input("Enter a number: ")) print(armstrong(num))
true
f392d085ada85ecfe6bde2596e6198dc6658bd46
anterra/learning-python
/functions/return.py
517
4.21875
4
#return statement #the return statement is used to break out of a function #can optionally return a value as well def maximum(x, y): if x > y: return x elif x == y: return "the numbers are equal" else: return y print(maximum(2, 3)) #a return statement without a value is equivalent to return None #None is a special type in Python that represents nothingness #note for this example: there's actually a 'max' function built-in to python that finds maximum, so use that whenever
true
59f6f161e94ee5c01aa75ad8c2ec971005d890b8
anterra/learning-python
/control_flow.py
2,922
4.34375
4
#3 control flow statements: if, for, and while #if number = 23 guess = int(input("Enter an integer : ")) #input function -- reusable piece of program. takes user input #int is a class -- here, it converts our string input into an integer if guess == number: #conditional statements in Python are followed by colon #new block indicates arguments #no brackets needed print("Congratulations, you guessed it.") print("(but you do not win any prizes!)") elif guess < number: print("No, it is a little higher than that.") else: print("No, it is a little lower than that") print("Done") #this last statement is always executed after the if statement is executed #while #allows you to repeatedly execute block of statements as long as a condition is true #looping statement #can have optional else clause number = 23 running = True while running: guess = int(input("Enter an integer: ")) if guess == number: print("Congratulations, you guessed it.") #this causes the while loop to stop running = False elif guess < number: print("No, it is a little higher than that.") else: print("No, it is a little lower than that.") else: print("The while loop is over.") print("Done") #for #looping statement which iterates over a sequence of objects for i in range(1, 5): print(i) else: print("The for loop is over") #iterates up to the end range, does not include it #iterates by 1 by default; add 3rd term to range i.e. (range(1, 5, 2)) to iterate by a different nubmer #generates one number at a time. to get full list: print(list(range(5))) #break statement #used to stop execution of a loop even if condiditon has not become false #if you break -- any else block is not executed while True: s = input("Enter something: ") if s == "quit": break print("Length of the string is", len(s)) print("Done") #continue #used to tell python to skil the rest of the statements in the current loop block and go to next iteration while True: s = input("Enter something: ") if s == "quit": break if len(s) < 3: print("Too small") continue print("Input is of sufficient length") #etc. #should the break statement for quit always come first? #my inclination would be to define statements first and then lastly give condition that if quit is provided, break.. #testing whether that would be functionally the same: while True: s = input("Enter something: ") if len(s) < 3: print("Too small") continue print("Input is of sufficient length") if s == "quit": break #seems to run the same! but thinking about it, I agree that its best to check whether we should just quit first #saves processing power that would be used checking all other conditions/executing any other statements if right away its ready to break. #short-circuit evaluation!
true
e70d3c5c135cc9cd625dfc88628a7441a3226997
imgagandeep/hackerrank
/python/built-ins/005-any-or-all.py
960
4.15625
4
""" Task You are given a space separated list of integers. If all the integers are positive, then you need to check if any integer is a palindromic integer. Input Format The first line contains an integer N. M is the total number of integers in the list. The second line contains the space separated list of N integers. Constraints 0 < N < 100 Output Format Print True if all the conditions of the problem statement are satisfied. Otherwise, print False. Sample Input: 5 12 9 61 5 14 Sample Output: True Explanation Condition 1: All the integers in the list are positive. Condition 2: 5 is a palindromic integer. Hence, the output is True. Can you solve this challenge in 3 lines of code or less? There is no penalty for solutions that are correct but have more than 3 lines. """ # Solution: n, item = int(input()), input().split() print(all([int(i) > 0 for i in item]) and any([j == j[::-1] for j in item]))
true
a70f141f5991ae013ee08942c8a803a9f6ab24ed
imgagandeep/hackerrank
/python/python-functionals/003-reduce-function.py
1,617
4.3125
4
""" Given a list of rational numbers,find their product. Concept The reduce() function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3] and you have to find its sum. >>> reduce(lambda x, y : x + y,[1,2,3]) 6 You can also define an initial value. If it is specified, the function will assume initial value as the value given, and then reduce. It is equivalent to adding the initial value at the beginning of the list. For example: >>> reduce(lambda x, y : x + y, [1,2,3], -3) 3 >>> from fractions import gcd >>> reduce(gcd, [2,4,8], 3) 1 Input Format First line contains n, the number of rational numbers. The iᵗʰ of next n lines contain two integers each, the numerator(Nᵢ) and denominator(Dᵢ) of the iᵗʰ rational number in the list. Constraints → 1 ≤ n ≤ 100 → 1 ≤ Nᵢ, Dᵢ ≤ 10⁹ Output Format Print only one line containing the numerator and denominator of the product of the numbers in the list in its simplest form, i.e. numerator and denominator have no common divisor other than 1. Sample Input: 3 1 2 3 4 10 6 Sample Output: 5 8 """ # Solution: from fractions import Fraction from functools import reduce def product(fracs): t = Fraction(reduce(lambda x, y: x * y, fracs)) return t.numerator, t.denominator if __name__ == '__main__': fracs = [] for _ in range(int(input())): fracs.append(Fraction(*map(int, input().split()))) result = product(fracs) print(*result)
true
907b2542961a3ee524450b800a625d0aae0a553e
imgagandeep/hackerrank
/python/regex-and-parsing/006-regex-substitution.py
1,254
4.15625
4
""" Task You are given a text of N lines. The text contains && and || symbols. Your task is to modify those symbols to the following: && → and || → or Both && and || should have a space " " on both sides. Input Format The first line contains the integer, N. The next N lines each contain a line of the text. Constraints 0 < N < 100 Neither && nor || occur in the start or end of each line. Output Format Output the modified text. Sample Input: 11 a = 1 b = input() if a + b > 0 && a - b < 0: start() elif a*b > 10 || a/b < 1: stop() print set(list(a)) | set(list(b)) #Note do not change &&& or ||| or & or | #Only change those '&&' which have space on both sides. #Only change those '|| which have space on both sides. Sample Output: a = 1 b = input() if a + b > 0 and a - b < 0: start() elif a*b > 10 or a/b < 1: stop() print set(list(a)) | set(list(b)) #Note do not change &&& or ||| or & or | #Only change those '&&' which have space on both sides. #Only change those '|| which have space on both sides. """ # Solution: import re for _ in range(int(input())): print(re.sub(r'(?<= )(&&|\|\|)(?= )', lambda x: 'and' if x.group() == '&&' else 'or', input()))
true
58ca9f5af796a136bd362c68bcf62bbfc3c4c1e1
imgagandeep/hackerrank
/regex/applications/013-utopian-identification-number.py
1,559
4.3125
4
""" A new identification number is given for every Citizen of the Country Utopia and it has the following format. → The string must begin with between 0-3 (inclusive) lowercase letters. → Immediately following the letters, there must be a sequence of digits (0-9). The length of this segment must be between 2 and 8, both inclusive. → Immediately following the numbers, there must be atleast 3 uppercase letters. Your task is to find out if a given identification number is valid or not. Input Format The first line contains N, N lines follow each line containing an identification number. Constraints 1 <= N <= 100 Output Format For every identification number, please print VALID if the identification number is valid and print INVALID otherwise. Sample Input: 2 abc012333ABCDEEEE 0123AB Sample Output: VALID INVALID Explanation The first testcase is valid as it starts with 3 letters, followed by 6 integers (max of 8 and min of 2) and ends with more than 3 uppercase letters. The second testcase is invalid as it satisfies the first (at least 0 lowercase letters) and the second condition (alteast 2 integers) but fails on the third condition. Viewing Submissions You can view others' submissions if you solve this challenge. Navigate to the challenge leaderboard. """ # Solution: import re n = int(input()) regex = r'^[a-z]{0,3}\d{2,8}[A-Z]{3,}$' for _ in range(n): string = input() if(re.search(regex, string)): print('VALID') else: print('INVALID')
true
2f4d085f3da588683468d707d190c4cc69db17a8
imgagandeep/hackerrank
/python/sets/009-symmetric-difference.py
1,604
4.125
4
""" Task Students of District College have subscriptions to English and French newspapers. Some students have subscribed to English only, some have subscribed to French only, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to either the English or the French newspaper but not both. Input Format The first line contains the number of students who have subscribed to the English newspaper. The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper. The third line contains the number of students who have subscribed to the French newspaper. The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper. Constraints 0 < Total number of students in college < 1000 Output Format Output total number of students who have subscriptions to the English or the French newspaper but not both. Sample Input: 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 Sample Output: 8 Explanation The roll numbers of students who have subscriptions to English or French newspapers but not both are: 4, 5, 7, 9, 10, 11, 21 and 55. Hence, the total is 8 students. """ # Solution: a = int(input()) english = set(map(int, input().split())) b = int(input()) french = set(map(int, input().split())) print(len(english.symmetric_difference(french)))
true
b6c123839ee60cbb2752532c424aa9c30db073c0
imgagandeep/hackerrank
/python/sets/001-intro-sets.py
1,114
4.4375
4
""" Task Now, let's use our knowledge of sets and help Mickey. Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse. Formula used: Average = Sum of Distinct Heights / Total Number of Distinct heights Input Format: The first line contains the integer, N, the total number of plants. The second line contains the N space separated heights of the plants. Constraints 0 < N ≤ 100 Output Format: Output the average height value on a single line. Sample Input: 10 161 182 161 154 176 170 167 171 170 174 Sample Output: 169.375 Explanation Here, set ([154, 161, 167, 170, 171, 174, 176, 182]) is the set containing the distinct heights. Using the sum() and len() functions, we can compute the average. Average = 1355 / 8 = 169.375 """ # Solution: def average(array): return sum(set(array)) / len(set(array)) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result)
true
b8bb91fb11ef5c57a368c44c0b61c41efd2ac577
imgagandeep/hackerrank
/python/numpy/002-shape-and-reshape.py
459
4.3125
4
""" Task You are given a space separated list of nine integers. Your task is to convert this list into a 3x3 NumPy array. Input Format A single line of input containing 9 space separated integers. Output Format Print the 3x3 NumPy array. Sample Input: 1 2 3 4 5 6 7 8 9 Sample Output: [[1 2 3] [4 5 6] [7 8 9]] """ # Solution: import numpy as np a = np.array(list(map(int, input().split()))) a.shape = (3, 3) print(a)
true
bb6f843e3b31e56bab3403880b437905d440bec9
imgagandeep/hackerrank
/python/built-ins/004-athlete-sort.py
1,715
4.25
4
""" You are given a spreadsheet that contains a list of N athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the th Kᵗʰ attribute and print the final resulting table. Note that K is indexed from 0 to M - 1, where M is the number of attributes. Note: If two attributes are the same for different rows, for example, if two atheletes are of the same age, print the row that appeared first in the input. Input Format The first line contains N and M separated by a space. The next N lines each contain M elements. The last line contains K. Constraints 1 ≤ N, M ≤ 1000 0 ≤ K ≤ M Each element ≤ 1000 Output Format Print the N lines of the sorted table. Each line should contain the space separated elements. Check the sample below for clarity. Sample Input: 5 3 10 2 5 7 1 0 9 9 9 1 23 12 6 5 9 1 Sample Output: 7 1 0 10 2 5 6 5 9 9 9 9 1 23 12 Explanation The details are sorted based on the second attribute, since K is zero-indexed. """ # Solution 1: import math import os import random import re import sys if __name__ == '__main__': nm = input().split() n = int(nm[0]) m = int(nm[1]) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) k = int(input()) p = sorted(arr, key=lambda row:row[k]) for i in range(len(p)): for j in range(len(p[i])): print(p[i][j], end=' ') print() # Solution 2: # n, m = map(int, input().split()) # rows = [input() for _ in range(n)] # k = int(input()) # for row in sorted(rows, key=lambda row: int(row.split()[k])): # print(row)
true
85d398f5893111a6b460034f488d2a5333810a97
ogulcangumussoy/Python-Calismalarim
/Dongu-Yapilari/Uygulamalar/fibonacci_serisi.py
275
4.21875
4
""" ******************** Fibonacci Serisi yeni bir sayıyı önceki iki sayının toplamı şeklinde oluşturur. 1,1,2,3,5,8,13,21,34........ ******************** """ a=1 b=1 fibonacci = [a,b] for i in range(0,20): a,b = b,a+b fibonacci.append(b) print(fibonacci)
false
f66d708e0e79a407d3d410df91d0d2acf990b0b1
ogulcangumussoy/Python-Calismalarim
/Ileri-Seviye-Veri-Yapilari-ve-Objeler/Uygulama/ileri-seviye-stringler.py
1,687
4.3125
4
#upper tüm harfleri büyüğe #lower print("python".upper()) print("PyThon".lower()) #replace metodu(stringdeki x değerini y ile değiştiriyor) print("Herkes ana bacı gardaş".replace("a","o")) # a ve o değişti. print("Python programlama Dili".replace(" ","-")) print("Kunduz".replace("duz","zun"))#kalıplar da değiştirilebiliyor. #startswith("x") x ile mi başlıyor. #endswith("x") x ile mi bitiyor. print("Python".startswith("Py")) print("Python".endswith("gon")) #split ile string parçalanıp listeye atılabilir. liste="Python programlama dili".split(" ") print(liste) liste2="Python-Programlama-Dİli".split("-") print(liste2) #strip ile boşluk silme yapabiliriz. lstrip--> sol boşluk rstrip-->Sağ boşluk siler. print(" Python ".strip()) print(" Python ".rstrip()) print(("<<<<<<<<<<<<<<<<<<<<<<<<Python2>>>>>>>>>>>>>>>>>>>>>>>>>>>>>".rstrip(">").lstrip("<"))) #join metodu liste=["21","02","2014"] print("/".join(liste)) #seçtiğimiz bir şeyi dizinin parçalarına ekleyip toplu çıktı alabiliriz. 21/02/2014 gibi liste2=["T","B","M","M"] print(".".join(liste2)) #count(x) metodu seçilen şeyin metinde kaç kere geçtiğini döndürür. #count(x,index) metodu index değerinden itibaren x kaç kere geçiyor diye bakar. print("ada kapısı yandan çarklı".count("a")) print("ada kapısı yandan çarklı".count("a",3))#3.indisten sonra bak. #find(x) x değerini string içerisinde arar ilk bulduğu indisin nosunu verir. #rfind(x) soldan bakıp ilk bulduğunu yazar eğer bulamazsa -1 döndürür ikisi de print("araba".find("a")) print("araba".rfind("b")) print("araba".find("s")) #-1 döner
false
817dc61178bff7577ca6db7209f37b1f668a8e4f
prastut/NLP
/POS/pos.py
620
4.3125
4
#!/usr/bin/env python import nltk, string # Set of all available punctuations. Set because don't want repitions. punctuation = set(string.punctuation) def pos_tag(text): ''' Function for returning parts of speech for the text provided. Steps: 1. First word tokenize the text. 2. Then check for punctuation. 3. Lowercase the words obtained after removing punctuation 4. Now pos_tag the subset of words thus obtained. ''' pos = nltk.pos_tag([word.lower() for word in nltk.wordpunct_tokenize(text) if word not in punctuation]) return pos
true
559a86996de62b784ea7a3b195d203955845306b
Hezhang12138/unit_five
/assignment_unit_five.py
938
4.15625
4
# assignment_unit_five # 10/18/2018 # "this is an interesting game, and I finally understand how loop exactly works" import random def number(): correct_answer = random.randint(1, 100) return correct_answer def main(): while True: answer1 = input("Do you want to start a game? put in 'y' or 'n'") if answer1 is "n": print("ok") break elif answer1 is "y": print("let's start") answer2 = number() while True: users_guess = int(input("Give a number you want to guess.")) if users_guess == answer2: print("Congratulation!") break elif users_guess > answer2: print("your guess was too high") else: print("Your guess was too low") else: print("your answer is not valid") main()
true
a2410c6515e7af9b20f50ecf7e4ef43646a37f43
bargavi-dev/friyay
/fizzbuzz-exercise.py
669
4.28125
4
#take a number input and print out the range from the number 1 to that number input given_num = int(input('What is the number? ')) #for any number input that can be divided by BOTH 3 and 5, print "fizzbuzz" for number in range(1, given_num + 1): if number % 3 == 0 and given_num % 5 == 0: print(str(number) + ": fizz buzz") #for any number input that can be divided by 3, print "fizz" elif number % 3 == 0: print(str(number) + ": fizz") #for any number input that can be divided by 5, print "buzz" elif number % 5 == 0: print(str(number) + ": buzz") #if number input is not divisible by any of the numbers, then:
true
e713a9de2a206664b8f450002e27c066c7789777
indrajanambiar/roll-a-dice
/roll.py
1,221
4.15625
4
""" #dice rolling game > crete a program that accepts a total number of rolls (N) from the user > make N rolls and output the sum > eg: create a random choice if __name__ == "__main__": improvements >>> accept the number of users playing M accept their names roll dice N times for each player and output the winner """ import random import time from random import randint N = 3 def game(): m=int(input("number of players")) print('number of players is:',m) names = list() scores = list() for i in range(m): name= input("enter player name:") names.append(name) for name in names: score = get_user_input(name) scores.append(score) max_score = max(scores) winner = names[scores.index(max_score)] print('winner is :',winner) def get_user_input(name): print(f"Let's get to rolling, {name}!") score = roll_n_times(N) print(f"FINAL SCORE for {name} is", score) return score def roll_dice(): """ roll dice once and return the result """ return random.choice(range(1, 7)) def roll_n_times(n): sum = 0 for i in range(n): print("\nrolling dice.....") roll_value = roll_dice() print(f"you got a: {roll_value}") sum = sum + roll_value return sum if __name__ == "__main__": game()
true
9a47cd52d468e50035f86f866217cdf39aa87a84
dpinizzotto/pythonStudents
/ifLesson.py
723
4.25
4
#add if statements for the different things people type in age = int(input("Please enter your age: ")) if(age>=0 and age <12): print("You are still a kid") print() elif(age >= 12 and age <=19): print("You are a teenager") print() elif(age >=20 and age <35): print("You are a young adult") print() elif(age >=35 and age <65): print("You are an adult") print() else: print("You are old") print() hoursWorked = float(input("Enter your hours worked this week: ")) if hoursWorked <= 40: print("You did not work overtime!") else: print("you worked overtime!") day = input("what is your favourite day of the week? ").lower() if day == "monday": print("are you mad!!!!")
true
5185a717d637a496a817b61ceb225afa70020a95
dpinizzotto/pythonStudents
/variables.py
447
4.40625
4
# Mr Pinizzotto # Feb 10, 2020 # Learning Variables and Data Types # This code will show you how python understands making and using variables and then the differnt types of # variables we can use # make a string variable and then display first_name = "Daniel" print(first_name) #set a top speed and distance variable and then display topSpeed = 160 distance = 300 print("The top speed is") print(topSpeed) print("The distance is "+str(distance))
true
faee413bdb5752c8bb007541e3e5583bf4df4776
dpinizzotto/pythonStudents
/nestedLoopTable.py
677
4.28125
4
rows = int(input("How many rows: ")) columns = int(input("How many columns: ")) skip = input("Do you want to count by 2's? ").lower() if skip == "yes": for x in range(1,rows+1,2): for y in range(1,columns+1,2): #this will print the cell coordinate print(f"({x},{y})", end="\t") #this will print a newline at the end of the row print("") else: for x in range(1,rows+1): for y in range(1,columns+1): #this will print the cell coordinate print(f"({x},{y})", end="\t") #this will print a newline at the end of the row print("")
true
18a26199063da9ed72d8e0d10a029b0cb4a7c944
bihellzin/monitoria-p1
/aulas-monitoria/07-10/6.py
336
4.15625
4
''' Escreva um programa que diz se uma lista inserida está com todos os seus elementos em ordem(crescente) ''' lista = [1, 2, 3, 4, 5] ordenado = True for i in range(len(lista)-1): if lista[i] > lista[i+1]: ordenado = False if ordenado: print('A lista esta ordenada') else: print('A lista nao está ordenada')
false
daa90d7b962e38027dc421716422a49236b8f4e5
bihellzin/monitoria-p1
/exercicios/estruturas-condicionais/enem-2019-metereologia/resposta.py
418
4.15625
4
temperatura = float(input('Insira a temperatura em graus Celsius: ')) umidade_ar = float(input('Insira a porcentagem referente a umidade relativa do ar: ')) if temperatura < 10 and umidade_ar < 40: print('ALERTA CINZA') elif 35 <= temperatura <= 40 and umidade_ar < 30: print('ALERTA LARANJA') elif temperatura > 40 and umidade_ar < 25: print('ALERTA VERMELHO') else: print('Nenhum alerta emitido')
false
0ab8bec71bcaacef03b3926393da97c90157198e
bihellzin/monitoria-p1
/aulas-monitoria/18-03/exercicios/01-03.py
723
4.125
4
print('1. Quantos dias tem um ano bissexto ? ') resposta1_correta = 366 resposta1_usuario = int(input('')) if resposta1_correta == resposta1_usuario: print('Você acertou a pergunta') else: print('Você errou a pergunta') print('') print('2. Qual a capital de Rondônia ? ') resposta2_correta = 'Porto Velho' resposta2_usuario = input('') if resposta2_correta == resposta2_usuario: print('Você acertou a pergunta') else: print('Você errou a pergunta') print('') print('3. Em que ano o Brasil perdeu de 7x1 ? ') resposta3_correta = 2014 resposta3_usuario = int(input('')) if resposta3_correta == resposta3_usuario: print('Você acertou a pergunta') else: print('Você errou a pergunta')
false
49cc5b4fdd34716708e81aa92587bd73a2ec5803
lapthorn/econ
/monty-hall.py
2,360
4.28125
4
#!/usr/bin/env python3 import random DEBUG=False # TODO turn the monty hall bit into a function # TODO PEP8 the whole thang # basic parameters BOXES=3 # the number of boxes (3 for classic Monty Hall) RUNS=30000 # number of simulation runs # initialize the counters CHANGEWINS=0 # number of wins if contestent changes STICKWINS=0 # number of wins if contestent sticks ROUNDS=0 # number of rounds so far CHANGE=False # strategy for player - change or stick - might allow both print ("Simulating the Monty Hall problem with", BOXES, "boxes, and", RUNS, "runs.") print () while (ROUNDS < RUNS): BOXSET={} # set for the possible boxes # generate the set of boxes for i in range(1,BOXES+1): BOXSET=set(BOXSET) | {i} MYBOXES=BOXSET # set of boxes for contestent if DEBUG: print ('Boxes:', BOXSET) # hide the car CAR=random.randint(1, BOXES) if DEBUG: print (' Car:', CAR) # contestent picks a random box PICK=random.randint(1, BOXES) if DEBUG: print (' Pick:', PICK) # monty needs to open an empty door # remove the CONTESTENT pick from the possible set BOXSET=BOXSET-{PICK} MYBOXES=MYBOXES-{PICK} # remove the CAR from the possible set BOXSET=BOXSET-{CAR} if DEBUG: print (' Left:', BOXSET) if DEBUG: print (' MYBOXES:', MYBOXES) # Monty now picks and shows an empty box. # There's either one or two boxes to choose from. # Pick one at random MONTYPICK=random.sample(set(BOXSET),1) if DEBUG: print (' Montypick:', MONTYPICK) # remove Monty's choice from the contestent set MYBOXES=MYBOXES-set(MONTYPICK) if DEBUG: print (' MYBOXES:', MYBOXES) # let's collapse the wave function (ie see who won!) # stickwins if (PICK==CAR): STICKWINS+=1 if DEBUG: print (' STICKWIN!') # changewins # pop the only remaining choice out of MYBOXES CHANGEPICK=MYBOXES.pop() if DEBUG: print (' CHANGEPICK:', CHANGEPICK) if (CHANGEPICK==CAR): CHANGEWINS+=1 if DEBUG: print (' CHANGEWIN!') ROUNDS+=1 # finish # the results print (' STICKWINS:', STICKWINS, STICKWINS/ROUNDS) print (' CHANGEWINS:', CHANGEWINS, CHANGEWINS/ROUNDS) print (' ROUNDS:', ROUNDS) print () if (CHANGEWINS > STICKWINS): print ("It's better to change") else: print ("It's better to stick")
true
c681d21a927c1a81c37175f041642bcd1ee8fbad
rowan-smith/CP1404-Practicals
/prac_01/shop_calculator.py
493
4.125
4
number_of_items = int(input("Please enter quantity of items: ")) while number_of_items < 0: print("Invalid number of items!") number_of_items = int(input("Please enter quantity of items: ")) total = 0 for i in range(number_of_items): item_price = float(input("Please enter item {}'s price: $".format(i + 1))) total += item_price if total > 100: discount = 10 / 100 * total total -= discount print("Total price for {} items is ${:.2f}".format(number_of_items, total))
true
a20f74e9ce66af30aa6f381465da18ed50ed6329
byuvraj/Solution_for_python_challanges
/Hacker_rank/hacker_rank_vally.py
659
4.15625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countingValleys' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER steps # 2. STRING path # def countingValleys(steps, path): # Write your code here ans =0 vally =0 for i in path: if i == 'D': vally-=1 if i=='U': vally+=1 print(vally) if vally == 0 and i == 'U': ans+=1 return ans if __name__ == '__main__': steps = int(input().strip()) path = input() result = countingValleys(steps, path)
true
ec3fbcf5e5e3cc76dd197ec6cfc422e0ff0aab80
ChavezCheong/MIT-6.0001
/ps4/ps4a.py
2,064
4.53125
5
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. ''' #Base case if len(sequence) == 1: return [sequence] #Run the recursion firstchar = sequence[0] runninglist = [] for sublist in get_permutations(sequence[1:]): wordlist = list(sublist) for i in range(len(wordlist)+1): newwordlist = wordlist.copy() newwordlist.insert(i, firstchar) newword = "".join(newwordlist) runninglist.append(newword) return runninglist if __name__ == '__main__': # #EXAMPLE # example_input = 'abc' # print('Input:', example_input) # print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) # print('Actual Output:', get_permutations(example_input)) # # Put three example test cases here (for your sanity, limit your inputs # to be three characters or fewer as you will have n! permutations for a # sequence of length n) example_input = 'abc' print('Input:', example_input) print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) print('Actual Output:', get_permutations(example_input)) example_input = 'ice' print('Input:', example_input) print('Expected Output:', ['ice', 'cie', 'cei', 'iec', 'eic', 'eci']) print('Actual Output:', get_permutations(example_input)) example_input = 'top' print('Input:', example_input) print('Expected Output:', ['top', 'tpo', 'otp', 'pot', 'pto', 'opt']) print('Actual Output:', get_permutations(example_input))
true
50606f47253cb0e361a2725f855dca82f675798e
ikostan/Exercism_Python_Track
/pythagorean-triplet/pythagorean_triplet.py
1,352
4.375
4
""" Given an input integer N, find all Pythagorean triplets for which a + b + c = N. For example, with N = 1000, there is exactly one Pythagorean triplet for which a + b + c = 1000: {200, 375, 425}. """ import math def triplets_with_sum(number) -> set: """ Given an input integer N, find all Pythagorean triplets for which: a + b + c = N. :param number: :return: """ return set(t for t in triplets_in_range(int(math.sqrt(number)), number) if sum(t) == number) def triplets_in_range(start: int, end: int) -> list: """ Returns all possible triplets within specific range :param start: :param end: :return: """ triplets = [] for b in range(end//4, end//2): for a in range(start, b): # calculate c c = int(math.sqrt(b ** 2 + a ** 2)) # check is a, b, c Pythagorean triplet if is_triplet([a, b, c]): triplets.append((a, b, c)) return triplets def is_triplet(triplet: list) -> bool: """ A Pythagorean triplet is a set of three natural numbers: {a, b, c} for which: a**2 + b**2 = c**2 and such that: a < b < c :param triplet: :return: """ return triplet[0] ** 2 + triplet[1] ** 2 == triplet[-1] ** 2
true
0baa774fc9322752ece73167748e6eb6fea42718
ikostan/Exercism_Python_Track
/queen-attack/queen_attack.py
1,192
4.21875
4
class Queen: """ Given the position of two queens on a chess board, indicate whether or not they are positioned so that they can attack each other. """ def __init__(self, row, column): # A chessboard can be represented by an 8 by 8 array. if row < 0 or column < 0 or row > 7 or column > 7: raise ValueError("Queen must have row on board!") self.row = row self.column = column def can_attack(self, another_queen): """ In the game of chess, a queen can attack pieces which are on the same row, column, or diagonal. :param another_queen: :return: """ if self.row == another_queen.row and self.column == another_queen.column: raise ValueError('Test queens same position can attack!') if self.row == another_queen.row: return True if self.column == another_queen.column: return True if max(self.row, another_queen.row) - min(self.row, another_queen.row) == \ max(self.column, another_queen.column) - min(self.column, another_queen.column): return True return False
true
0d03517895455cbd7f22db956e2cab99d854773a
ikostan/Exercism_Python_Track
/clock/clock.py
2,272
4.3125
4
class Clock: """ A clock that handles times without dates. """ DAY_AND_NIGHT = 24 HOUR = 60 def __init__(self, hour: int, minute: int): """ Constructor for the Clock class. Set hours and minutes by 24 hour clock. :param hour: :param minute: """ total_minutes = (hour * self.HOUR) + minute self.__hours = self.__calc_hours(total_minutes) self.__minutes = self.__calc_minutes(total_minutes) def __calc_minutes(self, total_minutes: int) -> int: """ Calculate minutes when update occurs :param total_minutes: :return: """ return total_minutes % self.HOUR def __calc_hours(self, total_minutes: int) -> int: """ Calculate hours when update occurs :param total_minutes: :return: """ return (total_minutes // self.HOUR) % self.DAY_AND_NIGHT def __repr__(self): """ Convert to string :return: """ return "{:02d}:{:02d}".format(self.__hours, self.__minutes) def __eq__(self, other) -> bool: """ Compare between objects. Two clocks that represent the same time should be equal to each other. :param other: :return: """ return self.__class__ == other.__class__ and \ self.__hours == other.__hours and \ self.__minutes == other.__minutes def __add__(self, minutes: int): """ Add minutes and update Clock. The Clock should be able to add minutes to it. :param minutes: :return: """ total_minutes = (self.__hours * self.HOUR + self.__minutes) + minutes return Clock(self.__calc_hours(total_minutes), self.__calc_minutes(total_minutes)) def __sub__(self, minutes: int): """ Subtract minutes and update Clock. The Clock should be able to subtract minutes to it. :param minutes: :return: """ total_minutes = (self.__hours * self.HOUR + self.__minutes) - minutes return Clock(self.__calc_hours(total_minutes), self.__calc_minutes(total_minutes))
true
250c11866f418ef397788851ee2ddf020c90b4fc
ikostan/Exercism_Python_Track
/scrabble-score/scrabble_score.py
703
4.125
4
def score(word: str) -> int: """ Given a word, computes the scrabble score for that word. :param word: :return: """ return sum(scrabble_score_generator()[letter] for letter in word.upper()) def scrabble_score_generator() -> dict: """ Generates Scrabble Score table :return: """ letter_value = { 1: 'AEIOULNRST', 2: 'DG', 3: 'BCMP', 4: 'FHVWY', 5: 'K', 8: 'JX', 10: 'QZ', } scrabble_score_table = dict() for letter_score in letter_value.keys(): for letter in letter_value[letter_score]: scrabble_score_table[letter] = letter_score return scrabble_score_table
true
56f685988b69bc39e808f8eb02023b9dce481a56
gautam4941/Python_Basics_Code
/ExtraConcepts/GlobalLocal.py
1,305
4.3125
4
''' a = 1 def func(): a = 5 b = 2 print(f"a inside Func = {a}") print(f"b inside Func = {b}\n") print(f"a outside Func() = {a}\n") #print(f"b outside Func() = {b}") func() print(f"a outside Func() = {a}") ''' ''' a = 2 def f1(): a = 5 print(f"a inside f1 = {a}") def f2(): b = 6 print(f"b inside f2 = {b}") print(f"a inside f2 = {a}") print(f"A Before Calling F1 = {a}") f1() f2() ''' """ a = 1 if( a == 1 ): print(f"a when a = 1 -> {a}") b = 6 if( b == 6): print(f"b when b = 6 -> {b}") c = 9 print(f"c when b = 6 -> {c}") print(f"c when outside of b -> {c}") print( f"a = {a}" ) print( f"b = {b}" ) print( f"c = {c}" ) """ """ a = 1 for i in range( 0, 5 ): b = 6 print(b) for j in range( 0, 3 ): c = 1 print(c, end = ', ') print(f"\na = {a}") print(f"b = {b}") print(f"c = {c}") #Note :- Local And Global Scope is only applicable to functions and Classes """ """ In Function and Classes. If we create any variable then, Then, those Variable follows Local- Global Rule with respect to the Level. But, Other than Funtions and classes. If we create any variable then, Those variable are by default Global. """
false
8447b6da7a3fbac47ff4d31fee03fb2f9bebea2e
gautam4941/Python_Basics_Code
/Tuple/Question1.py
592
4.125
4
#Question :- t = (5, 2, 9, 0) #output :- t =( 5, 2, 9, 0, 15, 20 ) #Method 1 :- ''' t1 = (5, 2, 9, 0) t2 = (5, 2, 9, 0, 15, 20) print( f"t1 = {t1}" ) print(f"t2 = {t2}") print() t1 = t2 print( f"t1 = {t1}" ) print(f"t2 = {t2}") ''' ''' #Method 2 :- Using Type Casting. t1 = (5, 2, 9, 0) list1 = list( t1 ) print(f"t1 = {t1}") print(f"list1 = {list1}") list1.append(15) list1.append(20) print(f"list1 = {list1}") t2 = tuple( list1 ) print(f"t2 = {t2}") t = (5, 2, 9, 0) t = list(t) t.append(15) t.append(20) t = tuple(t) print(t) '''
false
39b177ce1d6126900253c375c0dff05da4e3fb9b
gautam4941/Python_Basics_Code
/W3Resource/Basic Part 1/Prog10.py
358
4.125
4
#Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn #Ex :- Write a Python program that accepts an integer (5) and computes the value of 5+55+555 a = input("Enter a number = ") a_1 = int(a) a_2 = int( a*2 ) a_3 = int( a*3 ) print( f"Value of a = { a_1 } and { a_1 } + { a_2 } + { a_3 } = { a_1 + a_2 + a_3 }" )
false
c91672a2d63f2f273e1e7dc50eaff7adf2fb8f00
xc145214/python-learn
/exs/ex23.py
597
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 字符串转数字 print int('123456') # 进制 print int('123456', base=8) print int('123456',16) # 2进制转换 def int2(x,base=2): return int(x,base) print int2('1000000') print int2('1010101') # 偏函数 import functools int2 = functools.partial(int,base=2) print int2('1000000') print int2('1010101') # functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。 max2 = functools.partial(max,10) print max2(5,6,7)
false
a318a08b6bb24d1395246c61762daa9607804756
xc145214/python-learn
/exs/ex10.py
2,200
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 函数的参数 # 一个参数 def power1(x): return x * x print power1(5) # 多个参数 def power2(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s print power2(5) print power2(4, 4) # 学生注册 enroll()多参数 def enroll(name, gender, age=6, city='Beijing'): print 'name', name print 'gender', gender print 'age', age print 'city', city enroll('Saral', 'F') enroll('Bob', 'M', 7) enroll('Adam', 'M', city='Tianjin') # 定义函数的默认参数必须是不变的对象比如 string None def add_end_1(L=None): if L is None: L = [] L.append('END') return L print add_end_1() print add_end_1() print add_end_1() # 如果参数为可变对象 def add_end_2(L=[]): L.append('END') return L print add_end_2([1, 2, 3]) print add_end_2(['x', 'y', 'z']) print add_end_2() print add_end_2() # 计算 一组数的平方 # 使用列表参数 def calc_1(numbers): sum = 0 for n in numbers: sum = sum + n * n return sum # 调用函数时 用list 或者 tuple print calc_1([1, 2, 3]) print calc_1((1, 3, 6, 7)) # 使用可变参数 def cale_2(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print cale_2(1, 2) print cale_2() print cale_2(1, 3, 5, 6) # 如果已经有list 或者 tuple nums = [1, 2, 3, 4] print cale_2(*nums) # 好的写法 nums = [1, 2, 3, 4] print cale_2(nums[0], nums[1], nums[2], nums[3]) # 关键字参数 def person(name, age, **kw): print 'name', name, 'age ', age, 'kw', kw person('Michael', 30) person('Bob', 35, city='Beijing') person('Adam', 45, gender='F', job='Engineer') # 先组装成一个dict kw = {'city': 'Beijing', 'job': 'Engineer'} person('Jack', 23, city=kw['city'], job=kw['job']) person('Jack', 23, **kw) # 推荐写法 # 参数组合 def func(a, b, c=0, *args, **kw): print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw func(1, 2) func(1, 2, c=3) func(1, 3, 4, 'a', 'b') func(1, 2, 3, 'a', 'b', x=99) # 通过tuple 和 dict 调用 args = (1, 2, 3, 4) kw = {'x': 99, 'y': 88} func(*args, **kw)
false
7e4e6fc5abe745463d0a0d34c95c3fa80f9d87b7
chengshq/week2
/solution_4.py
316
4.125
4
# Syracuse sequence n=int(input("Please enter a natural number:")) def syracuse(x): seq = [x] if x < 1: return [] while x > 1: if x % 2 == 0: x = int(x / 2) else: x = 3 * x + 1 seq.append(x) return seq print("\nThe Syracuse sequence is", syracuse(n))
false
f72caf8d2c2d4492c6467a0028e136d8a70f7f30
Apocilyptica/Python_notes_school
/Variables/strings/strings.py
2,470
4.1875
4
sentence = 'The quick brown fo jumped over the lazy dog' sentence_two = 'That is my dog\'s bowl' sentence_three = "That is my dog's bowl" sentence_four = "Tiffany said, \"That is my dog's bowl\"" sentence = 'The quick brown fox jumped'.upper() # Entire string in uppercase #or #print(sentence.upper()) sentence = 'the quick brown fox jumped'.capitalize() # Capitalize the first letter of string sentence = 'the quick brown fox jumped'.title() # Capitalize every first letter of every word of string sentence = 'THE QUICK BROWN FOX JUMPED'.lower().title() # Entire string in lowercase + can have multipul calls starter_sentence = 'The quick brown fox jumped' #print(starter_sentence[0]) # prints out just the index callout starter_sentence = 'The quick brown fox jumped' #first = starter_sentence[0] #second = starter_sentence[1] #third = starter_sentence[2] #new_sentence = first + second + third first_word = starter_sentence[0:3] # brings back 'The' in range new_sentence = first_word # new_sentence = 'Thy' + starter_sentence[3:len(starter_sentence)] new_sentence = 'Thy' + starter_sentence[3:] #print(new_sentence) # Heredoc - multi-line comment, string content = """ Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam quis risus eget urna mollis ornare vel eu leo. Vestibulm id ligula porta felis euismod semper. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras justo odio, dapibus ac facilisis in. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. """.strip() # Takes out the new line characters at beggining and end content = """ Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam quis risus eget urna mollis ornare vel eu leo. Vestibulm id ligula porta felis euismod semper. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras justo odio, dapibus ac facilisis in. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. """ #print(repr(content)) # Representation of how the computer interperets at a string long_string = '\nNullam id dolor id nibh ultricies vehicula ut id elit. Nullam quis risus eget urna mollis ornare vel eu leo.\n\nVestibulm id ligula porta felis euismod semper. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras justo odio, dapibus ac facilisis in.\n\nInteger posuere erat a ante venenatis dapibus posuere velit aliquet.\n' print(long_string)
true
5730c9e980f8915cb3a6e24815a2bef55a28d9aa
rajkumarpatel2602/DataStructures_Algorithms
/G4G/DataStructures/Array/ArrayRotation.py
828
4.59375
5
# proble statement : array rotation without temp array # time complexity O(size*rotations) # space complexity O(1) # Python3 program to rotate an array by # d elements # Function to left rotate arr[] of size n by d*/ # utility function to print an array */ def printArray(arr, size): for i in range(size): print (str(arr[i])+" ") def leftRotateByOne(arr, size): temp = arr[0] for i in range(size-1): arr[i] = arr[i+1] arr[size-1] = temp def leftRotate(arr, rotation, size): for i in range(rotation): leftRotateByOne(arr, size) arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def main(): rotation = input("give number of rotation needed!") leftRotate(arr, rotation, 10) printArray(arr, 10) if __name__ == "__main__": main()
true
d1ac69d3ae3654034a314f65304edd0d0ed3917b
i143code/CRACKING-the-CODING-INTERVIEW
/chapter4/4-1.py
1,605
4.21875
4
# oute Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. class Node(object): def __init__(self,data): self.data = data self.visited = False self.adjacent = [] class BreadthFirstSearch(object): def bfs(self,node): queue = [] queue.append(node) node.visited = True while queue: data = queue.pop(0) print(data.data) for n in data.adjacent: if not n.visited: n.visited = True queue.append(n) # solution def bfssolution(self,node1,node2): queue=[] queue.append(node1) node1.visited= True while queue: data = queue.pop(0) # If this adjacent node is the destination node, # then return true if data == node2: print("There is a path from", node1.data,"to",node2.data) return True for n in data.adjacent: if n is node2: n.visited = True queue.append(n) print("There is no path from", node1.data,"to",node2.data) return False # Test node1 = Node("A") node2 = Node("B") node3 = Node("C") node4 = Node("D") node5 = Node("E") node6 = Node("F") node1.adjacent.append(node2) node1.adjacent.append(node3) node1.adjacent.append(node4) node2.adjacent.append(node5) node2.adjacent.append(node6) bfs = BreadthFirstSearch() # bfs.bfs(node1) print(bfs.bfssolution(node1,node6))
true
0707e025235ac9eda493fd1f1835b945eaaa3217
Anas-Abuhatab/snakes-cafe
/snakes_cafe/snakes-cafe.py
1,198
4.125
4
menu = { 'Wings':0, 'Cookies':0, 'Spring Rolls':0, 'Salmon':0, 'Steak':0, 'Meat Tornado':0, 'A Literal Garden':0, 'Ice Cream':0, 'Cake':0, 'Pie':0, 'Coffee':0, 'Tea':0, 'Unicorn Tears':0 } welCome = """************************************** ** Welcome to the Snakes Cafe! ** ** Please see our menu below. ** ** ** To quit at any time, type "quit" ** ************************************** Appetizers ---------- Wings Cookies Spring Rolls Entrees ------- Salmon Steak Meat Tornado A Literal Garden Desserts -------- Ice Cream Cake Pie Drinks ------ Coffee Tea Unicorn Tears *********************************** ** What would you like to order? ** ***********************************""" order =[] print(welCome) while True: userInput = input('> ') if userInput == 'quit': break elif userInput in menu: menu[userInput] +=1 else : print("**Please choose item **") for key ,value in menu.items(): if value >=1 : print( f"** {value} order of {key} have been added to your meal **") order.append(f"{value} order of {key}") else: continue
true
8ad96b846b5153d7d01808c8dd40123de9ceea36
Meowsers25/sowp
/chapt8/innotin.py
351
4.125
4
names = ['Luna', 'Beatrice', 'Sully'] names.append('Katie') names.append('Chris') print(names) if 'Sully' in names: print('Hi Sully') else: print('Sully is MIA') if 'Katie' in names: print('Hi sexy') else: print('Awwwww') if 'Chris' not in names: print('Where\'s the best guy in the world?') else: print('Hey, Awesome guy!')
false
7d6a7872d0809c4f9933da2668addcbd1ba94383
memanesavita/loop
/prime num.2.py
304
4.1875
4
# PRIME NUMBER # user=int(input("enter the number")) # i=1 # count=0 # while i<=user: # if user%i==0: # count=count+1 # i=i+1 # if count==2: # print("it is a prime number") # else: # print("it is not prime number")
true
526beca31008746cba9634cd2796469fa496bb8d
my-lambda-school-projects/Intro-Python-I
/src/dictionaries.py
1,950
4.4375
4
""" Dictionaries are Python's implementation of associative arrays. There's not much different with Python's version compared to what you'll find in other languages (though you can also initialize and populate dictionaries using comprehensions just like you can with lists!). The docs can be found here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries For this exercise, you have a list of dictionaries. Each dictionary has the following keys: - lat: a signed integer representing a latitude value - lon: a signed integer representing a longitude value - name: a name string for this location """ waypoints = [ { "lat": 43, "lon": -121, "name": "a place" }, { "lat": 41, "lon": -123, "name": "another place" }, { "lat": 43, "lon": -122, "name": "a third place" } ] # Add a new waypoint to the list # YOUR CODE HERE waypoints.append({"lat": 45, "lon": -124, "name": "new waypoint"}) print(waypoints) print() # Modify the dictionary with name "a place" such that its longitude # value is -130 and change its name to "not a real place" # YOUR CODE HERE for waypoint in waypoints: if (waypoint["name"] == "a place"): waypoint.update({"lon": -130, "name": "not a real place"}) break print(waypoints) print() # Write a loop that prints out all the field values for all the waypoints # YOUR CODE HERE # Student Question: What do you mean by all the field values?? # All the values for the keys (e.g.: 41, -123, 'another place') # By field do you mean the keys (e.g.: 'lat', 'lon', 'name') # or by field do you mean only the 'lat' and 'lon' values (e.g.: 41, -123) # Answer: Print all keys and values for waypoint in waypoints: # print(list(waypoint)) # print(waypoint.keys()) # print(waypoint.values()) print(waypoint.items()) # print([waypoint['lat'], waypoint['lon']]) print()
true
255f35f2b14f89e6638fd5a96ab39f73fdd374ef
MARKH0R/ProgrammingFundamentals
/basic function.py
1,875
4.25
4
"""fuction which find even and odd number""" def even_odd(x): if x%2==0: return "the number is even" else : return "number is odd" # ending of function """the function which check wather the number is negative or positive """ def _P_N_number(x): if x>0: return "number is positive" elif x==0: return "nither positive nor negative" else: return "number is negative" # ending of function """function to find greater and smaller number """ def differenceGandL(a,b): if a>b: return (a,"is grater then",b) elif b>a: return (b,"is grater then",a) else: return "both numbers are equal" # ending of function """function to find fibonachi number. You Have to give a number whome series you want. """ x=int(input('enter a number to find fibonacci series\t:' )) a=0 b=1 print (a,b) for i in range (1,x): z=a+b a=b b=z print (z) # ending of function """function which inter change tow strings""" x=input("enter any string:\n") z=input("enter an other string to swapwith frist:\t") y=x x=z z=y print( x ,z) # ending of function """Write a Python program to get the Python version you are using. for this we use library of sys""" import sys print("python version") print (sys.version) print ("python version info") print (sys.version_info) # ending of function """Write a Python program to display the current date and time. #for this we import date and time library""" import datetime now = datetime.datetime.now() print ("Current date and time : ") print (now.strftime("%Y-%m-%d %H:%M:%S")) # ending of function """Write a Python program which accepts the radius of a circle from the user and compute the area""" pi= 3.1415 def ares_of_circle(radius): area= pi* radius**2 return area # ending of function
true
7861cfccc6182b61b33c4de6097c0bf75391a07c
mkieft/Computing
/Python/Week 5/lab 5 q 3.py
250
4.3125
4
#Lab 5 Q 3 #Maura Kieft #9/29/2016 #3. Write a programs using the IF statement that prints only integers that are multiples of 6 and 2 from 0 to 20. def main(): for x in range (0,21,2): if (x%2==0) and (x%6==0): print(x) main()
true
21b7ae765b1c10e8cfaeeb36c1c9ab6d19a4de9a
JunXuanShi/python
/prac_03/password_check.py
847
4.3125
4
"""password = input("What's your password") number = len(password) print("*" * number)""" def main(): """the function is to get password and parameter from users and print asterisks.""" password = input("What's your password") while not is_valid_password(password): print("Invalid password!") password = input("> ") number = len(password) print("Your {}-character password is valid: {}".format(len(password), password)) print("*" * number) def get_parameter(): """the function is to get parameter from users.""" length = int(input("What's the size of your password ?")) return length def is_valid_password(password1): """the function is to check the password is valid or not.""" if 0 < len(password1) <= get_parameter(): return True else: return False main()
true
8baad6fdfbd6f0d94ef8ee0e79d18a18ebbde60c
Rielch/holbertonschool-higher_level_programming
/0x0A-python-inheritance/100-my_int.py
578
4.1875
4
#!/usr/bin/python3 """Creates a class MyInt that inherites from int that inverts == and !=""" class MyInt(int): """Class that inherites from int but inverts == and !=""" def __init__(self, value): """Initializates a MyInt class""" self.value = value def __new__(cls, value): """Creates a new int object""" return int.__new__(cls, value) def __eq__(self, other): """defines equality""" return self.value != other def __ne__(self, other): """defines inequality""" return self.value == other
true
1f58643b2bf4bdd7646546fa3b0846c8c5839043
Rielch/holbertonschool-higher_level_programming
/0x0A-python-inheritance/10-square.py
502
4.25
4
#!/usr/bin/python3 """Creates a Square class that inherits from Rectangle class""" Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """Creates a Square class""" def __init__(self, size): """initializates the object Square""" if self.integer_validator("size", size) is None: self.__size = size Rectangle.__init__(self, size, size) def area(self): """Returns the area of the square""" return self.__size ** 2
true
4a979a7d9f8e0e54914470b42a70867c9671bdb6
goutham-nekkalapu/algo_DS
/ctci_sol/stacks_queues/stack.py
1,108
4.1875
4
# stack implementation # operations supported : push,pop,peek,isEmpty class stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): if self.isEmpty(): print ("stack is empty : pop can not be done") else: return self.items.pop() def peek(self): if self.isEmpty(): print ("stack is empty : peek can not be done") else: return self.items[-1] def print(self): if self.isEmpty(): print ("stack is empty") else: print(self.items) if __name__ == "__main__": print("hello") s1 = stack() print(s1.isEmpty()) s1.push(10) s1.push(20) s1.print() s1.pop() s1.print() s1.pop() s1.print() s1.peek() """ s1.push(10) s1.push(20) s1.push(10) s1.push(40) s1.push(50) s1.push(610) s1.push(90) s1.push(100) s1.print() s1.pop() s1.print() print(s1.peek()) """
false
08aeea9414bca36b1d9b4a5d20e0c5c11b107b9a
goutham-nekkalapu/algo_DS
/python_programs/tail_recursion.py
742
4.21875
4
# This program gives two versions of recursion. Tail and non-tail recursion # Tailed recurison is best as the modern day compilers would optimize them, eliminating the recurison part ( thus helps us by eliminating # the need to store the stack pointers for each function call ). Typically compilers use 'goto' statement to achieve this # # Here we will see a factorial cal problem in both the versions # def recursion_tailed(n, a): print "a is",a print "n is",n if n == 0: return a else: return recursion_tailed(n-1,n*a) def recursion(n): if n == 1: return 1; else: return n*recursion(n-1) if __name__ == "__main__": print recursion_tailed(1000,1) #print recursion(1000)
true
93cb6df52c9b1dc2d629d8db2df42fb6448ae223
datlife/CISF003A-Python
/Classnote/Week8_Thursday.py
805
4.15625
4
# Python 3 Iterator import numpy as np class Reverse: def __init__(self, data): """ :param data: """ self.index = len(data) # get the last index of data self.data = data def __iter__(self): return self def __next__(self): if self.index ==0: raise StopIteration else: self.index -= 1 return self.data[self.index] if __name__ == "__main__": a_list = [1, 2, 3, 4, 5, 6] test = Reverse(a_list) # List comprehension print(list([i for i in test])) a_string = "the quick brown fox jumps over the lazy dog" print("".join([s for s in Reverse(a_string)])) # Create a rank 2 Array using numPy a = np.array([[1, 2, 3], [4, 5, 6]]) print(a.shape) print(a[0, 0], a[1, 0])
true
7703bcf8079b500a0903c6a63da5211fd28b599c
datlife/CISF003A-Python
/Classnote/Week5_Tuesday.py
2,988
4.15625
4
import typing class Test : def __init__(self): """ """ self.Answer = "" def print_answer(self)->None: """ Just prints the Answer variable :return: """ print(self.Answer) def test_me(self)->None: """ :param self: :return: """ print("leave me alone") class BankAccount: def __init__(self, balance: float=0.0): """ :param balance: """ self.Account_number = -1 self.Account_first_name = "" self.Account_last_name = "" self.Account_routing_numbers = [] self.Account_balance = balance def print_balance(self): print("The account balance is: " + str(self.Account_balance)) def double_my_money(self): self.Account_balance *=2 def add_to_balance(self, add_to_balance:float): """ Add money to the balance :param add_to_balance: :return: """ if add_to_balance <0: print("excuse me, you have to put some real money please, no funny business!") return elif add_to_balance > 10**7 : print(" please speak to the bank manager we don't accept such large deposits!") else: self.Account_balance += add_to_balance def __str__(self)->str: str_rep ="" str_rep += "The account number is: " + str(self.Account_number ) + "\n" str_rep += "For Account holder: " + str(self.Account_first_name) + " "+ str(self.Account_last_name) + "\n" str_rep += "The account balance is: " + str(self.Account_balance) return str_rep def __int__(self)->int: return self.Account_number def __add__(self, other): self.Account_balance += other.Account_balance return self def __mul__(self, other): self.Account_balance *= other.Account_balance return self def __truediv__(self, other): self.Account_balance /= other.Account_balance return self # code entry point if __name__ == "__main__": me = Test() second_me = Test() me.test_me() me.Answer= "Five" second_me.Answer = "Ten" me.print_answer() second_me.print_answer() ba = BankAccount() print(ba.Account_number) ba.print_balance() second_account = BankAccount(20) second_account.double_my_money() second_account.print_balance() second_account.add_to_balance(-50000) second_account.print_balance() second_account.add_to_balance(50000) second_account.print_balance() # print(str(second_account) ) print(second_account) print(int(second_account) + 5) print("is this upper case?".upper()) test_list = [3, 9, 5, 6, 4] test_list.append(20) test_int = 23 print(test_list) ba.add_to_balance(500) print(second_account+ba) print(ba) print(second_account) print(second_account*ba) print(second_account/ba)
true
1224bf2645fc88bf0c64327801600250334015c0
2016b093005/hackerrank_python
/02_Hex.py
994
4.1875
4
""" CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB). Specifications of HEX Color Code ■ It must start with a '#' symbol. ■ It can have or digits. ■ Each digit is in the range of to . ( and ). ■ letters can be lower case. ( and are also valid digits). You are given lines of CSS code. Your task is to print all valid Hex Color Codes, in order of their occurrence from top to bottom. CSS Code Pattern Input Format The first line contains , the number of code lines. The next lines contains CSS Codes. Constraints Output Format Output the color codes with '#' symbols on separate lines. """ # fetched_date = date_re_abr2.search(strn).group(1) # Enter your code here. Read input from STDIN. Print output to STDOUT # Enter your code here. Read input from STDIN. Print output to STDOUT import re import sys [print(j) for i in sys.stdin for j in re.findall('[\s:](#[a-f0-9]{6}|#[a-f0-9]{3})', i, re.I)]
true
1276da6c08b60c0d09de89c7f4a0bcee2d7e1744
2016b093005/hackerrank_python
/06_grades.py
1,528
4.3125
4
""" Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. Input Format The first line contains an integer, , the number of students. The subsequent lines describe each student over lines; the first line contains a student's name, and the second line contains their grade. Constraints There will always be one or more students having the second lowest grade. Output Format Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line. """ if __name__ == '__main__': students = list(list()) students.append(["name", 2.2]) lowest_grade = 100.0 s_lowest_grade = 100.0 for _ in range(int(input())): name = input() score = float(input()) if score < lowest_grade: s_lowest_grade = lowest_grade lowest_grade = score elif s_lowest_grade > score > lowest_grade: s_lowest_grade = score students.append(["name", 2.2]) students[_][0] = name students[_][1] = score output = list() for student in students: if student[1] == s_lowest_grade: output.append(student[0]) output.sort() for name in output: print(name)
true
d3076788dfdd6db16af81693ed586a491ac5fb67
ande0255/loopedback
/IfThen.py
320
4.15625
4
name = input('Please tell me your name: ') rawAge = input('Please tell me your age: ') age = int(rawAge) if age >= 21: print(name, 'you are 20 or older and can come in!') elif age >= 18: print('You are not allowed to drink, but you may come in.') else: print('You are too young, go home and learn Python!')
true
6ab2309db93c82c2e1df056c5cf1e1151f3128ac
curioussmind/my-python
/tuples_lists_dicts/cardinal_numbers.py
419
4.1875
4
cardinal_numbers = ("first", "second", "third") # creating tuple literal print(type(cardinal_numbers)) # creating tuple literal print(cardinal_numbers[1]) # print element at index 1 position_1, position_2, position_3 = cardinal_numbers # tuple unpacking print(position_1, position_2, position_3) my_name = ("o", "k", "t", "a", "v", "i", "a", "n", "u", "s") print(type(my_name)) print("x" in my_name) print(my_name[1:])
true
38a853e1504647d2abfb61322696ba53fc2f212b
curioussmind/my-python
/tuples_lists_dicts/exercises.py
320
4.21875
4
# PART 1 food = ["rice", "beans"] # 1 food.append("broccoli") # 2 food.extend(["bread", "pizza"]) # 3 print(food[:2]) # 4 print(food[-1]) # 5 # PART 2 breakfast = "eggs, fruit, orange juice".split(",") # 6 print(breakfast) print(len(breakfast)) # 7 lengths = [len(string) for string in breakfast] # 8 print(lengths)
true
ed8d3067551204a2b6a3551493ae017fb7f26a8e
curioussmind/my-python
/tuples_lists_dicts/basic_list_operations.py
1,265
4.53125
5
# indexing and slicing work alomst the same as tuple alphabet = ['a', 'b', 'c', 'd'] alphabet[1] # accessing item at index 1 new_alphabet = alphabet[1:3] # creating list from existing list by slicing 'z' in new_alphabet # checking element in the list # LIST ARE ITERABLE, WE CAN USE FOR LOOP TO ITERATE OVER THEM for alph in alphabet: print(alph * 2) # CHANGING ELEMENT IN LIST colors = ["red", "yellow", "green", "blue"] colors[0] = "burgundy" colors # >> ["burgundy", "yellow", "green", "blue"] # LIST METHOD FOR ADDING AND REMOVING ELEMENT # insert() used to add a single value into a list. It takes two parameters, the index and the value colors.insert(1, "orange") # if the value for index parameter .insert() is larger than the greatest index in the list, # the value will be inserted at the end. colors.insert(20, 'violet') colors.insert(-1, "indigo") # we can also use negative indices # REMOVE ELEMENT OF AT A SPECIFIC INDEX colors = colors.pop(3) # remove the value from index 3 # colors.pop(-1) # this also works colors.append("purple") # add new element at the end of a list colors.insert(len(colors), "black") # insert black at the end of a list # add several items/ elements to a list colors.extend(['white', 'maroon']) print(colors)
true
994ece04b72b5602cd2be141302d7a93fc550f8a
curioussmind/my-python
/function/temperature.py
489
4.15625
4
def convert_cel_to_far(celcius=float): fahrenheit = celcius * (9/5) + 32 return fahrenheit def convert_far_to_cel(fahrenheit=float): celcius = (fahrenheit - 32) * (5/9) return celcius cel = float(input("enter a temperature in degree C:")) cel_in_fah=convert_cel_to_far(cel) print(f"{cel} degrees C = {cel_in_fah} degrees F.") fah = float(input("Enter a temperature in degree F: ")) fah_in_cel = convert_far_to_cel(fah) print(f"{fah} degress F = {fah_in_cel} degrees C.")
false
8f40f431544b82df570e4b4e3aa1701125439929
JoseJunior23/Iniciando-Python
/aprendendo_python/ex026.py
446
4.21875
4
"""" O programa deve ler uma frase e mostrar quantas vezes a letra a aparece em que posição ela aparece pela 1º vez e emque posição aparece pela ultima vez""" frase = str(input('Digite uma frase: ')).upper().strip() print(' A letra A apareceu {} vezes na frase. '.format(frase.count('A'))) print('A primeira letra A esta na posição {} '.format(frase.find('A')+1)) print('A ultima letra esta na posição {} '.format(frase.rfind('A')+1))
false
c07de98e8f616d9aa294c0521322b88147e030dc
JoseJunior23/Iniciando-Python
/aprendendo_python/ex030.py
262
4.15625
4
# criar um programa que mostra se um numero é PAR ou IMPAR : num = int(input('Digite um numero para saber se ele é PAR ou IMPAR: ')) n = (num % 2) if n == 0: print('O numero {} é PAR: '.format(num)) else: print('O numero {} é IMPAR: '.format(num))
false
6f674c20f7989778ccb596737f77db932560485c
JoseJunior23/Iniciando-Python
/treinando_pythonLista1/ex 05.py
244
4.3125
4
# Faça um Programa que converta metros para centímetros. metro = float(input('Digite o valor em metros á ser convertido: ')) cent = metro * 100 print('Você indicou {} metros, que convertidos representa {} centimetros'.format(metro, cent))
false
55e2feefa92c98a743f713d510b402c24d0f84c7
JoseJunior23/Iniciando-Python
/treinando_pythonLista1/ex 018.py
478
4.1875
4
''' Faça um programa que peça o tamanho de um arquivo para download (em MB) e a velocidade de um link de Internet (em Mbps), # calcule e informe o tempo aproximado de download do arquivo usando este link (em minutos). ''' arquivo = float(input('Qual o tamanho do arquivo em MB: ')) velocidade = float(input('Qual a velocidade da internet(Mbps): ')) tempo = (arquivo / velocidade) * 60 print(' O tempo para termino do download é de aproximadamente {} minutos'.format(tempo))
false
34ac5af6cfc9d7ec6fe8b3ba74e4d7f4b92753b6
felsokning/Python
/SvenskaVeckanNummer.py
813
4.1875
4
#!/usr/bin/env python """Returns the current week number of the year. As some countries (e.g.: Sweden) use week numbers for organisation, it's important to be able to return the given week number in an easily referenced code-base. One could use http://vecka.nu, but this requires opening a web browser and going to the site specified - assuming that one can remember the address. The goal of this it to make this data available on the local machine, instead. TO RUN: python SvenskaVeckanNummer.py """ __author__ = "felsokning" __copyright__ = "Copyright 2018" __license__ = "MIT" import datetime today = datetime.date.today() # Since the ISO Calendar object is an array in Python, we return the object in the array representing the week's number. week_number = today.isocalendar()[1] print(week_number)
true
342d6b75c5b312553f6da47efb5c68f39843a949
stianbm/TDT4120_AlgoritmerOgDatastrukturer
/Ov2/Ov2It2.py
1,503
4.21875
4
#!/usr/bin/python3 from sys import stdin from itertools import repeat def merge(decks): # SKRIV DIN KODE HER #As the input is read as a list of lists, recursion becomes hard to implement because one has to # keep track of whichstage one resides in. This results in iteration via double while loop. #The idea is to take two and two lists out of the main list, sort them into one, and append # this to the main list. When the main list has only one list, the task is complete. while len(decks) > 1: #Extract two lists, we know from the while condition there's at least two. Remove said list from # main list. List1 = decks.pop(0) List2 = decks.pop(0) #Allocate a list to store the sorted values SortedList = [] #Iterate while 0 < len(List1) and 0 < len(List2): if List1[0] < List2[0]: SortedList.append(List1.pop(0)) else: SortedList.append(List2.pop(0)) #When one list is empty, add the rest of the other list to SortedList, because they're sorted. SortedList.extend(List1) SortedList.extend(List2) #Add the SortedList to the main list decks.append(SortedList) return decks def main(): # Read input. decks = [] for line in stdin: (index, csv) = line.strip().split(':') deck = list(zip(map(int, csv.split(',')), repeat(index))) decks.append(deck) # Merge the decks and print result. print(merge(decks)) if __name__ == "__main__": main()
true
9756281c7a608ead6fa56103a4b4479fad6e13a6
a-escala/DojoAssignment
/Python/funfunc.py
395
4.125
4
#printing odds and evens def odd_even(): for x in range(1, 2001): if x % 2 == 0: print ("Number is {}. This number is even").format(x) else: print ("Number is {} This number is odd").format(x) odd_even() #multiply each value by 5 a = [2, 4, 10, 16] b = [] def multiply(a): for num in a: b.append(num * 5) return b print multiply(a)
true
e72d53e0fc62644e39792f4924f2c1892d1e3c2d
tjwilli6/ENGR_2310
/private/homework/quadratic.py
1,238
4.4375
4
########################### # Author: Tyler Williamson # Date: 02/05/2021 # quadratic.py: a program to calculate the roots of # a quadratic equation #Tell the user what to do print("Enter the coefficients 'a', 'b', and 'c'",end='') print(" of the polynomial 'ax^2+bx+c'",end='') print(" and I will find the roots!") #Collect coefficients from user a = float(input("Enter coefficient 'a': ")) b = float(input("Enter coefficient 'b': ")) c = float(input("Enter coefficient 'c': ")) if a != 0: #If 'a' is not zero, two possibilities #discriminant >=0 --> use quadratic formula #discriminant < 0 --> complex, don't solve #Calculate discriminant disc = b**2 - 4 * a * c if disc >= 0: x1 = (-b + disc**0.5) / 2 / a x2 = (-b - disc**0.5) / 2 / a print("x1,x2 = (",x1,",",x2,")") else: print("The solution is complex, that's above my pay grade!") else: #if a = 0, the equation is just bx+c=0-->x=-c/b #I said you could assume 'b' is not zero #If that wasn't the case, you have to check #'b' evaluates to True UNLESS it is zero if b: x = -c / b print("x = ",x) else: print("Nothing to solve for!")
true
486f234eb506b40de1e14ad752ef8bdfbbf0fe16
tjwilli6/ENGR_2310
/public/lectures/sum_forces_new.py
2,612
4.28125
4
###################### #Author: T. Williamson #Date: 2020-02-24 #sum_forces_new.py: A program to add two force vectors together # user inputs |F| and theta in degrees for both forces # program prints x and y components of Fsum #Global constants PI = 3.14 #Functions def deg2rad(angle): """ Convert an angle from degrees to radians """ return angle * PI / 180 def factorial(number): """ Calculate the factorial of number """ result = 1 while number > 0: result = result * number number = number - 1 #number-=1 return number def cos(x,num_of_terms=20): """ Compute cos(x) using a Taylor expansion num_of_terms is an optional argument cos(x) ~= 1 - x**2/2! + x**4/4! - x**6/6! + ... """ #loop counter n = 0 #power each term is raised to exponent = 0 #alternating sign sign = -1 #sum total = 0 while n < num_of_terms: #calculate factorial fact = factorial(number) #continually alternating sign sign = -1 * sign term_value = sign * x**exponent / fact total = total + term_value n = n + 1 #Bump up by 2 so exp goes from 0,2,4,6,... exponent = exponent + 2 return total def sin(x,num_of_terms=20): """ Compute sin(x) using a Taylor expansion num_of_terms is an optional argument sin(x) ~= x - x**3/3! + x**5/5! - x**7/7! +... """ #loop counter n = 0 #power each term is raised to exponent = 1 #alternating sign sign = -1 #sum total = 0 while n < num_of_terms: #calculate factorial fact = factorial(number) #continually alternating sign sign = -1 * sign term_value = sign * x**exponent / fact total = total + term_value n = n + 1 #Bump up by 2 so exp goes from 1,3,5,7... exponent = exponent + 2 return total def main(): """ main program """ #Collect user input F1 = float(input("What is the magnitude of the first force (in Newtons)? ")) theta1 = float(input("What is the angle of the first force (in deg)? ")) F2 = float(input("What is the magnitude of the second force (in Newtons)? ")) theta2 = float(input("What is the angle of the second force (in deg)?")) #Convert to radians theta1_rad = deg2rad(theta1) theta2_rad = deg2rad(theta2) #x and y components of Fsum F3x = F1 * cos(theta1_rad) + F2 * cos(theta2_rad) F3y = F1 * sin(theta1_rad) + F2 * sin(theta2_rad) print("Net force is: ",Fx3,Fy3) #Now run the code! main()
true
aedf08a81e09d31641410d46bd04d7fc4ef9cbc5
tjwilli6/ENGR_2310
/private/temp/stanley_virtual/engr2310/g.py
486
4.34375
4
# Cameron Stanley # 2-12-2021 # This code askes the user for the mass of the planet and radius of the planet # and prints out the gravitational acceleration. mass = float(input("What is the planets mass? ")) # the inputs for the equation radius = float(input("What is the planets radius? ")) G = 6.7e-11# same as (6.7 * 10^-11) def equation(mass, radius, G): # is the function. print("g = ", (G * mass)/(radius**2))#what the code out puts and the equation. equation(mass, radius, G)
true
1d10a1c7faa5208df56f1265b96d0d077622f17d
GopichandJangili/Python
/operators_python.py
1,110
4.28125
4
#operators #1. Arithmetic operators print(1+2,2-1,2*3,2**3) #a**b means a to the power of b print(5/2,5//2) #5//2 -> means floor division....output is 2 instead of 2.5 print(5%2,4%2) #->modulo operator or gives reminder #2. Relational operators print(5>2,5<2,5>=2,5<=2,5!=2,5==5) # <> (this is not allowed in python) #3. Logical operators (and or not) a,b,c,d = True,False,True,False print(a and b,a and c,b and d) print(a or b) #True print(not a) #False print(not b) #True #4. Special Operators #4.1. Identity Operators (is ; is not) a,b,c = 2,3,2 print(a is b,a is c) print(a is not b, a is not c) #4.2 Membership operators (in ; not in) a = [1,2,3] print(1 in a,8 in a) print(1 not in a,8 not in a) #5 Ternary Operator a = '1' if 2==2 else '5' b = '1' if 2!=2 else '5' print(a,b) #6 Any;All a = [True,True,False,False] b = [False,False,False] c = [True,True,True,True] d =[] print(any(a),any(b),any(c),any(d)) print(all(a),all(b),all(c),all(d)) #empty becomes in case of True ########some more concepts print('abc'*3) #prints the string 3 times
true
30b83c39310657c2eae6892e76c4bb562e489e81
GopichandJangili/Python
/strings_Python.py
1,955
4.40625
4
#no char a = 'abcdef' #three single or double quotes for multiline strings a = '''hi this is a three line string \n''' b = """ This is a double quote statement""" print(a,b) ###slicing a = 'abcdefgh' print(a[:2],a[2:3],a[-1],a[:-2],a[-3:-1]) #reverse a string a = 'abcdef' print(a[::-1]) print(len(a)) print(reversed(a)) print(''.join(reversed(a))) # second way to reverse a string #upper, lower, strip and spaces print(a.upper()) b = 'abcdABCD' a = 'abcd' print(b.upper(),b.lower()) print(b.isupper(),b.islower(),a.isupper(),a.islower()) z = 'abcd ef lm' x = ' cceb ' v = x.strip() print(x) print(v) print(z.strip(),'\n',x.strip()) #count spaces in a string a = 'abcd ef xy' print(a.count(' ')) #or count =0 for i in a : if i.isspace(): count+=1 print(count) #convert string to list a = 'abcd' b = list(a) print(b) #endswith a = 'This is a sentence.' print(a.endswith('.')) #this returns True ## string replacement a = "this is a car" z = a.replace('car','bike') print(z) ##Check if a string exists in another string if 'car' in 'this is a car': print('yes') else: print('no') #splitting a string a = 'file.csv.txt' b = a.split('.') print(b,b[0],b[2]) #escape character a = "this is an "imp" string" #will not work a = "this is an \"imp\" string" print(a) #find location of a character a = "abcd-efgh" print(a.find('-')) print(a.index('-')) a = 'abcdABCD' print(a.capitalize()) # first letter capital ##############string formatting########################## ######################################################### ######################################################### #3 Types a = 'hi' b = '123' print('This is first way %s and %s ' %(a,b)) print('This is first way {} and {} '.format(a,b)) print(f'This is first way {a} and {b}') print(F'This is first way {a} and {b}')
false
4ec158c7ff751e5350bbfae4eb8faf29c7b5da46
omatveyuk/interview
/CrackingTheCodingInterview/ArraysAndStrings/permutation.py
830
4.15625
4
"""Check if one string is permutation of another string. Return: True if one string is permutation of another string, otherwise False. """ def permutation(str1, str2): """Check if one string is permutation of another string. >>> permutation("oxana", "xanao") True >>> permutation("oxana", "oxanaM") False >>> permutation("oxana", "mariia") False """ # SOLUTION 1 if len(str1) != len(str2): return False str1.sort() # O(n) = nlog(n) str2.sort() return str1 == str2 #SOLUTION 2 from collections import Counter # O(n) = nlog(n) return Counter(str1) == Counter(str2) if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. permutation.py WORKS SUCCESSFULLY! ***\n"
true
612b8de6f1024c4e899b6f5844f369e97dc8554d
omatveyuk/interview
/insertion_sort.py
777
4.25
4
"""Insertion sort. 6 5 3 8 7 2 5 6 3 8 7 2 3 5 6 8 7 2 3 5 6 8 7 2 3 5 6 7 8 2 2 3 5 6 7 8 For each item in the list, starting at the second, find out how far to the left it goes--as soon as we find a number smaller than it, we insert item after this number >>> insertion_sort([6, 5, 3, 8, 7, 2]) [2, 3, 5, 6, 7, 8] >>> insertion_sort([2, 3, 4, 7]) [2, 3, 4, 7] """ def insertion_sort(alist): """Given a list, sort it using insertion sort.""" for i in xrange(1, len(alist)): j = i while j > 0 and alist[j-1] > alist[j]: alist[j-1], alist[j] = alist[j], alist[j-1] j -= 1 return alist if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TEST PASSED. W00T! ***\n"
true
21678d1b5e876bb2c3da451c103ca009048ca567
britonohe0418/tarea-1-semana-1
/ejercicio10.py
1,290
4.375
4
"""Un ejemplo en el cual usamos el operador lógico AND sería: Una escuela aplica dos exámenes a sus aspirantes, por lo que cada uno de ellos obtiene dos calificaciones denotadas como C1 y C2. El aspirante que obtenga calificaciones mayores que 80 en ambos exámenes es aceptado; en caso contrario es rechazado. Un ejemplo usando el operador lógico OR sería: Una escuela aplica dos exámenes a sus aspirantes, por lo que cada uno de ellos obtiene dos calificaciones denotadas como C1 y C2. El aspirante que obtenga una calificación mayor que 90 en cualquiera de los exámenes es aceptado; en caso contrario es rechazado. """ class Ejercicio10: def __init__(self): pass def and_op(self): c1 = float(input('Ingrese la primera nota: ')) c2 = float(input('Ingrese la segunda nota: ')) if (c1 >= 80) and (c2 >= 80): print('Aceptado') else: print('Rechazado') def or_op(self): c1 = float(input('Ingrese la primera nota: ')) c2 = float(input('Ingrese la segunda nota: ')) if (c1 >= 90) or (c2 >= 90): print('Aceptado') else: print('Rechazado') operador = Ejercicio10() print('AND') operador.and_op() print('\nOR') operador.or_op()
false
995701ca37ec7cd0f7da7c86adb64f2847c0922a
r0bse/python_VL_snippets
/vl2/oop/diamond_problem.py
1,402
4.28125
4
from abc import ABC, abstractmethod class CrabPeople(ABC): def __init__(self, name): self.name = name self.race = "CrabPeople" class Bird(ABC): def __init__(self, name): self.name = name self.race = "Bird" @abstractmethod def fly(self): pass class Alien(CrabPeople, Bird): def __init__(self, name): super().__init__(name) self.race = "Alien" @abstractmethod def fly(self): pass class Human(CrabPeople): def __init__(self, name: str): super().__init__(name) self.name = name self.race = "Human" def walk(self): print("walking") class SuperHuman(Human, Alien): def __init__(self, name: str): super().__init__(name) def fly(self): print("flying") if __name__ == "__main__": superboy = SuperHuman("superboy") superboy.walk() superboy.fly() print("superboy is of instance \"CrabPeople\": {0}".format(isinstance(superboy, CrabPeople))) print("superboy is of instance \"Bird\": {0}".format(isinstance(superboy, Bird))) print("superboy is of instance \"Human\": {0}".format(isinstance(superboy, Human))) print("superboy is of instance \"Alien\": {0}".format(isinstance(superboy, Alien))) print("superboy is of instance \"SuperHuman\": {0}".format(isinstance(superboy, SuperHuman))) print(superboy.race)
false
d9800ef06f08392f7cff26b9e85ec3cfc9a74de8
RandyCB/Concurrency
/Multiprocessing.py
2,186
4.34375
4
import multiprocessing import concurrent.futures import time """ Description: Python 3.8.5 Program example for multiprocessing using two different methods Notes: Multiprocessing is meant to be use in tasks that make high use of the CPU cores Using the contex manager will join processes automatically The map method executes the function argument with all the elements of the list argument Test case: Intel(R) Core(TM) i3-4005U CPU @ 1.70GHz On-line CPU(s) list: 0-3 Thread(s) per core: 2 20.04.2 LTS (Focal Fossa) Running the Process pool with more than 4 iterations at time will cause to execute in more than 1 second since it is related with the HW cores in the PC where it is running """ def do_something(seconds): print(f'Sleeping {seconds} second(s)') time.sleep(1) print('Done sleeping') def do_something_else(seconds): print(f'Sleeping {seconds} second(s)') time.sleep(seconds) return 'Done sleeping' #------------------------------------------------------------------------------- #Old method processes = [] start = time.perf_counter() for _ in range(10): p = multiprocessing.Process(target=do_something, args=[1]) p.start() processes.append(p) for process in processes: process.join() finish = time.perf_counter() print(f'Finished in {round(finish-start,3)} seconds(s)') print(" "*3) #------------------------------------------------------------------------------- #newer method start = time.perf_counter() with concurrent.futures.ProcessPoolExecutor() as executor: results = [executor.submit(do_something_else,1) for _ in range(5) ] for f in concurrent.futures.as_completed(results): print(f.result()) finish = time.perf_counter() print(f'Finished in {round(finish-start,3)} seconds(s)') print(" "*3) #------------------------------------------------------------------------------- #Using map function instead start = time.perf_counter() s = [5,4,3,2,1] with concurrent.futures.ProcessPoolExecutor() as executor: results = executor.map(do_something_else, s) for result in results: print(result) finish = time.perf_counter() print(f'Finished in {round(finish-start,3)} seconds(s)')
true
82437df176eab4a0463f53f37f698888e5c7c542
hussainhaichel/encryption
/encryption.py
280
4.125
4
alphabet = 'abcdefghygklmnoprstuvwxyz' key = 3 newMassage = '' message = input('please enter a message:') for character in message: position = alphabet.find(character) newPosition = (position + key)%26 newCharacter = alphabet[newPosition] print('the new character is: ', newCharacter)
true
eb7da9853682cb3d43de491f8bc382d4db259460
JohnMellaley/python_test
/byotest.py
1,092
4.25
4
"""def is_even(number): return number%2==0 def number_of_evens(numbers): evens = sum([1 for n in numbers if is_even(n)]) return False if evens == 0 else is_even(evens)""" def test_are_equal(actual, expected): assert expected == actual, "Expected {0}, got {1}".format(expected, actual) def test_not_equal(a, b): assert a != b, "Did not expect {0} but got {1}".format(a, b) def test_is_in(collection, item): assert item in collection, "{0} does not contain {1}".format(collection, item) def test_not_in(collection,item): assert item not in collection, "{0} does contain {1}".format(collection, item) def test_in_between(lower,higher,item): assert item >= lower and item <= higher, "{0} is not between {1} and {2}".format(item, lower, higher) #test_are_equal(number_of_evens([1,2,4,9,6]), False) #test_are_equal(number_of_evens([1,2,4,9]), True) #test_is_in([5,4,3,2,1],6) #test_is_in([5,4,3,2,1],1) #test_not_in([5,4,3,2,1],6) #test_not_in([5,4,3,2,1],1) #test_not_equal(4,3) # test_not_equal(2,2) #test_in_between(1,5,3) #test_in_between(1,5,6)
true
9bd97f116934c47e2a0d0ccacbcc1b7f81236d7a
bballamudi/DataGristle
/datagristle/csvhelper.py
1,928
4.15625
4
#!/usr/bin/env python """ Used to help interact with the csv module. See the file "LICENSE" for the full license governing this code. Copyright 2011, 2017 Ken Farmer """ import csv from typing import Optional def get_quote_number(quote_name: str) -> int: """ used to help applications look up quote names typically provided by users. Inputs: - quote_name Outputs: - quote_number Note that if a quote_number is accidently passed to this function, it will simply pass it through. """ return csv.__dict__[quote_name.upper()] def get_quote_name(quote_number: int) -> str: """ used to help applications look up quote numbers typically provided by users. """ for key, value in csv.__dict__.items(): if value == quote_number: return key else: raise ValueError('invalid quote_number: {}'.format(quote_number)) class Dialect(csv.Dialect): def __init__(self, delimiter: str, has_header: bool, quoting: int, quotechar: str = None, doublequote: Optional[str] = None, escapechar: Optional[str] = None, lineterminator: Optional[str] = None, skipinitialspace: Optional[bool] = None) -> None: assert quoting in [csv.QUOTE_NONE, csv.QUOTE_MINIMAL, csv.QUOTE_ALL, csv.QUOTE_NONNUMERIC] skipinitialspace = False if skipinitialspace is None else skipinitialspace lineterminator = lineterminator or '\n' quotechar = quotechar or '"' self.delimiter = delimiter self.doublequote = doublequote self.escapechar = escapechar self.lineterminator = lineterminator self.quotechar = quotechar self.quoting = quoting self.skipinitialspace = skipinitialspace self.has_header = has_header
true
2ba4bdddca60666b5c02109c542f101db958f798
soumiyajit/python
/python-basic/003-string_length.py
310
4.25
4
""" WAP to take string input from users and print the length of the string. If the user enters quit, it should exit the program """ while True: str = raw_input("enter a string ::") # print(str) if str == "quit": break else: print "length of the string", str, "is ", len(str)
true
634c04ada4cd4470becc5618d77af5f1bd1dcf08
silviawin/Giraffe_python_exercises
/pyFor.py
744
4.5625
5
# for loop is to loop through different collections of items # ex: different arrays or the letters inside a string friends = ["jim", "ana", "mario", "carla", "dani"] for letter in "Giraffe Academy": print(letter) print("\n") for friend in friends: print(friend) print("\n") for index in range(10): print(index) print("\n") for elemento in range(3,10): print(elemento) print("\n") for index in range(len(friends)): print(index) print(friends[index]) print("\n") for index in range(len(friends)): print(friends[1]) print("\n") for especial in range(5): if especial == 0: print("First Iteration") else: print("More numbers are cool")
false
b09ff9d264bd19ef1eadc209856c10ac0d8353ca
jayshreeuw/Python
/DataTypes/Strings/Strings_methods.py
1,627
4.71875
5
#!usr/bin/python # 1. Capitalize() method: #It returns a copy of the string with only its first character capitalized str = "this is string example....wow!!!" print("str.capitalize():",str.capitalize()) # 2. Center() method: # This method returns centered in a string of length width. #Padding is done using a specified fillchar, default filler is a space. str1 = "Welcome to python world" print(len(str1)) # len() prints the number of characters in string print("str.center(27,'a'):",str1.center(27, '$')) # 23 is the length of the character and 4 we have added # two $ signs are added in suffix and two in prefix # 3. Count() method: # It returns the number of occurences of substring sub in the range [start,end] # Optional arguments start and end are interpreted as in slice notation mac = "Welcome to python world" sub = "o" print(len(mac)) print("mac.count(sub):", mac.count(sub)) print("mac.count(sub,4,23:", mac.count(sub, 4, 23)) sub1='python' print("mac.count(sub1,4,23:", mac.count(sub1, 4, 23)) # 4. Decode() method: #It defaults to the default string encoding mac1 = "Welcome to python" mac1 = mac1.encode('utf-8','strict') print("Encoded String: ", mac1) print("Decoded String: " + mac1.decode('utf-8','strict')) #5. Encode() method: #It returns an encoded version of the string #6. Endswith() method: #It returns TRUE if the string ends with the specified suffix otherwise returns FALSE str2 = "this is string example....wow!!!"; suffix = "wow!!!"; print(str2.endswith(suffix)) print(str2.endswith(suffix,20)) suffix = "is"; print(str2.endswith(suffix, 2, 4)) print(str2.endswith(suffix, 2, 6))
true
da259fce7eb104901d329c727d138e52ecba159e
jayshreeuw/Python
/DataTypes/Strings/String_Special_Operators.py
2,309
4.4375
4
''' INDEXING String Special Operators 0 1 2 3 4 # Left to Right index -5-4-3-2-1# Right to Left index Assume string variable a = 'Hello' and b = 'Python' then: ''' a = 'Hello' b = 'Python' #Accessing variables in python print("Accessing variable i.e. a:",a[1]) print("") print("Accessing variable i.e. b:",b[-4]) #RANGE SLICING: print("Left to Right Index i.e a",a[0:4]) print("") print("Right to Left Index i.e b",b[1:6]) #Raw String print(r'\n') #Format Operator print("My name is %s and I was born in %d" % ('jaya',1981)) #Declaring variables var1= 'jaya' var2= 1981 print("My name is %s and I was born in %d" % (var1,var2)) #format operator #{} placeholders print("My name is {} and I was born in {}".format('Guido Van Rossum',1981)) #method #part of method , call variables print("My name is {} and I was born in {}".format(var1,var2)) #another way, call variables inside placeholders {} print("My name is {var3} and I was born in {var4}".format(var3='python',var4=1981)) #indexing method,first declare variables print("My name is {0} and I was born in {1}".format(var1,var2)) print("My name is {1} and I was born in {0}".format(var1,var2)) #Concatenation firstname = 'Guido' lastname = 'Rossum' fullname = firstname + " & " + lastname print(fullname) fullname = firstname + " " + lastname print(fullname) fullname = firstname[0] + " & " + lastname[0] print(fullname) #print 5 times first name print(firstname*5) #new program str1 = "Hello World!" #11 characters str2 = 'This is an example of string' alphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' num = '0123456789' print(str1[0]) print(str1[-1]) print(str1[2:6]) print(str1[2:8]) print(str1[2:7]) print(str1[:5]) print(str1*3) print(alphabets[0::2]) #zero based indexing print(num[0::2]) #zero based indexing print(num[0::3]) #zero based indexing print(num[0::6]) #zero based indexing print("updated string ", str1[:6] + "planet") print("updated string ", str1[:12] + "perl") #formatting of strings print("Your name is %s and your account id is %d" %("Kevin",14456)) print("Calling str1 {0} and calling str2 {1}".format(str1,str2)) print("Value1{} Value2{} and Value3{}".format("python",100,"pycharm")) print("Value1 {1} Value2 {0} and Value3 {2}".format("python",100,"pycharm"))
false
e03ebd8f212bd0aeff08dc2a317b101887f3ff4b
chapman-cpsc-230/hw3-EddieWadors
/turtlepoly.py
620
4.375
4
# -*- coding: utf-8 -*- """ File: turtlepoly.py Copyright (c) 2016 Eddie Wadors License: MIT - allow the user to input data and create a shape using turtle. """ import turtle string_1 = raw_input ("Enter a number of sides:") side_number = int (string_1) string_2 = raw_input ("Enter side length:") length_number = int (string_2) def draw_reg_polygon(t, num_sides, side_len): for i in range(num_sides): t.forward(side_len) t.left(360.0/num_sides) bob = turtle.Pen() for j in range(1): draw_reg_polygon(bob,side_number,length_number) stopper = raw_input("Hit <enter> to quit.") turtle.bye()
true
b250f5084e0efef7d8c651a2e0894d477daae7ff
hkneal/DojoAssignments
/Python/LinkedList.py
2,857
4.15625
4
class Node(object): def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self): self.head = None self.numOfNodes = 0 def addToFront(self, newNode): newNode.next = self.head self.head = newNode self.numOfNodes += 1 def deleteFromFront(self): if self.head is None: print ("The list is empty!") else: currentNode = self.head self.head = currentNode.next del currentNode self.numOfNodes -= 1 def addToEnd(self, newNode): if self.head is None: #if there is an empty list self.head = newNode else: lastNode = self.head while True: if lastNode.next is None: break lastNode = lastNode.next lastNode.next = newNode self.numOfNodes += 1 def deleteFromEnd(self): if self.head is None: print ("The list is empty!") else: lastNode = self.head while True: if lastNode.next is None: previousNode.next = None; del lastNode self.numOfNodes -= 1 break previousNode = lastNode lastNode = lastNode.next def insertAt(self, newNode, position): #if position > numNodes calls addToEnd(self, newNode) currentNode = self.head currentPosition = 1 while True: if currentNode.next is None: self.addToEnd(newNode) break if position == 1: self.addToFront(newNode) break if currentPosition == position: previousNode.next = newNode newNode.next = currentNode self.numOfNodes += 1 break previousNode = currentNode currentNode = currentNode.next currentPosition += 1 def printList(self): currentNode = self.head while True: print currentNode.data if currentNode.next is None: break currentNode = currentNode.next def getNumOfNodes(self): return self.numOfNodes linkedList = LinkedList() firstNode = Node("Hiram") secondNode = Node("Kevin") linkedList.addToFront(firstNode) linkedList.addToFront(secondNode) linkedList.addToEnd(Node("Neal")) linkedList.addToEnd(Node("Alana")) linkedList.insertAt(Node("Coleman"), 9) linkedList.printList() print linkedList.getNumOfNodes() linkedList.deleteFromFront() linkedList.printList() print linkedList.getNumOfNodes() linkedList.deleteFromEnd() linkedList.printList() print linkedList.getNumOfNodes()
true
0eceb520c133a0b162d8390f7a12f324dc533823
jaimersoncorreia/mundo2
/mundo01/desafios/desafio023.py
607
4.15625
4
''' Exercício Python 023: Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados. ''' numero = str(input('Informe um número: ')) ''' print('Unidade: {}'.format(lista[3])) print('Dezena: {}'.format(lista[2])) print('Centena: {}'.format(lista[1])) print('Milhar: {}'.format(lista[0])) ''' n = int(numero) print(n) unidade = n // 1 % 10 dezena = n // 10 % 10 centena = n // 100 % 10 milhar = n // 1000 % 10 print('Unidade: {}'.format(unidade)) print('Dezena: {}'.format(dezena)) print('Centena: {}'.format(centena)) print('Milhar: {}'.format(milhar))
false
fd1e7f767edcb7075b352c3eba1aebdc08a5147c
Darshnadas/100_python_ques
/DAY8/day8.24.py
560
4.21875
4
""" Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions. Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input() And add document for your own function """ print(abs.__doc__) print(int.__doc__) print(str.__doc__) def pow_num(n,p): ''' Return square of an interger input ''' return n**p print(pow_num(4,2)) print(pow_num.__doc__)
true
4b1e3ae8a71291421d90a47fd6719a952c900012
Darshnadas/100_python_ques
/DAY13/day13.47.py
299
4.3125
4
""" Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. """ class Circle(): def __init__(self,r): self.r = r def area(self): return 3.1416 *(self.r** 2) circle = Circle(5) print(circle.area())
true
c60982f3c6d7d5bdd41f7387bca7a2e5a0512ff8
Darshnadas/100_python_ques
/prac_codes/init.py
545
4.125
4
""" Construct a class with init method """ class Student: def __init__(self,name,branch,year): self.name = name self.branch = branch self.year = year print("A sudent object is created.") def print_details(self): print("Name:", self.name) print("Branch:", self.branch) print("Year:", self.year) std1 = Student('Darshna', 'ECE', '2021') std2 = Student('Deshna', 'CSE', '2031') std3 = Student('Sonia', 'IT', '1997') std1.print_details() std2.print_details() std3.print_details()
false