blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c2a32f21b81a6f0b6ef647ebce2da833fafc8997
Vsevolod-IT/python_projects
/algorithms_and_data_structure/lesson_2/task_2.py
1,262
4.4375
4
'''Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).''' def var_1(num): # начиная с 20 до 25 знаков функция тормозит, если больше то работает вечно))) even, odd = 0, 0 num = int(num) while num: checking_num = num // 10 ** 0 % 10 if checking_num % 2 ==0: even += 1 else: odd += 1 num = num // 10 var_1(num) return f'четных:{even}, нечетных:{odd}' def var_2(num): even, odd = 0, 0 num = str(num) for i,k in enumerate(num): if int(k) % 2 == 0: even += 1 else: odd += 1 return print(f'четных: {even}, нечетных: {odd}') def var_3(num): even, odd = 0, 0 digit = '2,4,6,8' for i in num: if i in digit: even += 1 else: odd += 1 return print(f'четных:{even}, нечетных:{odd}') num = input('введите число --> ') print(var_1(num)) var_2(num) var_3(num)
false
6882df529d6eac3d58f15a3eac7fe0d9742df8ab
Vsevolod-IT/python_projects
/algorithms_and_data_structure/lesson_3/task_5.py
833
4.25
4
'''В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный». Это два абсолютно разных значения.''' import random a = [random.randint(-100,100) for i in range(50000000)] #print(a) min = a[0] for i in a: if i < min: min = i if min < -1: print(f'максимально отриц элемент это --> {min}') elif min == -1: print(f'максимально отриц элемент это --> {min}') else: print(f'в массиве нет отрицательных чисел')
false
0afbcb97b22db5ddb35b6ce63f80ebfe209d507a
emad555/python_projects
/r_p_s/r_p_s.py
1,508
4.125
4
from random import randint Rock = "Rock" Paper = "Paper" Scissors = "Scissors" while True: x = randint(1,3) your_input = input("Choose Rock, Paper, Scissors!") if x == 1 and your_input == "Rock": computer = Rock print("Computer choose: ", computer) print("Tie!") if x == 1 and your_input == "Scissors": computer = Rock print("Computer choose: ", computer) print("You lost!") if x == 1 and your_input == "Paper": computer = Rock print("Computer choose: ", computer) print("You Won!") if x == 2 and your_input == "Rock": computer = Paper print("Computer choose: ", computer) print("You lost!") if x == 2 and your_input == "Scissors": computer = Paper print("Computer choose: ", computer) print("You Won!") if x == 2 and your_input == "Paper": computer = Paper print("Computer choose: ", computer) print("Tie!") if x == 3 and your_input == "Rock": computer = Scissors print("Computer choose: ", computer) print("You Won!") if x == 3 and your_input == "Scissors": computer = Scissors print("Computer choose: ", computer) print("Tie!") if x == 3 and your_input == "Paper": computer = Scissors print("Computer choose: ", computer) print("You lost!")
true
eea534564a94f955bbde2687e79c4b79e498efaf
Ramtecs/SelftaughtPythonCourse
/Dictionaries.py
2,178
4.28125
4
_author_ = 'Ramses Murillo' '''/import datetime library import datetime Print("Creation date is: ", datetime.datetime.now()) ''' import datetime todaysdate = datetime.datetime.now() print("File run", todaysdate) capitals = dict() capitals={"Costa Rica": "San Jose","Puerto Rico": "San Juan"} print(capitals) answer =capitals["Costa Rica"] print(answer) #dictionary keys must be immuttable, that is why Tuples can be dictionary keys but not Lists # key , Value # you can check if there is a kew in a dictionary but not a value print("Costa Rica" in capitals) print("Costa Rica" not in capitals) #delete a key value pair del capitals ["Costa Rica"] print(capitals) rhymes = {"1": "fun","2": "blue","3": "me","4": "floor","5": "live",} n= input("Type a number between 1 and 5:") if n in rhymes: rhyme = rhymes[n] print(rhyme) else: print("Not found") ''' 1. Create a dictionary that contains different attributes about you: height, favorite color, favorite author, etc. 2. Write a program that lets the user ask your height, favorite color, or favorite author, and returns the result from the dictionary you created in challenge 1. ''' aboutme ={"hieght": "5.7","favorite color": "blue","favorite author": "Garcia Marquez"} print(aboutme) q1 =input("Please, ask about my height?") answer =aboutme["hieght"] print ("I am ",answer," feet tall") q2 =input("Please, ask about my favorite color? ") answer =aboutme["favorite color"] print ("My favorite color is ",answer) q3 =input("Pelase, ask about my favorite author? ") answer =aboutme["favorite author"] print ("My favorite author is ",answer) #3. Create a dictionary mapping your favorite musicians to a list of your favorite songs by them. MyFavMus={"Cat Stevens": "Wild world","Stevie Wonder": "I just called to say","Joan Manuel Serrat": "Pueblo blanco"} print("My favorite music by author and favorite song are: ") answer = MyFavMus["Cat Stevens"] print("1.Cat Stevens with the song '",answer,"'") answer = MyFavMus["Stevie Wonder"] print("2.Stevie Wonder with the song '",answer,"'") answer = MyFavMus["Joan Manuel Serrat"] print("3.Joan Manuel Serrat with the song '",answer,"'")
true
896d6af31d291fedea1db490f969ceddcbbbb694
Ramtecs/SelftaughtPythonCourse
/MoreOOP.py
2,352
4.34375
4
''' 1. Add a square_list class variable to a class called Square so that every time you create a new Square object, the new object gets added to the list. 3. Write a function that takes two objects as parameters and returns True if they are the same object, and False if not. ''' #1 class Square(): square_list= [] def __init__(self, w, l): self.width = w self.len = l self.square_list.append((self.width, self.len)) def print_size(self): print("""{} by {}""".format(self.width, self.len)) print("Number 1:") square1 = Square(10,10) square2 = Square(5,5) square3 = Square(20,20) print(Square.square_list) #2. Change the Square class so that when you print a Square object, a message prints telling you the len of each of the four sides of the shape. # For example, if you create a square with Square(29) and print it, Python should print 29 by 29 by 29 by 29. class Square(): def __init__(self, l): self.len = l def print_size(self): print("""{} by {} by {} by {}""".format(self.len, self.len, self.len, self.len)) square1=Square(29) print("Number 2:") print(square1.print_size()) #3. Write a function that takes two objects as parameters and returns True if they are the same object, and False if not. class Sphere: def __init__(self, Object1, Object2): self.type1 = Object1 self.type2 = Object2 def compare_sphere(self): if(self.type1 == self.type2): #print("They are the same") print("""{} is the same as {}""".format(self.type1, self.type2)) else: #print ("They are not the same") print("""{} is not the same as {}""".format(self.type1, self.type2)) print("Number 3:") #sphereinstance =Sphere('baseball', 'football') sphereinstance =Sphere('baseball', 'baseball') print(sphereinstance.compare_sphere()) sphereinstance =Sphere('baseball', 'basketball') print(sphereinstance.compare_sphere()) ''' output: C:\Users\code\AppData\Local\Programs\Python\Python37\python.exe C:/Users/code/PycharmProjects/SelftaughtPythonCourse/SelftaughtPythonCourse/Files/MoreOOPs.py Number 1: [(10, 10), (5, 5), (20, 20)] Number 2: 29 by 29 by 29 by 29 None Number 3: baseball is the same as baseball None baseball is not the same as basketball None Process finished with exit code 0 '''
true
2e163f76a06c19559d89b268f5b8d2c858ebfb37
NavneethRajan/Learning-Python
/STP-PracticeSets/Chapter 4/1.py
303
4.1875
4
# Write a function that takes a number as an input and returns that number squared def square(x): """ Returns x ** 2 :param x: int. :return: int x to the power of 2. """ return(x ** 2) a = input("Type in a number: ") a = int(a) print(square(a))
true
edafb03b683c9e8b14c628c3b2402e5d5f8ea5c4
NavneethRajan/Learning-Python
/STP-PracticeSets/Chapter 4/3.py
457
4.15625
4
# Write a function that takes 3 required parameters and 2 optional parameters def f(x, y, z, a = 10, b = 20, c = 30): """ Returns (x + y + z) * (a + b + c) :param x: int. :param y: int. :param z: int. :param a: int. :param b: int. :param c: int. :return: int (sum of x, y, and z) multiplied by (sum of a, b, and c), """ return((x + y + z) * (a + b + c)) result = f(1, 2, 3) print(result)
true
39b3d2d1f6e0489014ce1c7c2c6f0e8600326874
haripbalineni/learnpython
/maps.py
392
4.1875
4
#map(function,data) from random import shuffle def jumble(word): anagram = list(word) shuffle(anagram) return ''.join(anagram) words = ['beetroot','carrot','tomatoes'] anagrams = [] #using for loop for word in words: anagrams.append(jumble(word)) print(anagrams) #using comprehension print([jumble(word) for word in words]) #using map print(list(map(jumble,words)))
true
0efbad6d43825d73cc9a666359e727d15bfc0add
haripbalineni/learnpython
/string_format.py
574
4.125
4
# format string num1 = 10.236112321321 num2 = 23.36945645 #PREVIOUS # print('num1 is',num1,'and num2 is',num2) #FORMAT METHOD # print('num1 is {0} and num2 is {1}'.format(num1,num2)) # print('num1 is {0} \nnum2 is {1}'.format(num1,num2)) #next line # print('num1 is {0:.4} \nnum2 is {1:.5}'.format(num1,num2)) #no of digits to print # print('num1 is {0:.4f} \nnum2 is {1:.3f}'.format(num1,num2)) #no of decimals to print #USING F-STRINGS print(f'num1 is {num1} \nnum2 is {num2}') print(f'num1 is {num1:.4f} \nnum2 is {num2:.3f}') #no of decimals to print
false
62cdf958d1af3c59042e0b5d4d7bdb664a41b378
haripbalineni/learnpython
/ranges.py
650
4.25
4
# RANGES # syntax: range(arraystart,arraystop,increment/decrement) # syntax: range(array) # prints from 0 to 499 # for n in range(500): # print(n) # prints from 499 to 401 # for n in range(500,400,-1): # print(n) # prints from 3 to 9 # for n in range(3,10): # print(n) # prints from 3 to 9, incrementing 2 # for n in range(3,10,2): # print(n) burgers = ['chicken','beef','veg','double','regular','double'] # to Print the values for n in range(0,len(burgers),1): print(n + 1,burgers[n]) # to Print the values in reverse order # for n in range(len(burgers) -1, -1, -1): # print(n + 1,burgers[n])
true
dd92a168c2e30340ff4c5773b10a7c5f9c908a42
kiarashazadian/pymft
/homework02/triangle.py
907
4.1875
4
# numbers = [input("enter 3 numbers please")] ''' inputs = [] x=3 for i in range(3): # loop 3 times inputs.append(input("enter number")) print(inputs) ''' print('enter 3 numbers with space') numbers = list(map(int, input().split())) print(numbers) if numbers[0] + numbers[1] > numbers[2] and numbers[1] + numbers[2] > numbers[0] and numbers[2] + numbers[0] > numbers[ 1]: print("its triangle") else: print("its not triagnle") if numbers[0] == numbers[1] and numbers[1] == numbers[2] and numbers[0] == numbers[2]: print("its Equilateral") else: print("its not Equilateral") if numbers[0] == numbers[1] or numbers[1] == numbers[2] or numbers[0] == numbers[2]: print("its Isosceles") else: print("its not Isosceles") highest = int(max(numbers)) #numbers.remove(highest) if numbers[0] ** 2 + numbers[1] ** 2 == highest ** 2: print("its right") else: print("its not right")
true
d6b64456fd36d3fa55a3b28ab2f6c77b4e447130
shuyangren1/uwdatascience
/400/L04 Labs/L04-A-1-Dataframes.py
840
4.1875
4
""" # UW Data Science # Please run code snippets one at a time to understand what is happening. # Snippet blocks are sectioned off with a line of #################### """ # Make the pandas package available import pandas as pd # Create an empty data frame called Cars Cars = pd.DataFrame() # View the data frame Cars.head() ################# # Create a column of price categories that has values for the first 4 cars Cars.loc[:,"buying"] = ["vhigh", "high", "low", "med"] # Create a column of number of doors that has values for the first 4 cars Cars.loc[:,"doors"] = [2, 2, 4, 4] # View the data frame Cars.head() ################## # Add a fifth row of data Cars.loc[4] = ["vhigh", 3] # View the data frame Cars.head() ################## # View the data types of the columns in the data frame Cars.dtypes ####################
true
ff5b00fd8b6e39198d14465e7470c6b497703a10
alazaroc/python
/basics/11.logical_operations.py
318
4.3125
4
# Logical operations is_high_income = True is_good_credit = False if is_high_income and is_good_credit: print("OK 1") else: print("NO 1!!") if is_high_income or is_good_credit: print("OK 2") else: print("NO 2!!") if is_high_income and not is_good_credit: print("OK 3") else: print("NO 3!!")
true
acc605183089108ad4e8f33d100973aa2178a2a9
amrithamat/python
/pythonprogrms/differnt_type_of_functions/newpgm.py
561
4.15625
4
"""def add(num1,num2): res=num1+num2 print(res) add(10,20)""" #variable length arguments method """def add(*nums): print(nums) add(10,20) add(10,20,30,40) add(10,11,12,13,14)""" def add(*args): total=0 for num in args: total+=num print(total) add(10,20) add(10,20,30,40) add(10,11,12,13,14) def printEmp(*args):#*args accepted as tuple print(args) printEmp("kakkanad","ajay","aluva") def printEmp(**args):#**args accepted as dict ie, key value pairs print(args) printEmp(home="kakkanad",name="ajay",working="aluva")
false
b28bca6464d06b00912741d5e6dd44ca50abcc5d
amrithamat/python
/pythonprogrms/pythondatastructures/listprograms/list_part1.py
571
4.1875
4
#define by using [] lst=[] print(type(lst)) #list function lst=["java","pyhton","c#","javasript"] # 0 1 2 3 print(lst[0:4])#in order #slicing print(lst[0]) print(lst[3]) print(lst[-1]) print(lst[-2]) print(lst[-1:-4:-1]) print(lst[4:0]) print(lst[-1:-5:-1])#reverse print(lst[0:4:2]) print(lst[:3]) #to add a new element into the list lst.append("dart") #replacing java by ruby lst[0]="ruby" print(lst) #inserting an object into a specific position lst.insert(3,"perl") print(lst) #one by one iteration for item in lst: print("item",item)
false
37007c7f651dec5f68f46a219b27e67492531294
amrithamat/python
/pythonprogrms/swappingprogram.py
776
4.15625
4
#using a temp num1=10 num2=20 print("values b4 swapping num1=",num1,"num2=",num2) temp=num1 num1=num2 num2=temp print("values after swapping num1=",num1,"num2=",num2) #without using temp value num3=10 num4=20 print("values b4 swapping num3=",num3,"num4=",num4) num3=num3+num4 num4=num3-num4 num3=num3-num4 print("values after swapping num3=",num3,"num4=",num4) #method only using in python for swapping num5=10 num6=20 print("values b4 swapping num5=",num5,"num6=",num6) (num5,num6)=(num6,num5) print("values after swapping num5=",num5,"num6=",num6) #input passing num7=input("enter the value for num7") num8=input("enter the vlaue for num8") print("values b4 swapping num7=",num7,"num8=",num8) (num7,num8)=(num8,num7) print("values after swapping num7=",num7,"num8=",num8)
true
6b5d62778b34b08448543d8e83f3553c46bb0ead
anasibrahimgm/Programming-Challenges
/CodeForces/868/868A.py
1,796
4.15625
4
# # As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. # # Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. # # Input # The first line contains two lowercase English letters — the password on the phone. # # The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows. # # The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. # # Output # Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. # # You can print each letter in arbitrary case (upper or lower). # # # //SOLUTION # # to have the password, there should be the first char of the passowrd at the end of a string and the second char of password at the beginning # password = input() n = int(input()) firstLetter = 0 secondLetter = 0 found = 0 for i in range(n): inputStr = input() if inputStr == password: found = 1 if inputStr[1] == password[0]: firstLetter = 1 if inputStr[0] == password[1]: secondLetter = 1 if ( found or (firstLetter and secondLetter) ): print('YES') else: print('NO')
true
88c829a4c1fb495803ef337c3c561ddb1edb297e
MaddieVince/python-exercises
/loops-3.py
301
4.5625
5
# Use a while loop to ask the user for three names and append them to a list, then use a for loop to print the # list. names_list = [] name_add = "" name_add = input("Enter a name: ") while len(name_add) > 0: names_list.append(name_add) name_add = input("Enter a name: ") print(names_list)
true
4a0c94685f8e04c5e4856a632545e2ec54c3c63e
MaddieVince/python-exercises
/functions-2.py
576
4.3125
4
# Calculate the mean of a list of numbers # User to input numbers # Stop when a blank input is entered # Use the sum of the integers and total numbers to calculate mean # Print mean def calculate_mean(total_sum, num_items): mean = total_sum / num_items print(f"{mean:.2f}") num_list = [] num_input = 0 total_sum = 0 num_items = 0 num_input = input("Enter a number: ") while len(num_input) > 0: total_sum += int(num_input) num_items += 1 num_input = input("Enter a number: ") # print(total_sum, num_items) calculate_mean(total_sum, num_items)
true
412921fbe702e7532fbafbcf5a7978755b6b0e8d
MaddieVince/python-exercises
/variables-4.py
366
4.28125
4
# Input user name and height #Input 1, name = William, height = 192 name = input("What is your name? ") height = input("What is your height, in centimeters? ") print(f"{name} is {height}cms tall") #Input 1, name = Roary, height = 27 name = input("What is your name? ") height = input("What is your height, in centimeters? ") print(f"{name} is {height}cms tall")
true
9e76a121de5ea31249d5c690550997e84e5278ca
PruthviJ19/pruthvijana
/prg1.py
1,813
4.125
4
a = 2 #assigning the values b = 330 #print("A") if a > b else print("B") #using if and else in 1 line #to print the greater value a = 330 #assigning the values b = 330 #print("A") if a > b else print("=") if a == b else print("B") #to check the equality # one line if else stmt a = 80 #initialising the values b = 60 c = 90 if a > b and c > a: #print("both r true state") # and operator #comparing the btw 3 values x = 38 #assign the value of x if x > 10: #checking the condtion of x #print("above 10,") #comparing value of x with 10 # if x > 20: #checking whether x is greater than 20 #print("and also above 20") #to print if conditon above condition is true # else: #print("but not above 60") #nested if stmts #checking value of x and to print else stmt i = 1 #initialise the i value while i < 5: #checking condition of i # print(i) #to print i if condition is true i += 1 3increment operation till condition gets false #while condition i = 1 #assign value of i while i < 6: #checking condition of i # print(i) #if true ,priniting the value i if i == 3: #if value of i equals to 3,it breaks the execution break i += 1 #increment oprtn if i is not equal to 3 #exit of loop for x in range(6): #assign the range to x # print(x) #print value x upto the range #using range() for x in range(2,6):#assign specific range to x # print(x) #print the range #specific range()
true
81e798155fcac3010bf5b2e894cd7803f6094276
WA-Informatics/Python-course
/Problem Set 1/ps1.py
337
4.125
4
# Variable # String myString = "Hi" # Numbers myInteger = 1 myDouble = 3.3141 # How to print out a value print(myString) # How to print multipal things print(myString + str(myInteger)) #Changing a variables type str(myDouble) # This will give you "1" int(myDouble) # --> 3 and will get rid of everything after the decimal is gone
true
200a47a85d53ae70ed538a43076ddb897e3c7d34
innakaitert/programWithUs
/Day1/again04.py
310
4.28125
4
letter = input("Enter any letter: ") if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u': print ("The entered letter is a vowel.") elif letter == 'y': print("Sometimes 'y' is a vowel but sometimes it is a consonant.") else: print("The letter you entered is a consonant.")
true
c855b4e70b5104222ed03d060ec0b377c4e6321d
innakaitert/programWithUs
/Day2/ex0.py
725
4.1875
4
word = "Good morning class" first_half = word[0: len(word)//2] second_half = word[-1: (len(word)//2)-1: -1] print(first_half) print(second_half) word = "Good morning class" first_half = word[0: len(word)//2] second_half = word[-1: (len(word)//2): -1] print(first_half) print(second_half) word = "Good morning class" first_half = word[0: len(word)//2] second_half = word[-1: (len(word)//2)-1: 1] print(first_half) print(second_half) word = "Good morning class" first_half = word[0: len(word)//2] second_half = word[(len(word)//2)-1::] print(first_half) print(second_half) word = "Good morning class" first_half = word[0: len(word)//2] second_half = word[(len(word)//2)::] print(first_half) print(second_half)
false
a976d64567d37d1fc715c5d0ce7407128006d7c6
NumNine9/PythonPlayGround
/Python- Search and Replace.py
437
4.28125
4
''' one of the most important 're' methods are that use regular expressions is sub syntax: re.sub(pattern,repl,string,count=0) this method replaces all occurrences of the pattern in string with repl, substituting all occurences, unless count provided. This method returns the modified string ''' import re text = 'My name is George. Hi George.' pattern = r'George' newtext= re.sub(pattern, 'Amy',text) print(newtext)
true
dfc9a7cb9cd6426b3c4e35ae0d254cc96056113a
MahmoudHassan/hacker-rank
/30DaysOfCode/Day3.py
968
4.375
4
""" Task Given an integer,n, perform the following conditional actions: If n is odd, print Weird If n is even and in the inclusive range of 2 to 5, print Not Weird If n is even and in the inclusive range of 6 to 20, print Weird If n is even and greater than 20, print Not Weird Complete the stub code provided in your editor to print whether or not n is weird. Input Format A single line containing a positive integer,n. Constraints 1=< n <=100 Output Format Print Weird if the number is weird; otherwise, print Not Weird. Sample Input 0 3 Sample Output 0 Weird Sample Input 1 24 Sample Output 1 Not Weird """ # !/bin/python3 import math import os import random import re import sys if __name__ == '__main__': N = int(input()) if N % 2 == 1: print('Weird') elif N % 2 == 0: if 2 <= N <= 5: print('Not Weird') elif 6 <= N <= 20: print('Weird') elif N > 20: print('Not Weird')
true
ed78a3dadd64981e5d0406370ece57ab39422969
MahmoudHassan/hacker-rank
/30DaysOfCode/Day16.py
652
4.375
4
""" Task Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String. Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a 0 score. Input Format A single string, S. Output Format Print the parsed integer value of S, or Bad String if S cannot be converted to an integer. Sample Input 0 3 Sample Output 0 3 Sample Input 1 za Sample Output 1 Bad String """ #!/bin/python3 import sys S = input().strip() try: print(int(S)) except ValueError: print('Bad String')
true
24f11bfef78e1e05428babc0b535a42eba842197
Cxiaojie91/HgwzPractice
/python_practice/python_basic/python_function.py
1,287
4.375
4
""" 1.函数的作用是封装,可重复使用的,用来实现单一或相关联功能的代码段; 函数能提高应用的模块性和代码的重复利用率 2.以def关键词开通,后接函数名和圆括号() 冒号起始 注意缩进 在圆括号中定义参数 函数说明--文档字符串 3.用return结束函数 选择性地返回一个值给调用方 不带表达式的return或不写return函数,相当于返回none """ # 函数定义 def func1(a, b, c): """ 给程序员看的注释,一般放函数func1的作用,只是一个规范,增加函数的可读性 :param a: :param b: :param c: :return: """ # 使用tab添加缩进 print("这是一个函数") # a在函数值被使用,所以在定义的地方会变亮 # b和c没有在函数中被使用,故是置灰状态 # pycharm快捷键ctrl+d可复制一行代码 print("参数:", a) print("参数:", b) print("参数:", c) # return可加可不加 return """ 函数的调用形式 调用时的传参 位置参数 """ # 函数的调用,函数中所输入的参数和函数定义时的参数位置是一一对应的 func1(1, 2, 3) def func_return(r1, r2, r3, r4): return r1 + r2 + r3 + r4 print(func_return(1, 10, 100, 1000))
false
3c8eba5a916e6174389d8ae981fb7bf219b75fc8
symygy/100DaysOfCode
/#3/advanced_operations_on_strings.py
837
4.1875
4
# tutorial: https://www.youtube.com/watch?v=vTX3IwquFkc&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=22 import datetime person = {'name' : 'Michal', 'age' : 29} sentence = 'My name is {} and I am {} years old'.format(person['name'], person['age']) print(sentence) class Person(): def __init__(self, name, age): self.name = name self.age = age person = Person('Miki', '29') sentence = 'My name is {0.name} and I am {0.age} years old'.format(person) print(sentence) sentence = 'My name is {name} and I am {age} years old'.format(name = 'Marian', age='33') print(sentence) my_date = datetime.datetime(2020, 2, 21, 12, 30, 00) print(my_date) sentence = '{:%B %d, %Y}'.format(my_date) print(sentence) sentence = '{0:%B %d, %Y} fell on a {0:%A} and was the {0:%j} day of the year'.format(my_date) print(sentence)
true
b93ba12f8b33ae0a93128f7401826ebf8e938f22
mihrael/techdegree-project-1
/guessing_game.py
1,940
4.34375
4
""" Python Web Development Techdegree Project 1 - Number Guessing Game -------------------------------- """ import random def game_controller(): answer = random.randint(1, 10) global attempts attempts = 1 wrong = True while wrong: guess = guess_function() if guess == answer: wrong = False else: print ("It's lower") if guess > answer else print("It's higher") attempts += 1 if guess == answer: print("You guessed the correct number! It took you {} attempts".format(attempts)) def guess_function(): number = True while number: try: guess = int(input("Guess a number between 1-10 ")) if guess < 1 or guess > 10: raise ValueError("Your guess has to be a number between 1-10") else: number = False except ValueError as err: print("Your guess has to be a number between 1-10") return(guess) def check_highscore(score): if highscore == 0: highscore = score def start_game(): high_score = 0 play = True print("Welcome to the number guessing game!") while play: game_controller() if high_score == 0: high_score = attempts elif attempts < high_score: high_score = attempts print("The highscore is {}".format(high_score)) play_again = input("Would you like to play again? [Yes/No] ") try: if play_again.lower() not in ("yes","no"): raise ValueError("Your answer has to be either 'Yes' or 'No'") elif play_again.lower() == "no": play = False except ValueError as err: print("Your answer has to be either 'Yes' or 'No'") print("The game is over") if __name__ == '__main__': # Kick off the program by calling the start_game function. start_game()
true
3ba97d170795236a490b74858c745b0a0a552e65
ashishkrishan1995/dataStructures
/Basic/basic python programs/Finding-a-leap-year.py
482
4.375
4
# finding whether the entered year is leap year or not. # Enter the year as input and output will be True or false def is_leap(year): #function to check the leap year leap = False # logic here if year%4 == 0: if year%100 == 0 : if year%400 == 0: leap=True else : leap=False else : leap=True return leap year=int(input()) #taking input print(is_leap(year)) #printing the result
true
97965b4ca7081cd8c8be1d63f198e75d691d263e
imatyukin/python
/HackerRank/Python/02-Basic Data Types/List_Comprehension.py
1,066
4.21875
4
""" Let's learn about list comprehensions! You are given three integers x, y and z representing the dimensions of a cuboid along with an integer n. Print a list of all possible coordinates given by (i, j, k) on a 3D grid where the sum of i + j + k is not equal to n. Here, 0 <= i <= x; 0 <= j <= y; 0 <= k <=z. Please use list comprehensions rather than multiple loops, as a learning exercise. Example x = 1 y = 1 z = 2 n = 3 All permutations of [i, j, k] are: [[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2]]. Print an array of the elements that do not sum to n = 3. [[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,2]] Input Format Four integers x,y,z and n, each on a separate line. Constraints Print the list in lexicographic increasing order. Sample Input 0 1 1 1 2 Sample Output 0 [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]] """ x, y, z, n = (int(input()) for _ in range(4)) print([[i, j, k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if ((i+j+k) != n)])
true
4452c531eca79e1f1072acb453a5f2b38acde668
imatyukin/python
/ProgrammingInPython3/exercise_1_5.py
2,389
4.25
4
#!/usr/bin/env python3 # 5. It would be nice to be able to calculate the median (middle value) as well # as the mean for the averages program in Exercise 2, but to do this we must # sort the list. In Python a list can easily be sorted using the list.sort() # method, but we haven’t covered that yet, so we won’t use it here. Extend # the averages program with a block of code that sorts the list of # numbers—efficiency is of no concern, just use the easiest approach you # can think of. Once the list is sorted, the median is the middle value if the # list has an odd number of items, or the average of the two middle values # if the list has an even number of items. Calculate the median and output # that along with the other information. # # This is rather tricky, especially for inexperienced programmers. If you # have some Python experience,you might still find it challenging, at least if # you keep to the constraint of using only the Python we have covered so far. # The sorting can be done in about a dozen lines and the median calculation # (where you can’t use the modulus operator, since it hasn’t been covered yet) # in four lines. A solution is provided in average2_ans.py. prompt = 'enter a number or Enter to finish: ' numbers = [] count = sum = 0 lowest = None highest = None mean = number = input(prompt) while(number): try: if lowest is None or lowest > int(number): lowest = int(number) if highest is None or highest < int(number): highest = int(number) numbers.append(int(number)) count += 1 sum += int(number) number = input(prompt) except ValueError as err: print(err) lowest = None highest = None number = input(prompt) mean = sum / count print('numbers:', numbers) print('count =', count, 'sum =', sum, 'lowest =', lowest, 'highest =', highest, 'mean =', mean) # Сортировка методом пузырька n = 1 while n < len(numbers): for i in range(len(numbers)-n): if numbers[i] > numbers[i+1]: numbers[i], numbers[i+1] = numbers[i+1], numbers[i] n += 1 print('sorted numbers:', numbers) half = int(len(numbers)/2) if len(numbers)/2 == half: print('median =', (numbers[half-1]+numbers[half])/2) else: print('median =', int(numbers[half]))
true
571685a9582d509e0c7d5ec9be4429cfdc677832
imatyukin/python
/ProgrammingInPython3/exercise_1_3.py
1,930
4.21875
4
#!/usr/bin/env python3 # 3. In some situations we need to generate test text—for example, to populate # a web site design before the real content is available, or to provide test # content when developing a report writer. To this end, write a program that # generates awful poems (the kind that would make a Vogon blush). # # Create some lists of words, for example, articles (“the”, “a”, etc.), subjects # (“cat”, “dog”, “man”, “woman”), verbs (“sang”, “ran”, “jumped”),and adverbs # (“loudly”, “quietly”, “well”, “badly”). Then loop five times, and on each # iteration use the random.choice() function to pick an article, subject, verb, # and adverb. Use random.randint() to choose between two sentence structures: # article, subject, verb, and adverb, or just article, subject, and verb, # and print the sentence. Here is an example run: # # awfulpoetry1_ans.py # another boy laughed badly # the woman jumped # a boy hoped # a horse jumped # another man laughed rudely # # You will need to import the random module. The lists can be done in about # 4–10 lines depending on how many words you put in them, and the loop # itself requires less than ten lines, so with some blank lines the whole # program can be done in about 20 lines of code. A solution is provided as # awfulpoetry1_ans.py. import random articles = ["the", "a", "another"] subjects = ["cat", "dog", "man", "woman", "boy", "horse"] verbs = ["sang", "ran", "jumped", "laughed", "hoped"] adverbs = ["loudly", "quietly", "well", "badly", "rudely"] struct_1 = articles, subjects, verbs, adverbs struct_2 = articles, subjects, verbs struct = struct_1, struct_2 for i in range(0, 5): sentence = '' for j in random.choice(struct): word = random.choice(j) sentence += ' ' + word print(sentence)
true
f3ec8f5712ae9a02324b18397c1b4bccecc613c9
Ahasun-h/python
/Weight_converter.py
459
4.125
4
weight = int(input('Enter your weight :')) input = input('Enter (K)k or (L)bs :') if input == 'k' or input == 'K': result = 2.20462 * weight elif input == 'l' or input == 'L': result = 0.453592 * weight print(f"Your weight is : {result}") #using upper care mathod of string if input.upper() == 'K': result = 2.20462 * weight elif input.upper() == 'L': result = 0.453592 * weight print(f"Your convert weight is : {result} ")
true
a37527340c6d556e70e986c3d32ac41f6592b1dc
Ahasun-h/python
/if_else_Syntax_Program.py
1,294
4.21875
4
is_hot = False is_cool = True if is_hot: print("Drink Water") print("Enjoy The Day") if is_hot: print("Drink Water") elif is_cool: print("Drink Hot Tea") else: print("It,s Lovely Day,Thank You") print("Enjoy The Day") Price = 100000 have_a_good_price = True if have_a_good_price : down_payment = 0.1 * Price else: down_payment = 0.2 * Price print(f"Down Payment $:{down_payment}") has_high_income = True has_good_cradit = True if has_high_income and has_good_cradit: # AND:Both must Be True print("Eligible for loan") get_loan_before = False has_criminal_racode = True if has_high_income or get_loan_before: # OR: One must be True print("Eligible for loan") if has_high_income and not has_criminal_racode: print("Eligible for loan") else: print("Not eligible for loan") name = input('Enter your name :') name_langth = (len(name)) print(name_langth) if name_langth <= 3: print("Name must be at least 3 character") elif name_langth >= 50: print("Name must be maximum least 50 character") else: print("Good Name") if len(name)<= 3 or len(name) >= 50: print("Your name must be at least 3 character or maximum 50 character ") else: print("good name")
true
87b9cd6e2787dd4756d02b5e91d56feaaff74c25
samyak1903/GUI-1
/A1.py
308
4.1875
4
#Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface. from tkinter import * root=Tk() hwL=Label(root,text='Hello World',font='Times 20 bold underline') hwL.pack() exitB=Button(root,text="Exit",command=root.destroy) exitB.pack() root.mainloop()
true
852fe26b4ab8389d320f2e038bad6bf40a91242c
Sainterman/holbertonschool-higher_level_programming
/0x06-python-classes/2-square.py
502
4.34375
4
#!/usr/bin/python3 """ class Square that defines a square AND validates size """ class Square: """ Square with size verification Attributes: __size (int): Must be Integer type and >= 0 """ __size = 0 def __init__(self, size=0): """ Instantiate with proper size a Square object """ if type(size) != int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") self.__size = size
true
58f358e9c8fa63245717f44f8a35976c528f5c37
anton-perez/assignment-problems
/Assignment 2/count_characters.py
390
4.28125
4
def count_characters(input_string): lowercase_str = list(input_string.lower()) return {char: lowercase_str.count(char) for char in lowercase_str} print("testing count_characters on input 'A cat!!!'...") assert count_characters('A cat!!!') == {'a': 2, 'c': 1, 't': 1, ' ': 1, '!': 3}, "count_characters('A cat!!!') should equal {'a': 2, 'c': 1, 't': 1, ' ': 1, '!': 3}" print("PASSED")
false
de9173795f02fc0e5c5b2d7c2a4492d5e880655e
ATaoFire/pythonTutorial
/fourChapter/dict.py
853
4.1875
4
#一个简单的字典 #一个将人名作为键的字典,每个人都用一个字典表示 #字典包含phone和addr,他们分别与电话号码和地址相关联 people = { 'Alice': { 'phone': 1234, 'addr': 'Foo drive 23' }, 'Beth': { 'phone': 1233, 'addr': 'Bar drive 23' }, 'Cecli': { 'phone': 1235, 'addr': 'Bax drive 23' } } #电话号码和地址的描述性标签,供打印输出时使用 lables = { 'phone': 'phone number', 'addr': 'address' } name = input('Name:') #查找电话还是地址 request = input('电话(p)或者地址(a):') #使用正确的键 if request == 'p': key = 'phone' if request == 'a': key = 'addr' #仅当名字是字典里的,打印 if name in people:print("{}'s {} is {}.".format(name, lables[key], people[name][key]))
false
1895030bd64e560b35c808f19d9ec75e327c9a3e
cvhs-cs-2017/sem2-exam1-lilychau
/Turtle.py
674
4.125
4
"""Create a Turtle Program that will draw a 3-dimensional cube""" import turtle lily = turtle.Turtle() n = int(input("Put in a number, and ill make a cube: ")) def ThreeDCubeFunc(lily, n): for i in range(4): lily.forward(n) lily.right(90) lily.left(45) lily.forward(n) lily.right(45) lily.forward(n) lily.right(135) lily.forward(n) lily.left(45) lily.forward(n) lily.left(135) lily.forward(n) lily.left(45) lily.forward(n) ThreeDCubeFunc(lily, n) input() """Import and Call the DrawRectangle(Anyturtle, l, w) function from the file MyFile.py""" from MyFile.py import DrawRectangle(Anyturtle, l, w)
false
219b0c31483cd8757b1c58a59e8aba63a02cfd59
bregord/challenges
/CoderBytes/Easy/Python/letterchanges.py
594
4.21875
4
def LetterChanges(str): newstr ='' for letter in str: if letter != ' ' and 'a' <= letter <= 'z' or 'A' <= letter <= 'Z': letter = chr(ord(letter)+1) if letter in ('a', 'e', 'i', 'o', 'u'): letter = letter.upper() newstr= newstr+letter elif letter == ' ': newstr = newstr + ' ' else: newstr = newstr + letter return newstr # keep this function call here # to see how to enter arguments in Python scroll down print LetterChanges(raw_input())
false
ef85c753e70cf8f03834a3dfdd2cba844cf010d3
vmsgiridhar/DSA
/11_Graphs/1_BFS.py
1,833
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 20 16:59:18 2021 @author: z003z7n """ # Node or Vertex class Node: def __init__(self, name): # Vertex Name or identifier self.name = name # Adjacent vertices of this Vertex self.adjacent_vertices = [] # if visited or not self.visited = False def Breadth_First_Search(start): # Queue follows FIFO queue = [start] # We will end the iteration only when queue is empty (When all the vertices are visited) while queue: # pop the first vertex inserted and then append the vertices of the popped vertex # also set the vertex to be visited visited = queue.pop(0) visited.visited = True print('{}'.format(visited.name)) # appending the adjacent_vertices to queue for n in visited.adjacent_vertices: if not n.visited: queue.append(n) #print('Queue is: {}'.format([i.name for i in queue])) if __name__ == '__main__': # Creating the Nodes node1 = Node("Amsterdam") node2 = Node("Brussels") node3 = Node("Frankfurt") node4 = Node("Glasgow") node5 = Node("Cairo") node6 = Node("Delhi") node7 = Node("Heathrow") node8 = Node("Essen") # Supplying the adjacent nodes to Nodes or Cities node1.adjacent_vertices.append(node2) node1.adjacent_vertices.append(node3) node1.adjacent_vertices.append(node4) node2.adjacent_vertices.append(node5) node2.adjacent_vertices.append(node6) node4.adjacent_vertices.append(node7) node6.adjacent_vertices.append(node8) #Implementing the BFS Breadth_First_Search(node1)
true
574d63ca4a70b84dc3e840d3a5984a8be6a4e1e3
vmsgiridhar/DSA
/5_Queues/Queue.py
1,318
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 3 13:56:20 2021 @author: z003z7n """ class Queue: def __init__(self): self.queue = [] def is_empty(self): return self.queue == [] #this operation has O(1) running time. def enqueue(self, data): self.queue.append(data) # O(N) linear runing time. How to solve this problem? Doubly Linked List # Using Doubly Linked List, we can reduce the time complexity of enqueue and dequeue to O(1) # We can't solve the problem using simple Linked List because, while enqueuing we will need to find the last item to add a new item, which take O(N) def dequeue(self): if self.size_queue() != 0: data = self.queue[0] del self.queue[0] return data else: return -1 #O(1) cconstant runninng time def peek(self): return self.queue[0] def size_queue(self): return len(self.queue) # implementation queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) print('Size: {}'.format(queue.size_queue())) print('Dequeue: {}'.format(queue.dequeue())) print('Size: {}'.format(queue.size_queue())) print('Peek item: {}'.format(queue.peek())) print('Size: {}'.format(queue.size_queue()))
true
dd3efbd59978555026e75d4f303d971ee6300a4c
ramranganath/Python
/test/primenum.py
693
4.21875
4
# listing the prime numbers between Range from 2 to till ... for i in range(2,60): j=2 counter=0 while(j<i): if i%j==0: counter=1 j=j+1 else: j=j+1 if counter==0: print(str(i) +" is a Prime Number") else: counter=0 """ for a in range(0,45,2): print(str(a) +" Even") for o in range(1,45,2): print(str(o) +" Odd Nums") day = "Monday" if day=="Tuesday" or day == "Monday": print("Today is Sunny") else: print("Today is Rainy") wt =60 for i in range(0,10): mwgt = wt/6 print(mwgt) wt=wt+1 """
false
184ea6cc2b766a342435047b844ad668640b8b56
jav2074/python-curso
/06_lists.py
1,619
4.34375
4
#################################################### ######################LISTAS######################## #################################################### demo_list = [1, 2, 'tres', 4, 5, ['uno', 2, 3, 4]] print(demo_list) # Constructor list() numbers = list((1, 'dos', 3, 4, 5, 6, 7)) print("numbers: " + str(numbers)) r = list(range(1, 10)) #Rango de una lista del 1 al 10 print(r) print(demo_list[2]) #Acceder al dato que se encuetra en la posicion seleccionada colors = ['Blue', 'Yellow', 'Red', 'Black'] print(colors) colors[1] = 'White'#Modifica el archivo que se encuentra en dicha posicion print(colors) colors.append('Green')#Metodo para agregar un dato a la lista print(colors) colors.extend(['Pink', 'Brown'])#Metodo para agregar varios datos a la lista print(colors) colors.extend(('White', 'Grey'))#Metodo para agregar varios datos a la lista print(colors) colors.insert(1, 'Purple')#Metodo para insertar en una posicion el cual se asigne ademas de que elemento va a asignar print(colors) colors.insert(len(colors), 'Gold')#Metodo para insertar en la ULTIMA posicion print(colors) colors.pop()#Metodo para eliminar algun elemento de la lista print(colors) colors.pop(2)#Metodo para eliminar algun elemento de la lista print(colors) colors.remove('Purple')#Metodo para eliminar el elemento asignado de la lista print(colors) #colors.clear()#Metodo para limpiar la lista #print(colors) colors.sort()#Metodo para ordenar alfabeticamente print(colors) colors.sort(reverse=True)#Metodo para ordenar de manera ordenada print(colors) print(colors.index('White')) print('Green' in colors)
false
311d49288d6f762305cf7b757455a1afab5c3cd3
balalex12/PracticesPython
/Various/Problem1.py
753
4.125
4
""" Perform a program that asks for two numbers: * If the numbers are different, add them up. * If they are negative, they must be multiplied. * Finally, if one number is negative and one positive number subtracts them. """ def doing_operations(num1, num2): operation = 0 if num1 < 0 and num2 < 0: operation = num1 * num2 elif (num1 < 0 and num2 > 0) or (num2 < 0 and num1 > 0): operation = num1 - num2 else: operation = num1 + num2 return operation try: num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) print("The result is: "+str(doing_operations(num1, num2))) except ValueError: print("Error: You did not enter a numerical value")
true
33271a27af3e2c63557b20aa7b50f98b1db231d7
NC2412/python
/Collatz Conjecture.py
371
4.15625
4
while True: steps = 1 number = int(input('Enter a number > 1.')) while number != 1: if number % 2 == 0: number /= 2 else: number *= 3 number += 1 steps+=1 print(steps) try: choice = input('Would you like to enter a new number? (y/n): ') except: print('Please enter a number.') if choice == 'y': continue else: break
true
8085c4ef9e6c3e8b0160ce2a15446cfe4f88fda1
itsniteshh/100Days-of-coding-with-python
/Day 7/6.11 cities.py
659
4.4375
4
cities= { "mumbai" : { "country": "India", "population": "15 crore", "fact": "It is also called, 'City of dreams'" }, "nile": { "country": "egypt", "population": "3 crores", "fact": "It is also called, 'city of the gods'" }, "bihar": { "country": "India", "population": "10 crore", "fact": "It is the birth place of godess Sita" } } for city, info in cities.items(): print(f"City name: {city}") print(f"It is a city in the country of {info['country']}") print(f"It has a total population of {info['population']}") print(f"Fact: {info['fact']}\n")
true
0f3292908804fb0f16236092d5b4b7cdb678ad97
itsniteshh/100Days-of-coding-with-python
/Day 5/5.7 stages of life.py
283
4.15625
4
age = int(input("Enter ur age: ")) if age < 2: print("You are a baby") elif age < 4: print("You are a toddler") elif age < 13: print("you are a kid") elif age < 20: print("You are a teen") elif age <65: print("you're an adult") else: print("you're an elder")
false
a1dd24c1667edd636c6c5c15c9671222d3987d6a
itsniteshh/100Days-of-coding-with-python
/Day 10/7.10 Dream Vacation.py
628
4.125
4
responses = {} poll = True while poll: name = input("\nEnter ur name: ") location = input("Enter a location you'd like to visit next year: ") responses [name] = location repeat = input("Do you want to repeat the poll? (yes/no) \n") if repeat == "no": poll = False elif repeat == "yes": poll = True else: print("wrong input! Repeat the steps again") for answer in repeat: repeat = input("Do you want to repeat the poll? (yes/no) \n") for key, value in responses.items(): print(f"{key} would like to visit {value} someday.\n") print(responses)
true
c2d9eebdea27ca68424eaf28f17d174bf9a6bd38
itsniteshh/100Days-of-coding-with-python
/Day 18/brandname generator.py
375
4.46875
4
#1. Create a greeting for your program. print("hello user!") #2. Ask the user for the city that they grew up in. city = input("Enter the city wherein you grew: \n") #3. Ask the user for the name of a pet. pet = input("Enter your pet name: \n") #4. Combine the name of their city and pet and show them their band name. band_name = city.title() + pet.title() print(band_name)
true
1ad2ecad1edf72776e2d31bd84c54fa29708a150
Aliabdulaev/04_Osnovy_yazyka_Python
/DZ_03_task_06.py
998
4.375
4
"""Реализовать функцию int_func() , принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func() .""" def capitalize(line): return ' '.join(s[:1].upper() + s[1:] for s in line.split(' ')) line = input("Введите слово: ") print(capitalize(line))
false
7531b6c35112f4c01210be1937407153ead01485
Aliabdulaev/04_Osnovy_yazyka_Python
/DZ_04_task_04.py
752
4.15625
4
"""Представлен список чисел. Определить элементы списка, не имеющие повторений. Сформировать итоговый массив чисел, соответствующих требованию. Элементы вывести в порядке их следования в исходном списке. Для выполнения задания обязательно использовать генератор.""" my_list = [4, 7, 6, 4, 9, 1, 7, 1, 5, 3] print("Исходные элементы списка:\n", my_list) new_list = [i for i in my_list if my_list.count(i) == 1] print("Элементы списка, не имеющие повторений:\n", new_list)
false
35d7ecbf37952cd7ea60b11fa5b700d0c27bd0d2
acarter881/Python-Workout-50-Exercises
/4.py
316
4.3125
4
#! python3 def hex_output(): decimalValue = 0 hex = input('Enter a hexidecimal number to convert to a decimal:\n') for index, digit in enumerate(reversed(hex)): decimalValue += (int(digit) * 16 ** index) print(f'{hex} converted from hexidecimal to decimal is {decimalValue}.') hex_output()
true
e3740065757d52d6ac69f7fa7ce88c944c01700c
acarter881/Python-Workout-50-Exercises
/21.py
429
4.21875
4
#! python3 import os def find_longest_word(fileName): theWord = '' with open(fileName, 'r') as f: for row in f: for word in row.split(): if len(word) > len(theWord): theWord = word return theWord def find_all_longest_words(directory): return {fileName:find_longest_word(fileName) for fileName in os.listdir(directory)} print(find_all_longest_words('.'))
true
6afe5ef94accfc6d32212de5aa4b63f2fa25f681
Sunshine-Queen/Test
/day15/获取多个对象.py
791
4.1875
4
class Cat: #属性 #方法 def eat(self): print("猫正在吃鱼...") def drink(self): print("猫正在喝水...") def introduce(self): #print("%s的年龄是:%d" % (tom.name, tom.age)) print("%s的年龄是:%d"%(self.name,self.age)) #所谓的self,可以理解为自己 #某个对象调用其方法时,python解释器会把这个对象作为第一个参数传递给self,所以开发者只需要传递后面的参数即可 #创建一个对象 tom=Cat() #调用tom指向对象中的方法 tom.eat() tom.drink() #给tom指向的对象添加两个属性 tom.name="汤姆" tom.age=40 #print("%s的年龄是:%d" %(tom.name,tom.age)) tom.introduce() lanmao=Cat() lanmao.name="蓝猫" lanmao.age=10 lanmao.introduce()
false
862e4dd6103d6539237b2ce04a7ed8d4c10ee844
DuncanAForbes/learn_python_the_hardway
/ex3.py
756
4.34375
4
print "I will now count my chickens:" #This shall print the total number of 'Hens' and 'Roosters' print "Hens", 25.0 + 30.0 / 6 print "Roosters", 100.0 - 25.0 * 3 % 4 print "Now I will count the eggs:" #This shall count the total number of eggs print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7?" #This shall tell me whether the below calculation is false or true print 3 + 2 < 5 - 7 #This shall calculate the below sums print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh that's why it's False." print "How about some more." #This shall tell me whether the below calculations are false or true print "Is it greater?", 5 > -2 print "Is it great or equal?", 5 >= -2 print "Is it less or equal?", 5 <= 2
true
604fb50adf394d93cb4c7fc1ee1f6918f8189e27
DevByAthi/DiscordBotMath
/chocolatePrintFunctions.py
2,514
4.375
4
def printSingleCut(barHeight, barLength, cutIndex, cutDirection): """Given chocolate bar dimensions, a location to cut, and an orientation, print a graphical display of the cut. barLength and barHeight are positive integers referring to the size of the bar before splitting. cutIndex is a positive integer referring to the where on the bar the cut is located. cutDirection is an integer used to describe whether the cut is horizontal or vertical. The indexing scheme is such that (0,0) refers to the upper left point on the bar. A cutDirection of 0 refers to a horizontal cut, and a cutDirection of 1 refers to a vertical cut.""" # Input checking assert cutDirection == 0 or cutDirection == 1 assert barHeight > 1 assert barLength > 1 if cutDirection == 1: assert 0 < cutIndex < barLength elif cutDirection == 0: assert 0 < cutIndex < barHeight imageToReturn = str() i = 0 while i < barHeight+1: # This must be a while loop in order to allow us to modify the loop counter variable # from within, for the horizontal cut case where that is necessary for proper printing. currentLine = str() if i == 0: verticalChar = "." else: verticalChar = "|" for j in range(0,barLength): if cutDirection == 1 and cutIndex == j: # The cut is vertical. Thus it may occur at any of the horizontal indices. currentLine += verticalChar + " x " + verticalChar + "__" elif cutDirection == 0 and cutIndex == i: # This entire line is a cut currentLine += "\u0332".join("xxx") + "\u0332" else: # A normal segment currentLine += verticalChar + "__" # At the end of the line, add the final vertical character. if cutDirection == 0 and cutIndex == i: currentLine += "x" + "\u0332" else: currentLine += verticalChar # If the cut is horizontal, we'll need to print another row to avoid losing squares. if cutDirection == 0 and cutIndex == i: cutIndex = -1 i -= 1 imageToReturn += currentLine if i != barHeight: imageToReturn += "\n" i += 1 return imageToReturn # Testing ground print(printSingleCut(3,6,4,1)) print(printSingleCut(3,4,2,0))
true
9d4bf40538fcda521755b0431357e79276a72a78
RiveTroy/Learning_Python
/How to think like Computer Scientist/List_Methods.py
1,258
4.15625
4
### List Methods ### mylist = [] mylist.append(5) mylist.append(27) mylist.append(3) mylist.append(12) print(mylist) mylist.insert(1, 12) print(mylist) print(mylist.count(12)) print(mylist.index(3)) print(mylist.count(5)) mylist.reverse() print(mylist) mylist.sort() print(mylist) mylist.remove(5) print(mylist) lastitem = mylist.pop() print(lastitem) print(mylist) ''' Method Parameters Result Description append item mutator Adds a new item to the end of a list insert position, item mutator Inserts a new item at the position given pop none hybrid Removes and returns the last item pop position hybrid Removes and returns the item at position sort none mutator Modifies a list to be sorted reverse none mutator Modifies a list to be in reverse order index item return idx Returns the position of first occurrence of item count item return ct Returns the number of occurrences of item remove item mutator Removes the first occurrence of item ''' mylist = [] mylist.append(5) mylist.append(27) mylist.append(3) mylist.append(12) print(mylist) mylist = mylist.sort() #probably an error print(mylist)
true
e5bbac1da61ff530161de562ee85cb74590e92a7
RiveTroy/Learning_Python
/How to think like Computer Scientist/Error_Types.py
1,883
4.40625
4
# -*- coding: cp1252 -*- # Error Types # ''' *Many problems in your program will lead to an error message. Can You say what is wrong with this code by simply looking at it? No... current_time_str = input("What is the current time (in hours 0-23)?") wait_time_str = input("How many hours do you want to wait") current_time_int = int(current_time_str) wait_time_int = int(wait_time_int) final_time_int = current_time_int + wait_time_int print(final_time_int) NameError: name 'wait_time_int' is not defined ''' #ParseError ''' Parse errors happen when you make an error in the syntax of your program. If you dont use periods and commas in your writing then you are making it hard for other readers to figure out what you are trying to say. Similarly Python has certain grammatical rules that must be followed or else Python cant figure out what you are trying to say. #### Usually ParseErrors can be traced back to missing punctuation characters, such as parenthesis, quotation marks, or commas. #### ''' #TypeError ''' TypeErrors occur when you you try to combine two objects that are not compatible. For example you try to add together an integer and a string. Usually type errors can be isolated to lines that are using mathematical operators, and usually the line number given by the error message is an accurate indication of the line. ''' #NameError ''' Name errors almost always mean that you have used a variable before it has a value. Often NameErrors are simply caused by typos in your code. They can be hard to spot if you dont have a good eye for catching spelling mistakes. Other times you may simply mis-remember the name of a variable or even a function you want to call. ''' #ValueError ''' Value errors occur when you pass a parameter to a function and the function is expecting a certain type, but you pass it a different type. '''
true
e563efa086666807b3be654a21c979546b8f44b9
RiveTroy/Learning_Python
/How to think like Computer Scientist/string_method.py
1,773
4.40625
4
# String Methods # ss = "Hello, World" print(ss.upper()) tt = ss.lower() print(tt) ''' Method Parameters Description upper none Returns a string in all uppercase lower none Returns a string in all lowercase capitalize none Returns a string with first character capitalized, the rest lower strip none Returns a string with the leading and trailing whitespace removed lstrip none Returns a string with the leading whitespace removed rstrip none Returns a string with the trailing whitespace removed count item Returns the number of occurrences of item replace old, new Replaces all occurrences of old substring with new center width Returns a string centered in a field of width spaces ljust width Returns a string left justified in a field of width spaces rjust width Returns a string right justified in a field of width spaces find item Returns the leftmost index where the substring item is found rfind item Returns the rightmost index where the substring item is found index item Like find except causes a runtime error if item is not found rindex item Like rfind except causes a runtime error if item is not found ''' ss = " Hello, World " els = ss.count("l") print(els) print("***" + ss.strip() + "***") print("***" + ss.lstrip() + "***") print("***" + ss.rstrip() + "***") news = ss.replace("o", "***") print(news) food = "banana bread" print(food.capitalize()) print("*" + food.center(25) + "*") print("*" + food.ljust(25) + "*") # stars added to show bounds print("*" + food.rjust(25) + "*") print(food.find("e")) print(food.find("na")) print(food.find("b")) print(food.rfind("e")) print(food.rfind("na")) print(food.rfind("b")) print(food.index("e"))
true
275c16bb882861c0f39a239dd025df4f2597f2a2
RiveTroy/Learning_Python
/How to think like Computer Scientist/modules_exercises.py
792
4.34375
4
# Exercises # # 1. Use a for statement to print 10 random numbers. import random for i in range(10): i = random.random() print i # 2. Repeat the above exercise but this time print 10 random numbers between 25 and 35. import random for i in range(10): i = random.randrange(25,36) print i # 3. The Pythagorean Theorem tells us that the length of the hypotenuse # of a right triangle is related to the lengths of the other two sides. # Look through the math module and see if you can find a function that # will compute this relationship for you. Once you find it, write a short # program to try it out. import math result = math.hypot(3,4) print result ''' import math side1 = 3 side2 = 4 hypotenuse = math.hypot(side1,side2) print(hypotenuse) '''
true
37283e34cfb280ffddb90fdae5a1a30eff4e59da
import-keshav/91Social
/question_6.py
976
4.5625
5
''' Python program to convert an array to an array of machine values and return the bytes representation. ''' import array import binascii def get_bytes_representation_of_array(input_list): ''' Converts a pytho list to an python array of machine values. Args: input_list list: Input list. Returns: bytes representation of array. ''' python_array = array.array('i', input_list) bytes_array = python_array.tobytes() return binascii.hexlify(bytes_array) if __name__ == "__main__": print("Enter the length of array \n") LENGTH_OF_ARRAY = int(input()) INPUT_ARRAY = [] while len(INPUT_ARRAY) < LENGTH_OF_ARRAY: INPUT_NUMBER = input() try: INPUT_NUMBER = int(INPUT_NUMBER) INPUT_ARRAY.append(INPUT_NUMBER) except ValueError: print('Enter a valid key\n') print('Array of bytes is ') print(get_bytes_representation_of_array(INPUT_ARRAY))
true
6fb4d0b4f10c8e2e44ca667e630f2bbe3ac69246
sireeshavipparthi/python
/fibonacci.py
202
4.1875
4
n = int(input("Enter number of terms:")) print("Fibonacci sequence:") def fib(n): if n <= 1 : return n else: return(fib(n-1) + fib(n-2)) for i in range(n): print (fib(i))
false
149fd67ee4695479fc60eb01ba3f00b28de53e5a
gasser277/Data-Structures-and-Algorithms
/Data_Structures/Saving_Files.py
1,753
4.34375
4
import os def Find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ if not os.path.isdir(path): return 'Invalid Directory' path_list = os.listdir(path) output = [] for item in path_list: item_path = os.path.join(path, item) if os.path.isdir(item_path): output += Find_files(suffix,item_path) if os.path.isfile(item_path) and item_path.endswith(suffix): output.append(item_path) return output # # Test case 1 # print(find_files('.c', './Problem 2/testdir')) # # Test case 2 # print(find_files('.c', './asdf')) # print(find_files('.c', './Problem 2/emptydir')) # # Test case 3 # print(find_files('', './Problem 2/testdir')) # print(find_files('.z', './Problem 2/testdir'))/ #Test Case1 Referance_Path = os.getcwd() + '/testdir' print(Find_files('.c',path=Referance_Path)) print("///////////////////////////////////////////////////////////////////////") #Test Case2 file not in path Referance_Path = "C:/Users/gasse/OneDrive/Desktop" print(Find_files('.c',path=Referance_Path))#takes longer because has to search all files and folders in desktop print("///////////////////////////////////////////////////////////////////////") # Test Case3 path doesnt exist Referance_Path = '/testdir' print(Find_files('.c',path=Referance_Path)) print("///////////////////////////////////////////////////////////////////////")
true
30e80dab1da086f2b344cff9de3ec2dab09a4135
ExerciseAndrew/HackerRank-Puzzles
/minimax.py
477
4.1875
4
### Write a function that takes in an array and outputs ### the minimum or maximum sum (the array's sum minus its maximum ### and minimum elements) ### ex: input: [1, 2, 3, 4, 5,] ### output: [10 14] import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): print (sum(arr)-max(arr), sum(arr)-min(arr)) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
true
2f95080aa89f489d02f8ad9afef90ff1429547b7
larad5/python-exercises
/RepetitionStructures/avg_rainfall.py
928
4.28125
4
# 5.AVerage Rainfall # ask for the number of years years = int(input("Enter the number of years for calculations: ")) rainSum = 0 # outer loop for years i = 1 while i <= years : #inner loop for 12 months in the year print("----------\nYear",i) print("Enter the rainfall for each month.") for x in ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]: # ask the user for the inches of rainfall for each month inch = int(input(x + ": ")) rainSum += inch i += 1 # display total number of months months = years * 12 #print(months) # display total inches of rainfall #print(rainSum) # display the average rainfall per month for the entire period avgRain = rainSum/months #print(avgRain) # display results print("For", months, "months, there was", rainSum, "inches of rain.") print("The average rainfall over that time was", avgRain, "inches per month.")
true
fa8a7f9f19201f9617ac092fdb810425ef14cd8d
Mike-Xie/LearningPython
/ex25.py
977
4.15625
4
def break_words(stuff): """This function will break up words for us.""" return stuff.split() #more efficient not to have temp variable def sort_words(words): """This function will return the words sorted. """ return sorted(words) def print_first_word(words): """This function returns the first word.""" #thought tempvar wasn't necessary at first but it is #pop removes and returns an element from the list #so we have to create a temp copy to not mess with #the original wordCopy = words.pop(0) return wordCopy def print_last_word(words): """This function returns the last word. """ #same deal here wordCopy = words.pop(-1) return wordCopy def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): sortedS = sort_sentence(sentence) print_first_word(sortedS) print_last_word(sortedS)
true
04542d551c7c30b1add3fe1044fa7e4722048f74
hhchong/linked-lists-practice
/partition.py
1,453
4.15625
4
#write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. #use head and tail.. traverse list, if node is < head, push it, if node is >, append to tail? import unittest def partition(head, p): node = head head_new = None head_greater = None tail_greater = None tail_new = None while node: if node.data < p: if head_new == None: head_new = node tail_new = node else: tail_new.next = node tail_new = node else: if head_greater is None: head_greater = node tail_greater = node else: tail_greater.next = node tail_greater = node node = node.next tail_new.next = head_greater return head_new class Node(): def __init__(self, data, next=None): self.data, self.next = data, next def __str__(self): string = str(self.data) if self.next: string += ',' + str(self.next) return string class Test(unittest.TestCase): def test_partition(self): head1 = Node(7,Node(2,Node(9,Node(1,Node(6,Node(3,Node(8))))))) head2 = partition(head1, 6) self.assertEqual(str(head2), "2,1,3,7,9,6,8") head3 = partition(head2, 7) self.assertEqual(str(head3), "2,1,3,6,7,9,8") unittest.main()
true
2e5d6db38493ddc229606a43e01ee9529fa2e162
ankur-anand/Factorial-Algorithm
/fact_01_recursive.py
281
4.40625
4
def calculate_factorial_recursive(number): ''' This function takes one agruments and returns the factorials of that number This is naive recursive approach ''' #base case if number == 1 or number == 0: return 1 return number * calculate_factorial_recursive(number - 1)
true
db25ca4d149508fac300f74b1cab45fa5581a355
hsaglamlar-test/Prime-Number
/main.py
596
4.15625
4
number = input("Enter a positive integer grater than 1 :") if not number.isdigit(): print("It is not a valid number.") else: number = int(number) if number == 2: print("2 is a prime number.") elif number > 2: is_prime = True for i in range(2, number): if number % i == 0: is_prime = False break if is_prime: print(f"{number} is a prime number.") else: print(f"{number} is a not prime number.") elif number < 2: print("Number is expected to be greater than 1")
true
5d94da4e95e26a35f3f8c1d8c62ac070ddf975a0
Sandhyashende/Python
/boolean.py
1,239
4.15625
4
# MORE ABOUT BOOLEANS: # x = True # print(type(x)) # a = (4<5) # print(type(a)) # number1 = 45 # number2 = 56 # if number2 > number1: # print ("true") # else: # print ("false") # if True: # print ("Only I will run") # else: # print ("I will never run") # Logical operators questions; # question 1: # if (4 >= 4) and (6 == 5): # print ("Yes") # else: # print ("No") # question 2: # if (4 < 5) and (3 < 7): # print("true") # else: # print("false") # question 3: # if (6 == 5) and (4 >= 4): # print ("Yes") # else: # print ("No") # question 4: # x = 4 # y = 5 # z = 10 # print ((x + y) / (z*1)) # if (x > z) or (y > x): # print ("Yes") # else: # print ("No") # if not (x == z): # print ("Wow") # else: # print ("No wow!!") # if (x < y) and (x > y): # print ("Yes 123") # else: # print ("No 456") # print ((z / y) * x) # question 5: # pehlaBool = True # doosraBool = False # print (pehlaBool and doosraBool) # print (pehlaBool or doosraBool) # if not pehlaBool: # print ("yeh kya hua?") # else: # print ("pata nahi kya hua??") # print (not ("doosraBool")) # if (pehlaBool and doosraBool): # print ("Yes") # print (pehlaBool or doosraBool) # print (not pehlaBool) # print (not doosraBool)
false
09b87758e911b1e70918130096dc829433cbe0d4
TopskiyMaks/PythonBasic_Lesson
/lesson_7/task_3.py
850
4.125
4
print('Задача 3. Посчитай чужую зарплату...') # Бухгалтер устала постоянно считать вручную среднегодовую зарплату сотрудников компании # и, чтобы облегчить себе жизнь, обратилась к программисту. # Напишите программу, # которая принимает от пользователя зарплату сотрудника за каждый из 12 месяцев # и выводит на экран среднюю зарплату за год. sum_salary = 0 for i in range(12): num = int(input(f'Введите зарплату за {i+1} месяц: ')) sum_salary += num avg_salary = sum_salary / 12 print(f'Средняя зарплата за год: {avg_salary}')
false
d0134667289cc961ad55748ba63d2577e4e38951
TopskiyMaks/PythonBasic_Lesson
/lesson_13/task_5.py
559
4.21875
4
print('Задача 5. Число Эйлера') # Напишите программу, которая находит сумму ряда с точностью до 1e-5. # P.S: Формулу смотреть на сайте :) # Пример: # Точность: 1e-20 # Результат: 2.7182818284590455 def fun(x): eps = 1e-9 s = x / 2 t = x * x i = 2 while x / i > eps: s += x / i i += 2 x *= t return s if __name__ == '__main__': x = float(input('введите точность: ')) print(fun(x))
false
83a74dc432e9abbc1a827d2f3e4ed2d4ff30d541
TopskiyMaks/PythonBasic_Lesson
/lesson_11/task_7.py
1,439
4.375
4
print('Задача 7. Ход конём') # В рамках разработки шахматного ИИ стоит новая задача. # По заданным вещественным координатам коня # и второй точки программа должна определить может ли конь ходить в эту точку. # # Используйте как можно меньше конструкций if и логических операторов. # Обеспечьте контроль ввода. # Введите местоположение коня: # 0.071 # 0.118 # Введите местоположение точки на доске: # 0.213 # 0.068 # Конь в клетке (0, 1). Точка в клетке (2, 0). # Да, конь может ходить в эту точку. print('Введите местоположение коня:') x1 = float(input()) y1 = float(input()) x1 = int(x1 * 10) y1 = int(y1 * 10) print('Введите местоположение точки на доске:') x2 = float(input()) y2 = float(input()) x2 = int(x2 * 10) y2 = int(y2 * 10) print(f'Конь в клетке ({x1}, {y1}). Точка в клетке ({x2}, {y2}).') if abs(x2 - x1) == 2 and abs(y2 - y1) == 1: print('Да, конь может ходить в эту точку.') else: print('Нет, конь не может ходить в эту точку.')
false
eea9cdcf12527471b438771be09e097561e6617c
autofans/python_practice
/JA_贪婪模式和非贪婪.py
587
4.1875
4
import re # 贪婪模式:在整个表达式匹配成功的前提下,尽可能多的匹配; # 非贪婪模式:在整个表达式匹配成功的前提下,尽可能的少匹配; # python里默认是贪婪模式; a = "aa<div>test1</div>bb<div>test2</div>cc" pat1 = r"<div>.*</div>" # 贪婪模式 print(re.search(pat1, a)) b = "aa<div>test1</div>bb<div>test2</div>cc" pat2 = r"<div>.*?</div>" # 非贪婪模式 print(re.search(pat2, b)) c = "aa<div>test1</div>bb<div>test2</div>cc" pat3 = r"<div>(.*?)</div>" # 非贪婪模式2 print(re.findall(pat3, c))
false
7c7255572c0353a44a482b52529f729c03f5ab41
autofans/python_practice
/JA_test_复制列表.py
222
4.1875
4
# 题目:将一个列表的数据复制到另一个列表中 # 方法1 a = [1, 2, 3] b = [] b.extend(a) print(b) # 方法2 # a = [1, 2, 3] # b[len(b):] = a # print(b) # 方法3 # a = [1, 2, 3] # b = a[:] # print(b)
false
2a1c1c3317186b52cb2030df585265dd9d6bb7fa
redbrick/user-scripts
/src/help/text/email.py
653
4.4375
4
"""email help text""" EMAIL = dict( text="""Typing 'email' will bring you to a screen with a list of your emails. To read an email, use the up and down arrow keys to navigate to the email you want, then press enter. To write a new email, press 'm' (for 'mail'). Type in the email of the person you are sending to & press enter. Do the same with the subject of the email. Type your message. To send the email, press the control key and 'x' to quit and save your email, then press 'y' to send. The keys for various functions are detailed on the top line. 'q' quits from the main email screens.""", link="http://wiki.redbrick.dcu.ie/mw/Mutt", )
true
8808e5837a1316d92069ddb655b75f3531b8205b
FirstNoms/parsel_tongue_mastered
/love/chaptertwo/ten.py
587
4.15625
4
import math while(True): number = int(input("Enter a number: ")) # square_root = int(number ** 0.5) # if square_root * square_root == number: # print(f"the number {number} is a perfect square") # break # else: # print(f"the number {number} is not a perfect square, try another number") square_root = math.sqrt(number) print(square_root) if square_root.is_integer(): print(f"the number {number} is a perfect square") break else: print(f"the number {number} is not a perfect square, try another number")
true
57a23dc016d5dbbb559d893e680cad598ae34452
tsimafeip/leetcode
/strings/125_valid_palindrome.py
345
4.125
4
def is_palindrome(s: str) -> bool: cleaned_str = [ch.lower() for ch in s if ch.isalpha() or ch.isnumeric()] for i, ch in enumerate(cleaned_str): if ch != cleaned_str[-(i + 1)]: return False return True print(is_palindrome("A man, a plan, a canal: Panama")) print(is_palindrome("")) print(is_palindrome("car!"))
false
35a0906b5be466722b72973181f062d57f7c7747
tsimafeip/leetcode
/intervals/435_non_overlapping_intervals.py
1,404
4.15625
4
""" 435. Non-overlapping Intervals Medium Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Example 1: Input: [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of intervals are non-overlapping. Example 2: Input: [[1,2],[1,2],[1,2]] Output: 2 Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping. Example 3: Input: [[1,2],[2,3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping. Note: You may assume the interval's end point is always bigger than its start point. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. """ from typing import List class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key=lambda x:(x[0], x[1])) res = last_valid_index = 0 for i in range(1, len(intervals)): if intervals[last_valid_index][1] > intervals[i][0]: res+=1 # we choose which interval to delete to have as low right border as we can intervals[last_valid_index][1] = min(intervals[last_valid_index][1], intervals[i][1]) else: last_valid_index = i return res
true
9ce08f0c422172bda714abb34bdcd62808bd9aff
seanrobinson1114/euler
/problem_1/solution.py
489
4.40625
4
# Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6,and 9 # The sum of these multiples is 23 # Find the sum of all the multiples of 3 or 5 below 1000 # @author seanmr # imports import numpy as np # generate array from 3 to 999 vals = range(3, 1000) # filter out values that aren't multiples of 3 or 5 multiples = filter(lambda val: not(val % 3) or not(val % 5), vals) # print sum of list print(np.sum(list(multiples)))
true
a502a6b473ae3e0da0020b2a4e8bf03e9cc9211a
narendra-solanki/python-coding
/ListPrimeNumbers.py
678
4.375
4
#!/usr/bin/env python3 # A program to print list of prime numbers def is_prime_number(number): #any number less than 2 is not prime number if number < 2: return False #check if number is divisible by any of the number less than itself for x in range(2,number): #if number is divisible than its not prime if(number%x == 0): return False return True def list_primes(count): #run a for loop from 1 to 'count'-1 for x in range(count): if is_prime_number(x) is True: print(x, end = ' ', flush=True) #end each print statement in whitespace instead of new line print() #print newline after printing whole list if __name__ == '__main__': list_primes(101)
true
b2eeb264724c2022e8923d9987e2bf36f17cce94
Jamesmb85/LeetCode-Coding-Challenges
/Find All Numbers Disappeared in an Array.py
938
4.1875
4
# Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. # Find all the elements of [1, n] inclusive that do not appear in this array. # Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. # Example: # Input: # [4,3,2,7,8,2,3,1] # Output: # [5,6] def findDisappearedNumbers(nums): """ :type nums: List[int] :rtype: List[int] """ workingArray = [] #let's create an array and fill it with numbers from 1 to size of the array for value in range(1, len(nums)+1): workingArray.append(value) #let's convert workingArray and nums to a set so we can find the difference set1 = set(nums) set2 = set(workingArray) set3 = set2.difference(set1) return list(set3) print(findDisappearedNumbers([4,3,2,7,8,2,3,1]))
true
c5690665309b4bbb0ff1b51597d16113c2f77098
SakdaMrp/CED59-5902041610061
/assignment4/calculator.py
1,115
4.125
4
class myCalculator(): x = 0 y = 0 def __init__(self, in_x, in_y): self.x = in_x self.y = in_y def plus(self): result = self.x + self.y print('Plus : ', self.x, ' + ', self.y, " = ", result) def subtraction(self): result = self.x - self.y print('Subtraction : ', self.x, ' - ', self.y, " = ", result) def multiply(self): result = self.x * self.y print('Multiply : ', self.x, ' x ', self.y, " = ", result) def divide(self): result = self.x / self.y print('divide : ', self.x, ' / ', self.y, " = ", result) print("======= Calculator =========") score = int(input('Please input x : ')) score2 = int(input('Please input y : ')) cal = myCalculator(score,score2) print("======= Menu =========") print("Press 1 : Plus") print("Press 2 : Subtraction") print("Press 3 : Multiply") print("Press 4 : divide") my_operator = int(input('Please input [1-4] for result: ')) if my_operator == 1: cal.plus() elif my_operator == 2: cal.subtraction() elif my_operator == 3: cal.multiply() elif my_operator == 4: cal.divide() else: print("Please input [1-4] !!!")
false
e59de11505ad26120c896bcb373c4340845af09d
wreckoner/PyEuler
/src/problem025.py
977
4.25
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Problem 25: 1000-digit Fibonacci number The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? Answer: 4782 """ def number_of_digits(number): """ Returns the number of digits of @number. """ digits = 0 while number > 0: digits += 1 number /= 10 return digits def fibonacci(digits): """ Returns the position of the first number with number of digits = @digits in the fibonacci sequence. """ i = 2 i_1 = i_2 = 1 fib = 0 while number_of_digits(fib) < digits: fib = i_1 + i_2 i += 1 i_2 = i_1 i_1 = fib return i if __name__ == '__main__': print fibonacci(1000)
true
f1b73d0362c0d3af5e849bc41ceb1a077753bf59
wreckoner/PyEuler
/src/problem014.py
1,629
4.25
4
#!/usr/bin/env python # -*-coding:utf-8 -*- """ Problem 14: Longest Collatz sequence The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. Answer: 837799 """ import math def longest_collatz_sequence(upper_bound=1000000): """ This calculates the length of all collatz sequence with starting number between 1 and 1 million. There are 2 optimizations: 1. If a number is a power of 2, then no need to calculate further 2. Caches the length of collatz sequences, so if larger sequence contain a smaller one, simply adds the length. """ longest = 0 cached = {} for init_val in xrange(1, upper_bound): val, length = init_val, 0 while val > 1: if math.log(val, 2).is_integer(): length += (int(math.log(val, 2)) + 1) break elif val in cached: length += cached[val] break elif val%2 == 0: val = val/2 length += 1 else: val = 3*val + 1 length += 1 cached[init_val] = length if longest < length: start = init_val longest = length return start if __name__ == '__main__': print longest_collatz_sequence(1000000)
true
e77073722039084c32e6ccd6dc496c2c11402129
cs-richardson/table-reservation-4-3-9-aphan21
/Table Reservation.py
550
4.25
4
#This program checks if a person is in the reservation list in a restaurant #You must be in the reservation list to get a table name = input ("Welcome! What is your name?") reservation_name = ["Ann","Claire","Steven","Jason"] if name == reservation_name[0]: print("Right this way!") elif name == reservation_name[1]: print("Right this way!") elif name == reservation_name[2]: print("Right this way!") elif name == reservation_name[3]: print("Right this way!") else: print("Sorry, we don't have a reservation under that name.")
true
91f09441b8d604871030a7bfc89dde3fde0c0fe9
Ubaid97/python_control_flow
/calculate_birthyear.py
1,062
4.53125
5
# Calculates birth year by taking age and subtracting it from the current year (2020) name = "John Doe" age = 22 birth_year = 2020 - age print(f"OMG {name}, you're {age} years old and so were born in {birth_year}") # User asked to input name, age, the day of the month, and the month in which they born name = input("Enter your full name: ") age = int(input("Enter your age: ")) birth_date = int(input("Please enter the day of the month you were born in: ")) birth_month = input("What month were you born in: ").capitalize() # input for birth month is capitalised to ensure the == function in the if statement below functions # if statement checking whether the birth date (day/month) given by the user is after the 3rd of November or before. if after, user told that their birthday has yet to happen this year. if before, they're told that it's already passed if (birth_month == "November" and birth_date > 3) or (birth_month == "December"): print("your birthday hasn't happened yet this year") else: print("your birthday has already passed this year")
true
1d39d79681171cf817c62e2648f4248e706ade96
maleksal/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
1,010
4.4375
4
#!/usr/bin/python3 def split_text(text, delim): """ splits a text with a given delimiters Args: text: a given string delim (tuple): tuple of 3 delemiters Returns: finaltext: the final splited text """ a, b, c = delim newline = "\n\n" part_1 = text.split(a) part_2 = "{}{}".format( a, newline).join(i.lstrip() for i in part_1).split(b) part_3 = "{}{}".format( b, newline).join(i.lstrip() for i in part_2).split(c) finaltext = "{}{}".format(c, newline).join(i.lstrip() for i in part_3) return finaltext def text_indentation(text): """ prints a text with 2 new lines after each of these characters: [.,?,:] Args: text (string): must be a string Returns: TypeError: if text is not a string """ if type(text) is not str: raise TypeError("text must be a string") textholder = split_text(text, ('.', '?', ':')) for i in textholder: print(i, end="")
true
10c6e65683a994d0117a5cbaed17220579092d01
gogasparyan/Python3-Exercises
/Ex. 3. Write a Python program which accepts the radius of a circle from the user and compute the area.py
1,465
4.1875
4
#################################################################################################################### ### Required: Write a Python program which accepts the radius of a circle from the user and compute the area ### #################################################################################################################### ### #################### ### Sample Output: #################### ### Input radius of a circle: r = 4 #################### ### #################### ### Radius of a circle is: r = 4 #################### ### Area of a circle: S = 50.24 #################### ### #################### #################################################################################################################### #################################################################################################################### from math import pi r = "" while r!=0: try: r = int(input("\nEnter radius of a cirlce:\t")) if r<=0: print("\nYou must enter positive integer") continue r = float(r) s = pi*(r**2) print("\nRadius of a circle is:\tr = " + str(r)) print("Area of a circle:\tS = " + str(s)) print("(Enter '0' for exit)") except (ValueError, TypeError): print("\n\t*** Error occurred ***\n\n You must enter positive integer") continue print("\nAdios!")
true
dab184da29506a1552dd3515ceffe040e6dc1b96
roykim0823/Interview
/ProjectEuler/003_LargestPrimeFactor.py
2,239
4.125
4
#!/usr/bin/pyhton3 import math def prime_sieve(n): """Given n, return a list of all primes up to n.""" if n < 2: return [] size = math.floor(0.5 * (n-3)) + 1 prime_list = [2] # is_prime[i] represents whether (2i + 3) is prime or not. # Initially, set each to True. Then use sieving to eliminate non-primes. is_prime = [True] * size for i in range(size): if is_prime[i]: p = (i *2) + 3 prime_list.append(p) # Sieving from p^2, whose value is (4i^2 + 12i + 9). # The index in is_prime is (2i^2 + 6i +3) since is_prime[i] represents 2i + 3. # Note that we need to use long long for j because p^2 might overflow (for C/C++) for j in range(2*i*i + 6*i + 3, size, p): # range(start, stop, step) is_prime[j] = False return prime_list def prime_factors(n): """Given n, return a list of all primes up to n.""" MAXN = 1000000 if n < 2: return [] size = math.floor(0.5 * (n-3)) + 1 prime_list = [2] number = n if number % 2 == 0: prime_factor = [2] while number % 2 == 0: number = number // 2 else: prime_factor = [] # is_prime[i] represents whether (2i + 3) is prime or not. # Initially, set each to True. Then use sieving to eliminate non-primes. if size > MAXN: size = MAXN is_prime = [True] * size for i in range(size): if number == 1: break if is_prime[i]: p = (i *2) + 3 prime_list.append(p) if number % p == 0: prime_factor.append(p) while number % p == 0: number = number // p # Sieving from p^2, whose value is (4i^2 + 12i + 9). # The index in is_prime is (2i^2 + 6i +3) since is_prime[i] represents 2i + 3. # Note that we need to use long long for j because p^2 might overflow (for C/C++) for j in range(2*i*i + 6*i + 3, size, p): # range(start, stop, step) is_prime[j] = False return prime_factor, prime_list def main(): prime_factor, prime_list = prime_factors(600851475143) # prime_factor, prime_list = prime_factors(1000) print("Prime Factors:", prime_factor) print("Answer =", prime_factor[-1]) # print(prime_list) if __name__ == '__main__': main()
true
2924eae31b8f9370c4970eafd9d703b3a6e1d87c
sosergey/kolesa_lessons
/a5.py
1,060
4.21875
4
#Задание А #Реализуйте функцию с возможностью отрпавить любое количество строк в качестве аргументов #которая будет их конкатинировать, убирать лишние пробелы, корректировать регистр по умолчанию. #Или в качестве альтернативы к каждой строке применять callback функцию со своим вариантом обработки строки. #func("this is", "a funCtion\'s argUMents", " simple Example" callback = lambda x: x ) #"This is a funCtion's arguments simple example". def toStr(*args,word=[]): a = list(args) for i in args: word.append(i.strip(',!@#$%^&*()" ')) word = ' '.join(word).lower().capitalize() word = ' '.join(word.split()) #удалить лишние пробелы между словами a funCt return(word) #print(toStr(" this is", "a funCtion\'s argUMents", " simple Example"))
false
12a38780f9b5bdd0b5c3bd0db73571627a298b1a
GJayme/RaciocionioLogicoPython
/Lista_01_04.py
931
4.34375
4
''' 04 - Faça um programa que leia 3 números e mostre na tela o maior número. #PORTUGOL# Defina: num1, num2, num3, Real INICIO escreva ("Digite o primeiro número: ") leia (num1) escreva ("Digite o segundo número: ") leia (num2) escreva ("Digite o terceiro número: ") leia (num3) se num 1 > num 2 e num 1 > num 3 então escreva ("O primeiro número é o maior") senão se num 2 > num 1 e num 2 > num 3 então escreva ("O segundo número é o maior") senão escreva ("O terceiro número é o maior") fim_se fim_se FIM ''' num1 = float(input("Digite o primeiro número: ")) num2 = float(input("Dgite o segundo número: ")) num3 = float(input("Digite o terceiro número: ")) if num1 > num2 and num1 > num3: print("O número 1 é o maior: ", num1 ) if num2 > num1 and num2 > num3: print("O número 2 é o maior: ", num2) if num3 > num1 and num3 > num2: print("O número 3 é o maior:", num3)
false
a999808126294c34deea08d4af24964b37db9580
gunjany/python_40_challenge
/quad_equation.py
1,007
4.34375
4
import cmath print('Welcome to the Quadratic Equation Solver App.') print('\nA quadratic equation is of the form ax^2 + bx + c = 0\ \nYour solutions can be real or complex numbers.\ \nA complex number has two parts: a + bj\ \nWhere a is the real portion and bj is the imaginary portion') equation = int(input('\nHow many equations would you like to solve today: ')) for i in range(1, equation + 1): print('Solving equation #', i) print('---------------------------------------------------\n') a = float(input('Please enter your value of a(coefficient of x^2: ')) b = float(input('Please enter your value of b(coefficient of x: ')) c = float(input('Please enter your value of c(coefficient: ')) x1 = (-b + cmath.sqrt(b**2 - 4*a*c))/2*a x2 = (-b - cmath.sqrt(b**2 - 4*a*c))/2*a print('\nThe solutions to {}x^2 + {}x + {} = 0 are:\n'.format(a, b, c)) print('\t\tx1 = {}'.format(x1)) print('\t\tx2 = {}\n'.format(x2)) print('Thank you for using the Quadratic Equation Solver App. Goodbye.')
true
566074f036259564c966315d775276df33202217
gunjany/python_40_challenge
/ship_item.py
1,905
4.15625
4
class UserItems: def __init__(self, n): self.name = n self.price_0_100 = 5.10 self.price_100_500 = 5.00 self.price_500_1000 = 4.95 self.price_1000 = 4.85 print('Hello {}. Welcome to you account.'.format(self.name)) print('Current shipping prices are as follows:\n\ \nShipping orders 1 to 100:\t\t$5.10 each\ \nShipping orders 100 to 500:\t\t$5.00 each\ \nShipping orders 500 to 1000:\t\t$4.95 each\ \nShipping orders over 1000:\t\t$4.80 each') def takeInput(self, items): bill_payment = items price_each = 0 if items > 0 and items < 100: bill_payment *= 5.10 bill_payment = round(bill_payment, 2) price_each = self.price_0_100 elif items >= 100 and items < 500: bill_payment *= 5.00 bill_payment = round(bill_payment, 2) price_each = self.price_100_500 elif items >= 500 and items < 1000: bill_payment *= 4.95 bill_payment = round(bill_payment, 2) price_each = self.price_500_1000 else: bill_payment *= 4.85 bill_payment = round(bill_payment, 2) price_each = self.price_1000 return bill_payment, price_each print("Welcome to the Shipping Accounts Program.\n") users = ['Bob', 'Marley', 'Teena', "Aron", 'Ryan'] name = input("What is your user name? ").title() if name in users: obj = UserItems(name) quantity = int(input("\nHow many items would you like to ship: ")) price, price_each = obj.takeInput(quantity) print('\nTo ship {} items it will cost you ${} at ${} per item.'.format(quantity, price, price_each)) place_order = input('Would you like to place the order(y/n): ').lower() if place_order == 'y': print('\nOkay. Shipping your {} items.'.format(quantity)) elif place_order == 'n': print('\nOkay, no order is being placed at this time.') else: print('\nSorry Not a correct option. We are not shipping the orders.') else: print('\nSorry, you don\'t have an account with us. GoodBye.')
true
8af901b21d1e5f032405b993544a5da30acfd43b
rvladimir001/Python-Learning
/zadachki/task4/sortirovka_chisel_po_ubyvaniyu(if).py
1,000
4.40625
4
# -*- coding: utf- 8 -*- """ Напишите код который будет спрашивать 3 возраста и определять самый большой, маленький и средний. """ a = int(input("Введите первый возраст --> ")) b = int(input("Введите второй возраст --> ")) c = int(input("Введите третий возраст --> ")) line = "~"*20 print("Прекрасно! Теперь отсортируем их по убыванию.") print(line) if a==b==c: print("Они одинаковые") elif a>b>c: print(a, b, c) elif a<b<c: print(c, b, a) elif b>c>a: print(b, c, a) elif a>c>b: print(a, c, b) elif c>a>b: print(c, a, b) elif a==b>c: print(a, b, c) elif a==b<c: print(c, a, b) elif a>b==c: print(a, b, c) elif a<b==c: print(b, c, a) elif a==c>b: print(c, a, b) elif a==c<b: print(b, a, c) input("Для закрытия программы нажми Enter")
false
1fdbff7c732313d8e043fd2e62b46495e900148a
rvladimir001/Python-Learning
/lesson_06/Task_3.py
870
4.5
4
""" Задача 3 Заполнить список из шести элементов произвольными целочисленными значениями. Вывести список на экран в обратной последовательности. Два варианта получения обратной последовательности: с приминением цикла и без него. """ #first variant import random as rnd count = 6 lst = [rnd.randrange(0, 100) for i in range(count)] """ предвзятое отношение к данному циклу i = 0 while i < 7: lst.append(rnd.randint(0, 100)) i += 1 """ print(lst) lst.reverse() print(lst) print("~" * 50) #second variant count = 6 lst = [rnd.randrange(0, 100) for i in range(count)] print(lst) lst_r = [] for i in lst: lst_r.insert(0, i) print(lst_r)
false
6252517dc23892f4a67fadf1a5f9a9514cb6f302
GBVParrilla/Book.Python-Programming-Third-Edition
/Chapter 3.py
2,239
4.1875
4
#random import import random die1 = random.randint(1,6) die2 = random.randrange(6) + 1 total = die1 + die2 print("You rolled a", die1, "and a", die2, "for a total of", total) #randint(x,y) function makes a random number from the range of x to y so for exmample if randint(1,6) it will produce a random number from 1 - 6 #randrage(x) will produce a random number from the range of the number including zero. so if it is randrange(6) the list of possible numbers would be from 0-5 #branching is a fundamental part of programming. print("\n\n\n\n\n") #if statement print("Welcome to System Security Inc.") print("-- where security is our middle name\n") print("\n for demonstration purposes the password is \"secret\"\n") password = input("Enter your password: ") if password == "secret": print("\nAccess Granted") else: print("\n ACCESS DENIED. CALLED POLICE. COMING IN 5 MINUTES") #All if statements have a condition. A condition is just an expression that is either true or false. #True = true False = false, if in the program we made the user placed "secret" it would be true, anything else would be false. #== equal to != not equal to > < >= <= #indentation in Python is very important. ONe exmaple of using indentation is the if statement. #Else means if the if statement is false this executes. #elif can contain a sequence of conditions basically like the if and else statements print("\n\n\n\n\n\n") print("I sense your energy. Your true emotions are coming across my screen.") print("You are...") ready = input("\nAre you ready?") mood = random.randint(1,3) if mood == 1: print("""\n _________________ | | | O O | | < | | . . | | ....... | L_______________| """) print("\nYou are happy!") if mood == 2: print("""\n _________________ | | | O O | | < | | ....... | | . . | L_______________| """) print("\nYou are sad.") elif mood == 3: print("""\n _________________ | | | O O | | < | | | | ....... | L_______________| """) print("\nYou are neautral.")
true