blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
f1f065347901f3ab8ff3fd885742e7de75fe2b44
bastolatanuja/lab1
/lab exercise/question2.py
398
4.15625
4
#write a program that reads the length of the base and the height of the right angled triangle aqnd print the area. # every number is given on a separate line. base= int(input('enter the first number')) height= int(input('enter the second number')) area= 1/2*(base*height) #the float division//rounds the result down to the nearest whole number print(f"the area of right angled triangle {area}")
true
23f3df8b95b34e36307c94ad487283e9091c08c5
KatiukhaO/lists
/list_1.py
2,001
4.3125
4
'''Напишите программу, которая запрашивает с ввода восемь чисел, добавляет их в список. На экран выводит их сумму, максимальное и минимальное из них. Для нахождения суммы, максимума и минимума воспользуйтесь встроенными в Python функциями sum(), max() и min().''' b = list() for i in range(8): a = float(input('iNPUT numeric : ')) b.append(a) print(b) print(sum(b),max(b), min(b)) s = [float(input('iNPUT numeric : ')) for i in range(8)] print(s) print(sum(s), min(s), max(s)) '''Напишите программу, которая генерирует сто случайных вещественных чисел и заполняет ими список. Выводит получившийся список на экран по десять элементов в ряд. Далее сортирует список с помощью метода sort() и снова выводит его на экран по десять элементов в строке. Для вывода списка напишите отдельную функцию, в качестве аргумента она должна принимать список.''' from random import random, randint from math import def print_list(array, len_part = 10): i = 0 while i < ceil(len(array)/len_part): print(array[i*len_part : i*len_part + len_part]) i += 1 def print_listW(array): i = 0 while i < 100/10: j = 0 while j < 10: print(array[j + i], end=' ') j += 1 print() i += 1 start = float(input('Input renge random numerik : ')) stop = float(input('Input renge random numerik : ')) n = int(input('Len List :')) a = [round(random()*(stop - start) + start, 2) for x in range(n)] print_listW(a) a = sorted(a) print_list(a, 10)
false
2a40f93222078f2c393b8341a85763501ab57ad9
t3miLo/lc101
/Unit_1/assignments/analyze_text.py
1,508
4.28125
4
# Write a function analyze_text that receives a string as input. # Your function should count the number of alphabetic characters # (a through z, or A through Z) in the text and also keep track of # how many are the letter 'e' (upper or lowercase). # Your function should return an analysis of the text in the # form of a string phrased exactly like this: # “The text contains 240 alphabetic characters, of which 105 (43.75%) are ‘e’.” def analyze_text(text): # Your code here alpha = 'abcdefghijklmnopqrstuvwxyz' e = 'e' length = 0 for each_char in text: if each_char.lower() in alpha: length += 1 total = 0 for each_char in text: if each_char.lower() == e: total += 1 percent = (total / length) * 100 answer = "The text contains {} alphabetic characters, of which {} ({}%) are 'e'." return answer.format(length, total, percent) # Tests 4-6: solutions using str.format should pass these text4 = "Eeeee" answer4 = "The text contains 5 alphabetic characters, of which 5 (100%) are 'e'." print(analyze_text(text4)) print(answer4) text5 = "Blueberries are tasteee!" answer5 = "The text contains 21 alphabetic characters, of which 7 (33.33333333333333%) are 'e'." print(analyze_text(text5)) print(answer5) text6 = "Wright's book, Gadsby, contains a total of 0 of that most common symbol ;)" answer6 = "The text contains 55 alphabetic characters, of which 0 (0%) are 'e'." print(analyze_text(text6)) print(answer6)
true
ad0f14962ab78b9fc41634ddc257bb38b4f14190
Sankarshan-Mudkavi/Project-Euler
/11-20/Problem-14.py
1,127
4.125
4
"""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.""" def collatz(num, collatz_dict): num_original = num count = 0 while num >= 1: if num % 2 == 0: num /= 2 else: num = 3 * num + 1 count += 1 if num in collatz_dict: collatz_dict[num_original] = collatz_dict[num] + count return collatz_dict[num_original] def ans(num): collatz_dict = {} longest = [0, 0] collatz_dict[1] = 1 for ind in range(num, 2, -1): if collatz(ind, collatz_dict) >= longest[1]: longest = [ind, collatz(ind, collatz_dict)] return longest print ans(1000000)
true
37e3daa4b47ca72f956b5e70595409b99840c880
kmboese/the-coders-apprentice
/ch13-Dictionaries/stringToDict.py
652
4.125
4
# Converts a comma-separated list of words in a string # to a dict, with the strings as keys and their # frequency as a value text = "apple,durian,banana,durian,apple,cherry,cherry,mango,"+\ "apple,apple,cherry,durian,banana,apple,apple,apple,"+\ "apple,banana,apple" textDict = {} # dict that holds strings/frequency key/value pairs tmp = "" # temporary string # Convert string to dict for i in range(len(text)): if text[i] == ",": if tmp in textDict: textDict[tmp] += 1 tmp = "" else: textDict[tmp] = 0 tmp = "" else: tmp += text[i] # Print result print(textDict)
true
ce8a7a2f4c285dba67a8b43c996d53bf9d133125
jabuzaid/Python-Challenge---Py-Me-Up-Charlie
/PyBank.py
2,117
4.1875
4
import os import csv # Initializing the variable total_sales_change = 0 greatest_increase = 0 greatest_decrease = 0 # setting up the path of the diretly file_path = os.path.join('budget_data.csv') # readindg the rows of the csv file with open(file_path) as file_handler: data_lines = csv.reader(file_handler,delimiter=',') # skipping header row first_row =next(data_lines) # assigning the first montrh sales prev = int(next(data_lines)[1]) months_counter = 1 total_sales = prev # creating a for loop to read the data rows for row in data_lines: month = row[0] sale = int(row[1]) change = sale - prev total_sales = total_sales + sale prev = sale # calculating The total net amount of "Profit/Losses" over the entire perio total_sales_change = total_sales_change + change # calculating the total number of months included in the dataset months_counter = months_counter + 1 # calculating the greatest monthly increase if change > greatest_increase: greatest_increase = change greatest_month = month # calculating the greatest monthly decrease if change < greatest_decrease: greatest_decrease = change lowest_month = month # calculating the average change in "Profit/Losses" between months over the entire period average_change = round(total_sales_change/(months_counter-1), 2) # writing/creating a text file for the results text_file = open("Finanatial_Analysis_result.txt", "w") print(" Financial Analysis", file = text_file) print(" ----------------------------", file = text_file) print("Total Months: " + str(months_counter), file = text_file) print("Total: $" + str(total_sales), file = text_file) print("Average Change: $" + str(average_change), file = text_file) print("Greatest Increase in Profits: " + str(greatest_month) + " ($" + str(greatest_increase) + ")", file = text_file) print("Greatest Decrease in Profits: " + str(lowest_month) + " ($" + str(greatest_decrease) + ")", file = text_file)
true
109fa5c7bb6c4ca98dbe0da4cb4b05fd6b278428
mmantoniomil94/D4000
/Cipher.py
1,489
4.3125
4
# Write your methods here after you've created your tests #A python program to illustrate Caesar Cipher Technique def login(): user = raw_input("Username: ") passw = raw_input("Password: ") f = open("users.txt", "r") for line in f.readlines(): us, pw = line.strip().split("|") if (user in us) and (passw in pw): print "Login successful!" return True print "Wrong username/password" return False def menu(): #here's a menu that the user can access if he logged in. def main(): global True while True: True = True log = login() if log == True: menu() True = False main() def encrypt(text,s): result = "" # traverse text for i in range(len(text)): char = text[i] # Encrypt uppercase characters if (char.isupper()): result += chr((ord(char) + s-65) % 26 + 65) # Encrypt lowercase characters else: result += chr((ord(char) + s - 97) % 26 + 97) return result def decrypt(text,s): result = "" # traverse text for i in range(len(text)): char = text[i] # Decrypt uppercase characters if (char.isupper()): result += chr((ord(char) - s-65) % 26 + 65) # Decrypt lowercase characters else: result += chr((ord(char) - s - 97) % 26 + 97) return result
true
22b4129e4db8c0dd4a4f4b03cd264da540817669
CodingDojoDallas/python_march_2017
/jessica_hart/assignments/Basics/string_n_list.py
1,190
4.34375
4
# Print the position of the first instance of the word "monkey" # Then create a new string where the word "monkey" is replaced with the word "alligator" str = "If monkeys like bananas, then I must be a monkey!" print "Index of the first monkey:", str.find("monkey") new_str = str.replace("monkey", "alligator", 1) print new_str # Print the min and max values in a list x = [2,54,-2,7,12,98] print "The min and max are {} and {} respectively".format(min(x), max(x)) # Print the first and last values in a list # Create a new list containing only the first and last values in the original x = ["hello",2,54,-2,7,12,98,"world"] print "The first and last values are {} and {}".format(x[0], x[-1]) # Alternatives: len(x)-1 y = [x[0], x[-1]] print y # Start with a list. Sort your list first. Then, split your list in half. # Push the list created from the first half to position 0 of the list created from the second half x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() # Sort the list in ascending order print x x1 = x[:len(x)/2] # Split the list into two halves x2 = x[len(x)/2:] print x1, x2 x2.insert(0, x1) # Insert the first list into index 0 of the second list print x2
true
a7124975646f3fe613bf9575eb1b772056d9dc62
CodingDojoDallas/python_march_2017
/jessica_hart/assignments/OOP/animal_class.py
1,484
4.1875
4
class Animal(object): def __init__(self, name): # Initialize an animal with set health and give name self.name = name self.health = 100 def walk(self): # Walking and running drains the animal's health self.health -= 1 return self def run(self): self.health -= 5 return self def displayHealth(self): print "Current health:", self.health class Dog(Animal): def __init__(self, name): super(Dog, self).__init__(name) # Inherit the parent class initialization self.health = 150 def pet(self): # Exclusive pet method for Dogs that heals self.health += 5 return self class Dragon(Animal): def __init__(self, name): super(Dragon, self).__init__(name) # Inherit the parent class initialization self.health = 170 def fly(self): # Exclusive fly method for Dragons that decreases health self.health -= 10 return self def displayHealth(self): print "This is a dragon!" super(Dragon, self).displayHealth() # Inherit the parent class displayHealth animal = Animal("animal") animal.walk().walk().walk().run().run().displayHealth() dog = Dog("Dog") dog.walk().walk().walk().run().run().pet().displayHealth() dragon = Dragon("Dragon") dragon.walk().walk().walk().run().run().fly().fly().displayHealth()
true
f023923d44357298c9696963caacea756017a639
CodingDojoDallas/python_march_2017
/kim_cole/Assignments/FunWithFunctions.py
600
4.21875
4
#Odd/Even def odd_even(): for x in range(1, 2001): if x % 2 == 0: print x, " this is an even number." else: print x, " this is an odd number." odd_even() #Multiply: def multiply(arr, n): for x in range(0, len(arr)): arr[x] *=n return arr n_array = [2,4,10,16] print multiply(n_array,5) def layered_multiples(arr): print arr new_array = [] for x in arr: val_arr = [] for i in range(0,x): val_arr.append(1) new_array.append(val_arr) return new_array x = layered_multiples(multiply([2,4,5],3)) print x
false
61020f395f53b981ec59bb83f3dda2f489182c0a
CodingDojoDallas/python_march_2017
/jessica_hart/assignments/Basics/coin_toss.py
665
4.15625
4
import random # Function that simulates tossing a coin a number of times, counting the heads/tails def coin_toss(reps): print "Starting the program..." head_count = 0 tail_count = 0 for count in range(reps): odds = random.randrange(1, 3) # Random number that's either 1 or 2 if odds == 1: coin = "head" head_count += 1 else: coin = "tail" tail_count += 1 print "Attempt #{}: Throwing a coin... It's a {}! ... Got {} heads(s) so far and {} tails(s) so far".format(count+1, coin, head_count, tail_count) print "Ending the program, thank you!" coin_toss(5000)
true
937b0c965007b3cfbe9d7cb352fb1164f6ef674e
CodingDojoDallas/python_march_2017
/emmanuel_ogbeide/ASSIGNMENTS/fwf.py
814
4.15625
4
def odd_even(): for count in range (1, 2001): if count % 2 == 0: print "Number is " + str(count) + ". This is an even number." else: print "Number is " + str(count) + ". This is an odd number." odd_even() #Above block checks for oddity of functions def multiply(a, n): for index, item in enumerate(a): a[index] *= n return a x = multiply([2,3,4,5,6,7,8], 2) print x #Above block multiplies list items by a value def Blist(a): layered_arr = [] for index, item in enumerate(a): y = a[index] t = [] for count in range(0, y): t.append(1) count = count - 1 layered_arr.append(t) return layered_arr y = Blist(multiply([2,3,4,5,6,7,8], 2)) print y #Above block does stuff I can't explain
true
fcb7036ea15b970d83a5271ffd086306e5119685
mayurilahane/Python_Practise
/class.py
1,204
4.375
4
# #to delete the object: # x = "hello" # print(x) #before deleting object # del x # print(x) #after deleting object class People(object): def __init__(self, name): self.name = name def details(self): return self.name class Student(People): def __init__(self, name, marks): People.__init__(self, name) self.marks = marks def details(self): return (self.name, self.marks) class Teacher(People): def __init__(self, name, year): People.__init__(self, name) self.year = year def details(self): return (self.name, self.year) pep = People("mayuri") print(pep.details()) stud = Student("rujuta", 100) print(stud.details()) tech = Teacher("demo", 2005) print(tech.details()) """Default Module""" import os import requests #printing objects address class computer: pass c1 = computer print(id(c1))#to get the menory address of that object from heap memory #heap memory stores all the objects creted and id gives its address num = [1,2,3,4,5] it = iter(num) print(it) #will print object print(next(it)) #will print next value print(it.__next__()) #other way to print next value print(it.__next__()) #and so on....
true
fcd767f290b880ee86435f4de1d4e16f29cc0d71
srinath3101/ibm-yaml-training
/methodsdemo4.py
858
4.25
4
""" Variable Scope """ a=10 def test_method(a): print "Value of local a is:" , a a=2 print "New value of local a is", a print "Value of global a is:",a test_method(a) print "Did the value of global a change?" , a """ ***********output********* Value of global a is: 10 Value of local a is: 10 New value of local a is 2 Did the value of global a change? 10 """ print("*******************************") def test_method1(): global a print "Value of 'a' inside the method is:" ,a a=2 print "New value of 'a' inside the methode is changed to :" ,a print "Value of global a is:" ,a test_method1() print "Did the value of global 'a' change?" , a """ ***output*** Value of global a is: 10 Value of 'a' inside the method is: 10 New value of 'a' inside the methode is changed to : 2 Did the value of global 'a' change? 2 """
false
98a83bf5c5bff7844ff705a58d90770bb21ff349
srinath3101/ibm-yaml-training
/methodsexercise.py
1,228
4.25
4
""" Methods Exercise Create a method, which takes the state and gross income as the arguments and rereturns the net income after deducting tax based on the state. Assume Federal Tax: 10% Assume State tax on your wish. You don't have to do for all the states, just take 3-4 to solve the purpose of the exercise. """ def calculateNetIncome(gross,state): """ Calculate the net income after federal and state tax. :param goes: Gross Income :param state: State Name :return Net Income """ state_tax={'CA':10,'NY':9,'TX':0,'NJ':6} #Calculate net income after federal tax net= gross-(gross * .10) #Calculate net income after state tax if state in state_tax: net=net -(gross * state_tax[state]/100) print "Your net income after all the heavy taxes is:" , net return net else: print("State not in the list") return None calculateNetIncome(100000,'NJ') """ output Your net income after all the heavy taxes is: 80000.0(CA state) Your net income after all the heavy taxes is: 81000.0(NY state) Your net income after all the heavy taxes is: 90000.0(TX state) Your net income after all the heavy taxes is: 84000.0(NJ state) """
true
89455d9d17bf3d7b2485edda53e73d9767248469
srinath3101/ibm-yaml-training
/classdemo2.py
267
4.21875
4
""" Object Oriented Programming Create your own object """ class Car(object): def __init__(self,make,model='550i'): self.make=make self.model=model c1=Car('bmw') print(c1.make) print(c1.model) c2=Car('benz') print(c2.make) print(c2.model)
true
40da6ac4d395b6114675ac38d16e8098b4ad6281
WDLawless1/Python
/pythagoras.py
432
4.3125
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 11 07:31:52 2020 @author: user """ import math a = float(input("Please enter the length of the opposite side (in meters): ")) b = float(input("Please enter the length of the adjacent side (in meters): ")) c = math.sqrt(a**2 + b**2) alpha = math.degrees(math.atan(a/b)) print('The hypotenuse of this right triangle is ', c, 'meters. and the angle is', alpha,' degrees.')
true
a1a3ebe18b874807ea4670635c57e24c0c4c320a
ronaldfalcao/python-webscraping-meteorologia
/webscrap.py
950
4.1875
4
#webscraping com Python utilizando o BeautifulSoup utilizando as buscas da biblioteca import requests from bs4 import BeautifulSoup page = requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html") soup = BeautifulSoup(page.content, 'html.parser') ##Retornando o conteúdo da tag <p> #print (soup.find_all('p')) ##Exibindo apenas o conteúdo da tag <p> #print (soup.find_all('p')[0].get_text()) ##Alterando a página para buscas com id e class page = requests.get("http://dataquestio.github.io/web-scraping-pages/ids_and_classes.html") soup = BeautifulSoup(page.content, 'html.parser') ##Exbindo a tag <p> com class específico "outer-text" #print(soup.find_all('p', class_='outer-text')) ##Exibindo qualquer tag com class "outer-text" #print(soup.find_all(class_="outer-text")) ##Exibindo por um id específico "first" #print(soup.find_all(id="first")) ##Exibindo com busca pelos seletores CSS print(soup.select("div p"))
false
3e5da2edeee9428bfb9cc80f6415a30865dddb10
shreyansh225/InfyTQ-Foundation-Courses-Assignment-Answers
/Programming Fundamentals using Python/Day 4/T-strings.py
1,365
4.28125
4
#Creating a string pancard_number="AABGT6715H" #Length of the string print("Length of the PAN card number:", len(pancard_number)) #Concatenating two strings name1 ="PAN " name2="card" name=name1+name2 print(name) print("Iterating the string using range()") for index in range(0,len(pancard_number)): print(pancard_number[index]) print("Iterating the string using keyword in") for value in pancard_number: print(value) print("Searching for a character in string") if "Z" in pancard_number: print("Character present") else: print("Character is not present") #Slicing a string print("The numbers in the PAN card number:", pancard_number[5:9]) print("Last but one 3 characters in the PAN card:",pancard_number[-4:-1]) pancard_number[2]="A" #This line will result in an error, i.e., string is immutable print(pancard_number) ''' Length of the PAN card number: 10 PAN card Iterating the string using range() A A B G T 6 7 1 5 H Iterating the string using keyword in A A B G T 6 7 1 5 H Searching for a character in string Character is not present The numbers in the PAN card number: 6715 Last but one 3 characters in the PAN card: 715 Traceback (most recent call last): line 31, in <module> pancard_number[2]="A" #This line will result in an error, i.e., string is immutable TypeError: 'str' object does not support item assignment '''
true
2c6bd3f139106ee6a5a1693cc8ba83b1ba468621
Guilian-Deflandre/Football-Pass-Prediction
/Vectors.py
2,333
4.125
4
import math def dot(v,w): """ Compute the dot product of vectors v and w. PARAMETERS v, w: (x, y) ((float, float)) 2D components of vectors v, w. RETURN dot : float The dot product of v and w. """ x,y = v X,Y = w dot = x*X + y*Y return dot def norm(v): """ Compute the Euclidean norm of vector v. PARAMETERS v: (x, y) ((float, float)) 2D components of vectors v. RETURN norm : float The Euclidean norm of v. """ x,y = v norm = math.sqrt(x*x + y*y) return norm def vector(a,b): """ Compute the 2D components of vector a->b. PARAMETERS a, b: (x, y) ((float, float)) 2D coordinates of points a,b. RETURN vector : (v1, v2) ((float, float)) 2D components of vector a->b. """ x,y = a X,Y = b vector = (X-x, Y-y) return vector def unit(v): """ Transform v into a unity-norm vector. PARAMETERS v: (x, y) ((float, float)) 2D components of vector v. RETURN unit : (x, y) ((float, float)) 2D components of unit vector. """ x,y = v mag = norm(v) unit = (x/mag, y/mag) return unit def distance(p0,p1): """ Compute the 2D Euclidean distance between points p0 and p1. PARAMETERS p0, p1: (x, y) ((float, float)) 2D coordinates of points p0,p1. RETURN distance : float 2D Euclidean norm of vector p0->p1. """ distance = norm(vector(p0,p1)) return distance def scale(v,sc): """ Scale vector v by scaling factor sc. PARAMETERS v: (x, y) ((float, float)) 2D components of vector v. sc: float Scaling factor. RETURN scaled_vector : (x, y) ((float, float)) 2D components of scaled vector v*sc. """ x,y = v scaled_vector = (x * sc, y * sc) return scaled_vector def add(v,w): """ Add vectors v and w. PARAMETERS v, w: (x, y) ((float, float)) 2D components of vectors v, w. RETURN addition : (x, y) ((float, float)) 2D components of vector v+w. """ x,y = v X,Y = w addition = (x+X, y+Y) return addition
false
8cc85a8bd62a281b48ce4aebfb39e9b1a27335b1
berubejd/PyBites
/278/minmax.py
790
4.46875
4
#!/usr/bin/env python3.8 """ Bite 278. Major and minor numbers ☆ You are given a list of integers. Write code to find the majority and minorty numbers in that list. Definition: a majority number is the one appearing most frequently, a minority number appears least frequently. Here is a simple example how it should work: >>> numbers = [1, 2, 2, 3, 2, 3] >>> major_n_minor(numbers) (2, 1) """ from collections import Counter def major_n_minor(numbers): """ Input: an array with integer numbers Output: the majority and minority number """ c = Counter(numbers) major = c.most_common()[0][0] minor = c.most_common()[-1][0] # major = max(c, key=c.get) # minor = min(c, key=c.get) return major, minor print(major_n_minor([1, 2, 2, 3, 2, 3]))
true
7f3dde74d2ffe06bb423482b7c05e61b01bebce8
berubejd/PyBites
/119/xmas.py
593
4.25
4
#!/usr/bin/env python3.8 def generate_xmas_tree(rows=10): """Generate a xmas tree of stars (*) for given rows (default 10). Each row has row_number*2-1 stars, simple example: for rows=3 the output would be like this (ignore docstring's indentation): * *** *****""" max_row_length = rows*2-1 # for row in range(1, rows+1): # stars = '*' * (row * 2 - 1) # print(f'{stars:^{max_row_length}}') return '\n'.join([f'{"*" * (row * 2 - 1):^{max_row_length}}' for row in range(1, rows+1)]) print(generate_xmas_tree(10))
true
33f6282fe2f7dd28ffb268aeba4b20572f028552
YOlandaMcNeill/cti110
/M3HW2_BodyMassIndex_YolandaMcNeill.py
556
4.5
4
# This program will calculate a person's BMI and determine if their weight is opimal, underweight, or over weight. # 6.14.2017 # CTI-110 M3HW1 - Body Mass Index # YOlanda McNeill # #Get user's height. height = int(input('Enter your height in inches: ')) #Get user's weight. weight = int(input('Enter your weight in pounds: ')) #Calculate BMI. BMI = float(weight * 703/height**2) print('BMI=',BMI) if BMI < 18.5: print('UNDERWEIGHT.') elif BMI >= 18.5 or BMI < 25: print('Weight is OPTIMAL.') else: print('OVERWEIGHT.')
true
eeaa1be554f205f638ff6aea473ae73bbcbfd5f4
matheus3006/object-oriented-programming-oop
/sorting_algorithms/first_class.py
1,012
4.3125
4
""" AEscreva uma função que receba um float representando o valor da temperatura em Celsius e retorne a temperatura equivalente em Farenheit. Em seguida, escreva um código que leia uma temperatura em Celsius e informe o valor equivalente em Farenheit. """ # def celsius_to_farenheit(celsius): # return celsius * (9/5) + 32 # cel = input('Enter the temperature in celsius: ') # far = celsius_to_farenheit(float(cel)) # print(cel + ' C equivale to ' + str(far) + 'f') """ Escreva uma função booleana que recebe uma string e verifica se a mesma é um palíndromo. Em seguida, escreva um código para ler uma string e, usando a função criada, verifique se a mesma é uma string. """ # def isPalindrome(str): # for i in range(0, int(len(str) / 2)): # if(str[i] != str[len(str) - i - 1]): # return False # return True # str = input('Enter a string: ') # if(isPalindrome(str)): # print(str + ' is a palindrome') # else: # print(str + ' is not a palindrome')
false
131b07bdb8ab94d2d138e11b39891acbf766be1d
zacharyaanglin/python-practice
/python-practice/project-euler/problem_nine/main.py
1,000
4.28125
4
"""https://projecteuler.net/problem=9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ from functools import reduce import math from operator import mul from typing import Optional, Tuple def find_pythagorean_triple(sum: int) -> Optional[Tuple[int, int, int]]: """ Find a Pythagorean triple (a, b, c) such that a + b + c = 1000. If no such triple exists, return None. """ for a in range(1, int(sum/3)): for b in range(1, int(sum-2*a)): if a + b == sum/2 + (a*b) / sum: print('A is {}, B is {}'.format(a, b)) return a, b, int(math.sqrt(a**2 + b**2)) return None if __name__ == '__main__': triple = find_pythagorean_triple(1_000) product = reduce(mul, triple) print('Triple is', triple) print('Product is', product)
true
ffabb97390f2031e6bff672d4cb11d75ffc9f794
victorina-ya/HomeWork1
/2.py
673
4.15625
4
# Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). my_l = list(input("Введитее любое число, но без пробелов:")) for i in range(1, len(my_l), 2): my_l[i - 1], my_l[i] = my_l[i], my_l[i-1] print(my_l)
false
4a5aa878a7d9d7c826806bc8ad08a5fea6743f54
rofernan42/Bootcamp_Python
/day00/ex03/count.py
642
4.34375
4
def text_analyzer(text=""): "\nThis function counts the number of upper characters, lower characters, punctuation and spaces in a given text." while (len(text) == 0): text = input("What is the text to analyse?\n") print("The text contains " + "%s" % len(text) + " characters:") print("- " + "%s" % sum(c.isupper() for c in text) + " upper letters") print("- " + "%s" % sum(c.islower() for c in text) + " lower letters") print("- " + "%s" % (len(text) - sum(c.isalnum() for c in text) - sum(c.isspace() for c in text)) + " punctuation marks") print("- " + "%s" % sum(c.isspace() for c in text) + " spaces")
true
73dc40ebb53112a44af1e59630531edd669d8a75
Merbs/algorithms
/reverse_words.py
602
4.28125
4
### # Reverse Words in a String ### def reverse_words(string): reversed_string = '' j = len(string) for i in range(len(string)-1, 0, -1): if string[i] == ' ': reversed_string += string[i+1:j] + ' ' j = i reversed_string += string[:j] return reversed_string def reverse_words_pythonic(string): return ' '.join(reversed(string.split(' '))) test_cases = [ ("hello world", "world hello"), ("these words reversed", "reversed words these") ] for test_case, ans in test_cases: assert reverse_words(test_case) == ans print "All is Good"
false
cfe2d67cca7e4adcf32a20b425c7181e3cb177d9
Dprajapat765/Forsk-Technologies-Jaipur
/DAY_2/reverse.py
219
4.3125
4
# -*- coding: utf-8 -*- """ Created on Wed May 8 18:53:26 2019 @author: Dinesh Prajapat """ def reverse(string): reverse = string[::-1] return reverse string = input("enter the string to reverse it:") reverse(string)
false
0a0efbd6785daa8526f5b82dc06b92d843363bbb
tajimiitju/python_course
/Python_Short_Course/tribhuj_check.py
629
4.1875
4
#Taking Inputs a = int(input('please enter 1st arm ')) b = int(input('please enter 2nd arm ')) c = int(input('please enter 2nd arm ')) #Check for tribhuj Definition if ((a >= b + c) or (b >= a + c) or (c >= a + b)): print('This is not a triangle') else : #Opening a File with open('tribhuj.txt','w') as f: #check for Somobahu if a==b and b==c and a==c : f.write('Somobahu tribhuj') #Check for Bishombahu elif a!=b and b!=c and a!=c : f.write('Bishombahu tribhuj') #Remaining Somodibahu else: f.write('Somodibahu tribhuj')
false
ebee8b24709719a3f831f2c361475d2426276f12
tajimiitju/python_course
/long_class3/marks_tajim.py
1,089
4.15625
4
# coding: utf-8 # In[4]: #Assignment 1 by tajim # 3. Write a program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. # Calculate TOTAL percentage(Not Each subject) and grade according to following: # Percentage >= 90% : Grade A # Percentage >= 80% : Grade B # Percentage >= 70% : Grade C # Percentage >= 60% : Grade D # Percentage >= 40% : Grade E # Percentage < 40% : Grade F # Assume Each exam has 100 marks in total. Physics = int(input("Enter Physics Marks: ")) Chemistry = int(input("Enter Chemistry Marks: ")) Biology = int(input("Enter Biology Marks: ")) Mathematics = int(input("Enter Mathematics Marks: ")) Computer = int(input("Enter Computer Marks: ")) total_marks = Physics + Chemistry + Biology + Mathematics + Computer Percentage = (total_marks/500)*100 print('You have got ',Percentage,'% marks and got : Grade ',end='') if(Percentage>=90): print('A') elif(Percentage>=80): print('B') elif(Percentage>=70): print('C') elif(Percentage>=60): print('D') elif(Percentage>=40): print('E') else: print('F')
true
7d1bbd1d9e764570b537c8f531f73e3db06222ca
dk81/python_math
/arithmeticSeries.py
1,422
4.25
4
# Arithmetic Sequence & Series Functions # Formula: # Arithmetic Sequence Formula: end = start + (n - 1)d # end - start = (n - 1)d # (end - start) / d = n - 1 # (end - start) / d + 1 = n def find_term_n(start, n, diff): if start % 1 != 0: print("Please choose an integer.") elif n % 1 != 0 and n < 1: print("Please choose a positive whole number.") else: term_n = start + (n - 1)*diff return term_n print(find_term_n(start = 1, n = 10, diff = 6)) def find_numTerms_arithSeq(start, end, diff): if start % 1 != 0: print("Please choose an integer.") numTerms = 1 + (end - start) / diff if numTerms > 0: return int(numTerms) else: print("The number of terms cannot be negative. Try again.") print(find_numTerms_arithSeq(1, 10, -1)) # Arithmetic Series formula: # Finding the sum of an arithmetic series. # Reference: https://stackoverflow.com/questions/21583758/how-to-check-if-a-float-value-is-a-whole-number def find_arithmetic_seriesSum_verOne(start, end, n): if start % 1 == 0 and start > 0: if end % 1 == 0 and end > 0 and end > start: total = 0.5*n*(start + end) return total else: print("Choose a starting number that is a whole positive number please.") print(find_arithmetic_seriesSum_verOne(start = 1, end = 10, n = find_numTerms_arithSeq(1, 10, 1)))
true
d3c8944d172df2b52c866c29ad276162389857f0
Anoopcb/First_variables_1
/test_one_variables.py
2,152
4.53125
5
#print() function ## first project, how to print in print function print("Hello world") print('Hello world') #string:- collection of character inside "Double quotes" #or 'single quotes' # you can use 'single quotes' insides "double quotes" and #double quotes "" inside single quotes '' but you can not use #double quotes inside double quotes "" same with single quotes ### please see below example print("Hello 'world' world") print('Hello "world" world') #Escape Sequences #\' single quote #\" double quote #\\ backslash #\n new line #\t tab #\b backspace print('Hello \'world\' world') print("Hello \"world\" world") print("Hello World\nHello World") #Comments, like this, python ignore all these hash comments #for out put Line A \n Line B print("Line A \\n Line B") print("#****print these following lines*****") print("This is \\\\ double blackslash") print("this is /\\/\\/\\/\\/\\ mountain") print("\\\" \\n \\t \\\' ") ## if you put r before double quotes or single quotes in print ## function then this will treat escape sequance as a normal test # how to print emoji print("\U0001F602") print("\U0001F604") #Python as a calculator ## use print function and you can do any calculation inside it print(2+3) #Operators # + Additon # - Subtraction # * Multiplication # / Float division # // integer division # 5 Modulo, it gives remainder # ** Exponent ## use bodmash rule and ##Precedence rule #####*** VARIABLES finally ****** # varialbe ar just container which can store any data in memory ## or you can say these are agents for a memory allotment ## you can change value in variables ### varibles are immutable number = 1 print(number) number= "Anoop" print(number) #### variable rule ##### you can't start a variable name by number # 2number = 44, will give a error ####### second rule # can be start any letter or _ print(number[0])### we will see these string topic #### convention ## normally we use snake case writting ### use_one_name ##### useOneName--camel case writting, we should avoid this tye of writting
true
aea1599b5709e0d5c0c45b7c910bf898db701aad
housewing/Data-Structure
/LinkedList/LinkedList.py
2,091
4.125
4
class Node: def __init__(self, value): self.data = value self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def size(self): current = self.head count = 0 while current is not None: count += 1 current = current.next return count def insertFront(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def insertBack(self, data): new_node = Node(data) current = self.head while current is not None: if current.next is None: current.next = new_node break current = current.next def insert(self, node, data): new_node = Node(data) new_node.next = node.next node.next = new_node def search(self, data): current = self.head while current is not None: if current.data == data: break current = current.next return current def traversal(self): current = self.head while current is not None : print(current.data) current = current.next def reverse(self): parent = self.head me = parent.next child = me.next parent.next = None while child is not None: me.next = parent parent = me me = child child = child.next me.next = parent self.head = me return self.head def main(): root = LinkedList() for i in range(1, 5): root.insertFront(i * 10) print('----- size -----', root.size()) number = 30 node = root.search(number) print('----- insert ----') root.insert(node, 150) root.insertBack(65) print('----- traversal -----') print(root.traversal()) root.reverse() print('----- reverse -----') print(root.traversal()) print('----- size -----', root.size()) if __name__ == '__main__': main()
true
188234f214487f3ed30de2515971e58b099cb6ce
print-Hell/Python-stuff
/Guessing game.py
1,614
4.125
4
import random secret_number = (random.randint(0,10)) count = 0 greetings = print(f'Hey Welcome To My Guessing Game Which I Made On Python. You Will Have 3 Guesses And Each Time You Guess I Will Tell You If You Are Close To The Number Or Not.') print('The secret numbers range is from 1-10') First_guess =int(input('Your first guess is....')) if secret_number == First_guess : print(f'Outstanding luck your guess was spot on ') print('Thanks for playing') quit() elif First_guess < secret_number: print('Your number is too low') count +=1 elif First_guess > secret_number: print('Your number is too high') count +=1 Second_guess =int(input('Your second guess is....')) if secret_number == Second_guess: print(f'Good job your guess was spot on ') print('Thanks for playing') quit() elif Second_guess < secret_number: print('Your number is too low') count +=1 elif Second_guess > secret_number: print('Your number is too high') count +=1 Third_guess =int(input('Your last guess is....')) if secret_number == Third_guess: print(f'Good job your guess was spot on ') print('Thanks for playing') quit() elif Third_guess < secret_number: print('Your number is too low') count +=1 elif Third_guess > secret_number: print('Your number is too high') count +=1 if count == 3: print('You have run out of guesses :(. Good luck next time.') print(f'Btw the number was {secret_number} dummy! ') quit()
true
f377f51b11c09e8d01e8d6b86f36d5af29fbc7c2
emmaliden/thePythonWorkbook
/E44.py
460
4.375
4
month = raw_input("Enter a month of the year (the complete name): ") day = input("Enter the day of the month: ") holiday = "No holiday" if month == "January" and day == 1: holiday = "New years's day" if month == "July" and day == 1: holiday = "Canada day" if month == "December" and day == 25: holiday = "Christmas day" if holiday == "No holiday": print("%r %r is not holiday" % (month, day)) else: print("%r %r is %r" % (month, day, holiday))
true
7cf0243f31c62097919d7fa56a32c0eceea90b2c
emmaliden/thePythonWorkbook
/E66.py
902
4.28125
4
# Create a grade to points dictionary gradeToPoints = {'A+':4.0, 'A':4.0, 'A-':3.7, 'B+':3.3, 'B':3.0, 'B-':2.7, 'C+':2.3, 'C':2.0, 'C-':1.7, 'D+':1.3, 'D':1.0, 'F':0} print(gradeToPoints['A']) grade = str(input("Input a valid letter grade: ")) grade = grade.upper() while grade not in gradeToPoints: print("That is not a valid grade. Try again.") grade = str(input("Input a valid letter grade: ")) grade = grade.upper() sumGrade = 0 count = 0 while grade != '': while grade not in gradeToPoints: print("That is not a valid grade. Try again or blank to quit") grade = str(input("Input a valid letter grade (or blank to quit): ")) gradePoint = gradeToPoints[grade] sumGrade = sumGrade + gradePoint count = count + 1 grade = str(input("Input a valid letter grade (or blank to quit): ")) grade = grade.upper() print("The grade point average is ", sumGrade/count)
true
8e484d6f171811be50a3b88b3ae08b47ec59bcf6
emmaliden/thePythonWorkbook
/E39.py
791
4.34375
4
jackhammer = 130 gas_lawnmower = 106 alarm_clock = 70 quiet_room = 40 decibel = input("What is the decibel level?: ") if decibel<quiet_room: print("That's quieter than a quiet room") elif decibel==quiet_room: print("That's like a quiet room") elif decibel<alarm_clock: print("That's somewhere between a quiet room and an alarm clock") elif decibel==alarm_clock: print("That's like an alarm clock") elif decibel<gas_lawnmower: print("That's somewhere between an alarm clock and a gas lawnmower") elif decibel==gas_lawnmower: print("That's like a gas lawnmover") elif decibel<jackhammer: print("That's somewhere between a gas lawnmover and a jackhammer") elif decibel==jackhammer: print("That's like a jackhammer") else: print("That's louder than a jackhammer!")
true
8bf385b881b38c597f1995fc1544f2d4346d3123
emmaliden/thePythonWorkbook
/E50.py
753
4.34375
4
# Find the real roots of a quadratic equation print("A quadratic equation has the form f(x) = ax2 + bx + c, where a, b and c are constants") print("This program will give you the real roots of your equation") a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) discriminant = b**2 - 4 * a * c if discriminant < 0: roots = 0 elif discriminant == 0: roots = 1 else: roots = 2 if roots == 0: print("There are no real roots to this equation") elif roots == 1: root = - b / (2 * a) print("This equation has one real root and it is %r" % (root)) else: root1 = (-b + (discriminant**0.5)) / (2 * a) root2 = (-b - (discriminant**0.5)) / (2 * a) print("This equation has two real roots and they are %r and %r" % (root1,root2))
true
c4d0337daec2b0accdcb4a69d085600ae884718f
raunakkunwar/college-projects
/TkinterGUIProject/Creating_Text_Field.py
2,831
4.21875
4
from tkinter import * #text widget is not a theme widget of ttk module. So, we don't have to import the ttk module. root = Tk() text = Text(root, height = 10, width = 40) #Height and width are defined in characters text.pack() text.config(wrap = 'word') #Make each line on the box to wrap after a complete word #By default it wraps by a character #To get the desired content from the textbox: print(text.get('1.0', 'end')) #Here '1.0' represents 'line.char', i.e The 0th character of the first line #'end' represents the end of the text in the box. So this gives all the text in the box print(text.get('1.0', '1.end')) #Gives the first logical line of the textbox #Here logical line refers to the line which ends with a new line character, i.e '\n' #To insert text at any position in the text box: text.insert('1.0 + 2 lines', 'Inserted text') #Inserts the text in the 3rd line from the start text.insert('1.0 + 2 lines lineend', 'Another inserted text') #This inserts the text at the end of the third line #To delete any text in the box: text.delete('1.0','1.0 lineend + 1 chars') #Doing this not only deletes the 1st line, but also deletes the remaining new line character #in the first line #To replace text in the box: text.replace('1.0', '1.0 lineend', 'This is the replaced text') #To configure the state: text.config(state = 'disabled') text.config(state = 'normal') #About Tags: #A tag is a set of characters to which we can perform several changes using the tagname: text.tag_add('tag_name', '1.0', '1.0 wordend') #Creates a tag from 1.0 to 1.0 wordend text.tag_configure('tag_name', background = 'yellow') text.tag_remove('tag_name', '1.1', '1.3') #To get the range of characters included in a tag: text.tag_ranges('tag_name') #To get the names of tags used in the text box: text.tag_names() text.tag_names('1.0') #Shows the tag name for the 1st character text.replace('tag_name.first', 'tag_name.last', 'Replaced text')#Replaces the characters of the tag text.tag_delete('tag_name') #About Marks: #A mark is the position where you want to insert something or where your mouse position is #currently text.mark_names() #Shows the names of the marks which are insert and current text.insert('insert', '_') text.mark_set('my_mark', 'end') #Sets the created mark 'my_mark' at the end of the text text.mark_gravity('my_mark', 'right') #Decides whether to shift the inserted text to left/right text.mark_unset('my_mark') #Deletes the mark you created earlier #To insert image or widget to the textbox: # new_image = PhotoImage(file = '\Location') # text.image_create('insert', image = new_image) #Adding a button to the text field: button = Button(text, text = 'Click Me') text.window_create('insert', window = button)
true
7d1b724dfd5cb6f52b0c4a035048167f0c475c54
sutariadeep/datastrcutures_python
/LinkedList/deleting_element_value.py
1,881
4.34375
4
# Python program to delete a node in a linked list # with a given value # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Constructor to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Given a reference to the head of a list # and a value, delete the node with that value def deleteNode(self, value): # If linked list is empty if self.head == None: return # If head needs to be removed while self.head != None and self.head.data == value: temp = self.head self.head = self.head.next temp = None #current points to the next link while temp points #to the node to be removed while scanning through #the list current = self.head while current.next != None: if current.next.data == value: temp = current.next current.next = temp.next temp = None else: current = current.next # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print " %d " %(temp.data), temp = temp.next # Driver program to test above function llist = LinkedList() llist.push(7) llist.push(1) llist.push(3) llist.push(2) llist.push(8) value = 7 print "Created Linked List: " llist.printList() llist.deleteNode(value) print print "After deletion of element valued %s:"%(value) llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
true
8eee7394059e17e653e83ed3f5581300e104a15c
cowleyk/sort_lists
/sort_lists.py
1,509
4.21875
4
import sys def mergeSort(formattedLists): first = formattedLists[0] second = formattedLists[1] # first and second are already sorted # need to perform merge sort and turn each item into an integer # initialize counting variables and final list i = 0 j = 0 sorted = [] # typical merge sort approach, look at each item starting at the front of each list # append the lower of the two list items first while i < len(first) and j < len(second): firstInt = int(first[i]) secondInt = int(second[j]) if firstInt < secondInt: sorted.append(firstInt) i += 1 else: sorted.append(secondInt) j += 1 # if second list has been totally added to final list, add all remaining # items from the first list while i < len(first): sorted.append(int(first[i])) i += 1 # if first list has been totally added to final list, add all remaining # items from the second list while j < len(second): sorted.append(int(second[j])) j += 1 # display final sorted list print(sorted) return sorted def formLists(stringList): newList = ''.join(stringList).strip('[]').split('][') # want to keep with goal behind problem statement and merge two sorted lists # rather than sorting on long list of numbers first = newList[0].split(',') second = newList[1].split(',') return [first, second] if __name__ == '__main__': # need to format incoming arguments formattedLists = formLists(sys.argv[1:]) mergeSort(formattedLists)
true
9bfbacd404884eb996501c9c3ce36a8ac912e313
dishashetty5/Python-for-Everybody-Variables-expressions-and-statements
/chap2 5.py
264
4.25
4
""" Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature""" celsius=input("enter the degree in celsius") h=float(celsius) f=(h*9/5)+32 print("degree in fhrenheit",f)
true
f15d96b02094f24ed598aaaa6a1aea1c88eac198
andrewt18/course
/Python/Lesson_1/GuessNumber.py
590
4.25
4
import random print('Try to guess the system number.') count = 0 systemNumber = random.randint(1,100) while systemNumber != "": mynumber = int(input("Enter a number: ")) count += 1 if (mynumber < 1) or (mynumber > 100): print('Please enter a number from 1 to 100: ') continue if mynumber < systemNumber: print('Your number is smaller than system number') continue if mynumber > systemNumber: print('Your number is bigger than system number') continue if mynumber == systemNumber: print('Correct! You have guessed with ' + str(count) + ' attempts!') break input()
true
4460cd9e9e6264d82b0340156b5f9c5723e269e4
mukund7296/Python-Brushup
/37 class adn objects.py
588
4.21875
4
# how to create class class Person(): # how to initialize attributes # init method we use to create methods def __init__(self,name,age,weight,height): self.name=name self.age=age self.weight=weight self.height=height def details(self): print( "Name :-",self.name,"\nAge :-",self.age,"\nHeight :-",self.height,"\nWeight :-",self.weight) ob1=Person("Mukund Biradar",33,113,"6.3 feet") # self value is ob1 now print(ob1.details()) ob2=Person("Shaurya Biradar",18,23,"2.3 feet") # self value is ob2 now print(ob2.details())
false
1d585ae933bd9a283c1cae1c40347e44f2733655
mukund7296/Python-Brushup
/01 Data types.py
1,338
4.15625
4
# diffrent types of data types. # python have default string. # if you want " between then sue 'wrap with single quote' # if you want ' between then use "wrap your string here" print('Mukund Biradar') print("Mukund's Biradar Laptops's") print('Mukund"s" Biradar Laptops') print('Mukund\'s Biradar Laptops') # raw data or string we use to r"abcdefgh" print(r"C:\Users\Mukund\Downloads\navine") print(r"C:\Users\Mukund\Downloads\navine") '''Built-in Data Types In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview''' # python default data type is string x='' print(type(x)) x = 5 print(type(x)) x = 5.9 print(type(x)) x = "5" print(type(x)) x = [1,2,3,4,5,6] print(type(x)) x = (1,2,3,4,5,6) print(type(x)) x = {1,2,3,4,5,6} print(type(x)) x = {1:"mukund",3:"Harish",5:"anand"} print(type(x)) x = complex(1j) print(type(x)) x = list(("apple", "banana", "cherry")) print(type(x)) x = (("apple", "banana", "cherry")) print(type(x))
true
5cd1586c0e6874f2e43090915d9a7715e10b2a73
pyMurphy/hacker-olympics-2019
/Ryan/anagram.py
206
4.15625
4
def anagram(words): word1,word2=words.strip().split() if sorted(word1)==sorted(word2): print('The words are anagrams') else: print('The words are not anagrams') anagram(input())
true
2b993c8e8beebcff4186986d900d4bc691220085
taism-ap/hw-3-3-python-list-problems-IsaacJudeBos
/python_list_find_number.py
1,298
4.125
4
#This is the stuff from list_setup.py # import the randint function from the random module from random import randint # create a function to generate a list of "size" random integers # up to a maximum of "largest" def random_list(largest,size): # create an empty list l = [] # add a random number to the list the appropriate number of times for i in range(size): n = randint(0,largest-1) l.append(n) #print the list to check return(l) #call the function l = random_list(9,10) #MY STUFF! #testing manual variable setting place: print(l) imputNumber = 0 def find_number(Number): #Set variables to their defaults frequency = 0 locationList = [] position = 0 #This thing looks through everything while position <= 9: if l[position] == Number: frequency = frequency + 1 locationList.append(position) position = position + 1 #This thing compiles the outputs in 1 list and returns that outputList = [frequency,LocationList] return(outputList) #This is an alternate output meathod for the function print(frequency) print(locationList) #This runs the function find_number(imputNumber) result = find_number(imputNumber) numb = result.pop[0] print(result) print(numb)
true
cabea165a389adb76279499a69d9f3d361825a6e
chaositect/pandas
/dataframe_apply_map_and_vector_functions.py
1,927
4.15625
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 19 17:32:48 2021 @author: Grant Isaacs """ #IMPORT LIBRARIES-------------------------------------------------------------> import pandas as pd import numpy as np #LOAD DATA--------------------------------------------------------------------> dataset = np.round(np.random.normal(size=(4,3)), 2) dataset = pd.DataFrame(dataset, columns=['A', 'B', 'C']) #APPLY------------------------------------------------------------------------> """Used to execute a function against an entire dataframe or subset. Functions used in this manner must be vectorized functions.""" def some_function(x): x = x**2 x += 100 return x dataset_01 = dataset.apply(some_function) """A lambda expression can also be placed directly in the argument.""" dataset_02 = dataset.apply(lambda x: (x**2) + 100) """Apply can be used with one or more columns.""" dataset_03 = dataset.copy() dataset_03[["A", "B"]] = dataset[["A", "B"]].apply(some_function) dataset_04 = dataset.copy() dataset_04.A = dataset.A.apply(some_function) #MAP--------------------------------------------------------------------------> """Map is similar to apply but only runs on a series and can use dictionaries as inputs.""" series = pd.Series(["Steve Jackson", "Alex Trebek", "Jessica Rabbit", "Mark Hamill"]) series_01 = series.map({"Steve":"Steven"}) series_02 = series.map("My name is {}".format) series_03 = series.map(lambda x: f"I am {x}") series_04= dataset.A.map(lambda x: f"The number is {x}") #VECTORIZED FUNCTIONS---------------------------------------------------------> """Pandas as Numpy have a number or built in vectorized functions.""" series_05 = series.split() #This will not work because .split is not a vectorized function series_05 = series.str.split() #This is the correct version using the built in vectorized function. series_05 = series.str.split(expand=True) series.str.contains("Jackson") series.str.upper()
true
41f24113d9557610911f64ca1fa4c7bb3f31be62
alexandrabrt/calculator_grupa2
/Calculator.py
2,663
4.15625
4
# list = ["+", "-", "*", "/"] # continua = "DA" # while continua == "DA": # # # numar1 = input("Primul numar:\n") # operatia = input("Ce operatie vrei sa faci (+, -, *, /):\n") # numar2 = input("Al doilea numar:\n") # # numar1 = float(numar1) # numar2 = float(numar2) # # rezultat = None # # if operatia in list: # if operatia == "+": # rezultat = numar1 + numar2 # elif operatia == "-": # rezultat = numar1 - numar2 # elif operatia == "*": # rezultat = numar1 * numar2 # elif operatia == "/" and numar2 != 0: # rezultat = numar1 / numar2 # if rezultat is None: # print("Nu se poate realiza impartirea la zero!") # else: # print("Rezultat este:" + str(rezultat)) # continua = input("Vrei sa reiei operatia? ").upper() # def adunare(numar1: int, numar2: int) -> int: """ :param numar1: Primul numar introdus de la tastatura :param numar2: Al doilea numar introdus de la tastatura :return: Suma celor doua numere """ return numar1 + numar2 def scadere(numar1: int, numar2: int) -> int: """ :param numar1: Primul numar introdus de la tastatura :param numar2: Al doilea numar introdus de la tastatura :return: Diferenta celor doua numere """ return numar1 - numar2 def inmultire(numar1: int, numar2: int) -> int: """ :param numar1: Primul numar introdus de la tastatura :param numar2: Al doilea numar introdus de la tastatura :return: Inmultirea celor doua numere """ return numar1 * numar2 def impartire(numar1: int, numar2: int) -> float: """ :param numar1: Primul numar introdus de la tastatura :param numar2: Al doilea numar introdus de la tastatura :return: Impartirea celor doua numere """ return numar1 / numar2 def main() -> float: rezultat = None numar_ales_1 = int(input("Introduceti primul numar: ")) numar_ales_2 = int(input("Introduceti al doilea numar: ")) operatia = input("Selectati operatia dorita: ") if operatia == "+": rezultat = adunare(numar_ales_1, numar_ales_2) elif operatia == "-": rezultat = scadere(numar_ales_1, numar_ales_2) elif operatia == "*": rezultat = inmultire(numar_ales_1, numar_ales_2) elif operatia == "/" and numar_ales_2 != 0: rezultat = impartire(numar_ales_1, numar_ales_2) return rezultat continua = 'DA' while continua == 'DA': a = main() if a is None: print("Nu se poate realiza impartirea la zero ") else: print(a) continua = input("Vrei sa reiei operatia? ").upper()
false
13d1a5da5e3127187d9f7c85065eb4cca933200d
yuchench/sc101-projects
/stanCode_Projects/hangman_game/rocket.py
1,726
4.28125
4
""" File: rocket.py Name: Jennifer Chueh ----------------------- This program should implement a console program that draws ASCII art - a rocket. The size of rocket is determined by a constant defined as SIZE at top of the file. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ # This constant determines rocket size. SIZE = 3 def main(): """ This program is to built a rocket in different sizes. """ head() belt() upper() lower() belt() head() def head(): """ :return: Built a rocket head. """ for i in range(SIZE): for j in range(SIZE-i): print(' ', end='') for k in range(i+1): print('/', end='') for m in range(i+1): print('\\', end='') print("") def belt(): """ :return: Built a rocket belt. """ for i in range(1): print('+', end='') for j in range(SIZE*2): print('=', end='') print('+', end='') print("") def upper(): """ :return: Built a rocket upper-body. """ for i in range(SIZE): for j in range(1): print('|', end='') for k in range(SIZE-i-1): print('.', end='') for m in range(i+1): print('/\\', end='') for n in range(SIZE-i-1): print('.', end='') for o in range(1): print('|', end='') print("") def lower(): """ :return: Built a rocket lower-body. """ for i in range(SIZE): for j in range(1): print('|', end='') for k in range(i): print('.', end='') for m in range(SIZE-i): print('\\/', end='') for n in range(i): print('.', end='') for o in range(1): print('|', end='') print("") ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
true
da3146f0e7228765ea44b9ca1e64b08121e48ba3
VagrantXD/Stajirovka
/7kyu/herosRoot.py
2,096
4.59375
5
#!/bin/python3 import math #One of the first algorithm used for approximating the integer square root of a positive integer n is known as "Hero's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first description of the method. Hero's method can be obtained from Newton's method which came 16 centuries after. # #We approximate the square root of a number n by taking an initial guess x, an error e and repeatedly calculating a new approximate integer value x using: (x + n / x) / 2; we are finished when the previous x and the new x have an absolute difference less than e. # #We supply to a function (int_rac) a number n (positive integer) and a parameter guess (positive integer) which will be our initial x. For this kata the parameter 'e' is set to 1. # #Hero's algorithm is not always going to come to an exactly correct result! For instance: if n = 25 we get 5 but for n = 26 we also get 5. Nevertheless 5 is the integer square root of 26. # #The kata is to return the count of the progression of integer approximations that the algorithm makes. # #Reference: # #https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method # #Some examples: # #int_rac(25,1): follows a progression of [1,13,7,5] so our function should return 4. # #int_rac(125348,300): has a progression of [300,358,354] so our function should return 3. # #int_rac(125348981764,356243): has a progression of [356243,354053,354046] so our function should return 3. # # #You can use Math.floor (or similar) for each integer approximation. # # # #Note for JavaScript, Coffescript, Typescript: # #Don't use the double bitwise NOT ~~ at each iteration if you want to have the same results as in the tests and the other languages. # import math def int_rac(n, guess): """Integer Square Root of an Integer""" res = 1 while abs( guess - math.floor( ( guess + n / guess ) / 2 ) ) >= 1 : guess = math.floor( ( guess + n / guess ) / 2 ) res += 1 return res if __name__ == "__main__" : print( int_rac( 125348, 300 ) )
true
a08575c9aac62218cf30fd6d3ce7f20f5e366f2f
VagrantXD/Stajirovka
/7kyu/maximumProduct.py
1,238
4.40625
4
#!/bin/python3 #Task #Given an array of integers , Find the maximum product obtained from multiplying 2 adjacent numbers in the array. # #Notes #Array/list size is at least 2 . # #Array/list numbers could be a mixture of positives , ngatives also zeros . # #Input >> Output Examples #adjacent_elements_product([1,2,3]) ==> return 6 #Explanation: #The maximum product obtained from multiplying 2 * 3 = 6, and they're adjacent numbers in the array. #adjacent_elements_product([9, 5, 10, 2, 24, -1, -48]) ==> return 50 #Explanation: #Max product obtained from multiplying 5 * 10 = 50 . # #adjacent_elements_product([-23, 4, -5, 99, -27, 329, -2, 7, -921]) ==> return -14 #Explanation: #The maximum product obtained from multiplying -2 * 7 = -14, and they're adjacent numbers in the array. #Playing with Numbers Series #Playing With Lists/Arrays Series #For More Enjoyable Katas #ALL translations are welcomed #Enjoy Learning !! #Zizou def adjacent_element_product(array): max = array[ 0 ] * array[ 1 ] for i in range( 1, len( array ) - 1 ) : if array[ i ] * array[ i + 1 ] > max : max = array[ i ] * array[ i + 1 ] return max if __name__ == "__main__" : print( adjacent_element_product( [ 1, 2, 3 ] ) )
true
deffdf32ba128db0d671d254d01b99b41156ee66
VagrantXD/Stajirovka
/6kyu/threeAddedChar.py
1,276
4.28125
4
#!/bin/python3 #Given two strings, the first being a random string and the second being the same as the first, but with three added characters somewhere in the string (three same characters), # #Write a function that returns the added character # #E.g #string1 = "hello" #string2 = "aaahello" # #// => 'a' #The above is just an example; the characters could be anywhere in the string and string2 is actually shuffled. # #Another example #string1 = "abcde" #string2 = "2db2a2ec" # #// => '2' #Note that the added character could also exist in the original string # #string1 = "aabbcc" #string2 = "aacccbbcc" # #// => 'c' #You can assume that string2 will aways be larger than string1, and there will always be three added characters in string2. # #Can you do it in O(m+n) or O(n) time and O(1) Space ? # #When you're done you'll be shown the average runtime your code took to finish all test cases; feel free to include it at the top of your solution ;) # #Collapse 'Test cases' or scroll down to the end of the test cases to see your code's Average runtime # Average runtime: 595 ms def added_char(s1, s2): for i in s2 : if s2.count( i ) - s1.count( i ) == 3 : return i if __name__ == "__main__" : print( added_char( "abcde", "2db2a2ec" ) )
true
edcbb6196c4849ddb5efb2058dbd3d64bb85f2a9
VagrantXD/Stajirovka
/7kyu/specialNumber.py
1,455
4.46875
4
#!/bin/python3 #Definition #A number is a Special Number if it’s digits only consist 0, 1, 2, 3, 4 or 5 # #Task #Given a number determine if it special number or not . # #Warm-up (Highly recommended) #Playing With Numbers Series #Notes #The number passed will be positive (N > 0) . # #All single-digit numbers with in the interval [0:5] are considered as special number. # #Input >> Output Examples #1- specialNumber(2) ==> return "Special!!" #Explanation: #It's a single-digit number within the interval [0:5] . # #2- specialNumber(9) ==> return "NOT!!" #Explanation: #Although ,it's a single-digit number but Outside the interval [0:5] . # #3- specialNumber(23) ==> return "Special!!" #Explanation: #All the number's digits formed from the interval [0:5] digits . # #4- specialNumber(39) ==> return "NOT!!" #Explanation: #Although , there is a digit (3) Within the interval But the second digit is not (Must be ALL The Number's Digits ) . # #5- specialNumber(59) ==> return "NOT!!" #Explanation: #Although , there is a digit (5) Within the interval But the second digit is not (Must be ALL The Number's Digits ) . # #6- specialNumber(513) ==> return "Special!!" #7- specialNumber(709) ==> return "NOT!!" def special_number(number): while number * 10 // 10 != 0 : if not( 0 <= number % 10 <= 5 ) : return "NOT!!" number //= 10 return "Special!!" if __name__ == "__main__" : print( special_number( 123459 ) );
true
eef888c3549fb4c58a96b543133a706e05e2e96e
tze18/AI
/python-training/datatype.py
493
4.25
4
# 資料:程式的基本單位 # 數字 345 # 字串 "測試中文" "hello world" # 布林值 True False # 有順序,可動的列表 list [3,4,6] #有順序,不可動的列表 Tuple (3,4,5) ("hello","world") #集合 Set {3,4,5} {"hello","world"} # 字典 Dictionary {"apple":"蘋果","data":"資料"} #變數:用來儲存資料的自訂名稱 #變數名稱=資料 (變數名稱可以自己決定) x=3 #print(資料) print(x) x=True #取代舊的資料 print(x) x="hello" print (x)
false
1b386bde52a76aa53fe557ea491c71c3e7c2fb2a
SanmatiM/class_problems
/cls_prb3.py
264
4.1875
4
class element: def elenotrep(n): n=int(input("enter number of elements in list")) for i in range(n): lst1.extend(input("Enter input numbers")) for num in lst1: if num not in lst2: lst2.append(num) print(lst2) lst1=[] lst2=[] element.elenotrep(3)
true
65dc7a3f7bb29d1e1187a7010bb51c7ec26c6285
KidCodeIt/Projects
/Python/Lesson-Three/Using_Variables.py
825
4.4375
4
#using variables in if-else statements #The different relational and logic operations # <, <=, >, >=, ==, != num1 = 2; num2 = 3; #Less than if num1 < num2: print "if: num1 is less than num2" else: print "This won't be printed" #Less than or equal to if num1 <= num2: print "if: num1 is less than or equal to num2" else: print "This won't be printed" #Greater than if num1 > num2: print "This won't be printed" else: print "else: num1 is not greater than num2" #Greater than or equal to if num1 >= num2: print "This won't be printed" else: print "else: num1 is not greater than or equal to num2" #Equal too if num1 == num2: print "This won't be printed" else: print "else: num1 is not equal to num2" #Not equal too if num1 != num2: print "if: num1 is not eqaul to num2" else: print "This won't be printed"
true
62a693bb17e53756d200a033dbdde1f845174b72
VictorTruong93/list_exercises_python
/madlibs.py
578
4.1875
4
# # request user to complete a sentence # print("Please fill complete this statement.") # print("(Name) enjoys eating (food)") # # ask user to name character # character_name=input("What is your name? ") # # ask user to specify character's favorite food # character_food=input("What does "+character_name.capitalize()+" enjoy eating? ") # # complete the statement with user choices # print("%s enjoys eating %s." % (character_name.capitalize(), character_food)) def make_madlibs(person, subject): return '%s enjoys eating %s' % (character_name.capitalize(), character_food)
true
3862988a43fdc1933a91bf8861636c3bb9baef1e
5at05h1/excersize
/base5.py
650
4.125
4
from abc import abstractmethod, ABCMeta class Animals(metaclass=ABCMeta): @abstractmethod def speak(self): pass class Dog(Animals): def speak(self): print('わん') class Cat(Animals): def speak(self): print('にゃー') class Sheep(Animals): def speak(self): print('めー') class Other(Animals): def speak(self): print('そんな動物いない') number = input('好きな動物は? 1: 犬、2: 猫、3: 羊') if number == '1': animal = Dog() elif number == '2': animal = Cat() elif number == '3': animal = Sheep() else: animal = Other() animal.speak()
false
d8564359bfe77459d7cad265911cb5ead91e4c39
ArunRamachandran/ThinkPython-Solutions
/Chapter3/3-4.py
1,360
4.15625
4
# A fn. object is a value you can assign to a variable or pass as an argument # 'do_twice' is a fn that take a fn objct as an argument and calls it twice # def print_spam(): print "spam" def do_twice(f): f() f() do_twice(print_spam) # 2.Modify do_twice so that it takes two arguments, a fn objct and a value, # and calls the fn twice, passing the value as an argument. word = raw_input("Enter a word..\n") def print_spam(word): print word def do_twice(f,word): f(word) f(word) do_twice(print_spam,word) #3. Write a grn. version of print_spam, called print_twice, that takes a # a string as a paramtere and print it twice. word = raw_input("Enter a string\n"); def print_twice(word): print word print word print_twice(word) #4. Use the modified version of do_twice to call print_twice, passing 'spam' # as an argument. print "\n" def do_twice(word): print_twice(word) print_twice(word) def print_twice(word): print word s = "hello" do_twice(s) # 5.Define a new fn. called do_four(), that takes a fn object and a value # and calls the fn four times, passing the values as a parameter . There # should be only two statements in the body of this fn, not four obj = raw_input("Give a string .\n") def f(obj): print obj def do_twice(f,obj): f(obj) f(obj) def do_four(f,obj): do_twice(f,obj) do_twice(f,obj) do_four(f,obj)
true
a5ba5bef1c1edc9aa06f3fe87232501307f1a1b2
ArunRamachandran/ThinkPython-Solutions
/Chapter16/16-3.py
652
4.125
4
class Time(object): ''' to represent the time of a day ''' t1 = Time() t2 = Time() t1.h = 4 t1.m = 185 t1.s = 0 t2.h = 1 t2.m = 56 t2.s = 0 def add_time(t1,t2): sum_time = Time() sum_time.h = t1.h + t2.h sum_time.m = t1.m + t2.m sum_time.s = t1.s + t2.s if sum_time.s > 60: val = sum_time.s / 60 sum_time.s -= (60 * val) sum_time.m += val if sum_time.m > 60: val_1 = sum_time.m / 60 sum_time.m -= (60 * val_1) sum_time.h += val_1 print '%.2d:%.2d:%.2d' % (sum_time.h,sum_time.m,sum_time.s) print "t1 ", print '%.2d:%.2d:%.2d' % (t1.h, t1.m, t1.s) print "t2 ", print '%.2d:%.2d:%.2d' % (t2.h, t2.m, t2.s) add_time(t1,t2)
false
f1954e70bcf9909caf7d5a4263c09efb0b4c6dcd
ArunRamachandran/ThinkPython-Solutions
/Chapter17/add_time.py
1,022
4.28125
4
class Time(object): ''' class time to represent time of day ''' def __init__(self,h = 0, m = 0, s = 0): self.h = h self.m = m self.s = s def __str__(self): return '%.2d:%.2d:%.2d' % (self.h,self.m,self.s) def __add__(self,other): if isinstance(other,Time): return self.add_time(other) else: return self.increment(other) def add_time(self,other): self_seconds = self.time_to_int() other_seconds= other.time_to_int() tot = self_seconds + other_seconds return int_to_time(tot) def increment(self,other): seconds = self.time_to_int() + other return int_to_time(seconds) def time_to_int(time): seconds = time.h * 60 * 60 + time.m * 60 + time.s return seconds def __radd__(self,other): return self.__add__(other) def int_to_time(seconds): t = Time() minutes,t.s = divmod(seconds,60) t.h,t.m = divmod(minutes,60) return t time = Time(5,45,30) print time other= Time(4,25,50) print other ''' time = time.add_time(other) print "Added time : ", print time ''' print time + other
false
d859f9bfe8243651fe0dc97563e0ff27a6664f5c
ArunRamachandran/ThinkPython-Solutions
/Chapter6/6-3.py
310
4.125
4
# fn is_between(x,y,z) that returns a True if x<= y <= z or False def is_between(x,y,z): if (y >= x) and (y <= z): return True else: return False x = raw_input("Give x:\n") y = raw_input("Give y:\n") z = raw_input("Give z:\n") case = is_between(x,y,z) if case == True: print True else: print True
false
82ff9a319ba847cef5ffd5e7a95e3d6041927075
ArunRamachandran/ThinkPython-Solutions
/Chapter17/init.py
296
4.21875
4
class Time(object): ''' class time to represent the time of day ''' def __init__(self,h = 0, m = 0, s = 0): self.h = h self.m = m self.s = s def print_time(self): print '%.2d:%.2d:%.2d' % (self.h,self.m,self.s) time = Time() time.print_time() clock= Time(9,45) clock.print_time()
false
e0cd8763ee20b85862fd3c8713c18d7959f5a48e
IreneGabutti/Esercizi-Estivi-Python
/cap9_giochiConLeParole/es_9.4/9.4.py
813
4.25
4
#___Gabutti Irene___ #Scrivete una funzione di nome usa_solo che richieda una parola e una stringa di #lettere, e che restituisca True se la parola contiene solo le lettere indicate. def usa_solo(lettere, parola): verificato = True for lettera in parola: if lettera not in lettere: verificato = False else: verificato = True #verificato = True if verificato: print(f"La parola {parola} contiene tutte le lettere {lettere}") elif verificato == False: print(f"La parola {parola} non contiene tutte le lettere {lettere}") lettere = input("Inserisci una stringa di lettere: ") parola = input("Inserisci la parola: ") print(parola + " " + lettere) usa_solo(lettere, parola)
false
c54105965152a54322c6b16fc10f08b861304b6a
ndragon798/cse231
/Spring 2017/labs/Labs/Lab09/lab09_pre-lab_A.py
744
4.25
4
def display( y ): x = 2 print( "\nIn display, x:", x ) print( "\nIn display, y:", y ) # Here we print out the actual namespace # locals is the generic name of the current namepace # it is a "dictionarly", a data type we will study soon. # We use 'for' to iterate through the whole namespace # and print each item in the namespace. print( "\n\tNamespace for function display:" ) for k,v in locals().items(): print( "{:>10} {}".format( k, v ) ) def main(): x = 6 display( x+2 ) print( "\nIn main, x:", x ) print( "\n\tNamespace for function main:" ) for k,v in locals().items(): print( "{:>10} {}".format( k, v ) ) main()
true
06aa9ec917f0403f67c7c5b31f7fb4e0a0cd4fea
BK-Bagchi/52-Programming-Problems-and-Solutions-with-Python
/Prblm39.py
247
4.375
4
def myFunction(string): return string[::-1] string= input("Enter your string: ") length= len(string) track=0 r_string= myFunction(string) if string== r_string: print("Yes! It is palindrome") else: print("Sorry! It is not palindrome")
true
7544207aecd82808003919ebf1a94f31b184b63b
TahirMia/RusheyProjects
/Lists and iterations Task2.py
266
4.125
4
names=[] print("Please enter 10 names") for i in range (0,9): name = input("Enter the next name: ") names.append(name) print(names) grades=[] for g in range(0,3): grade_one=input("Enter the grade: ") grades.append(grade_one) print(grades)
true
fe3195ace5bee163beea3e6bad214b114b45191e
TahirMia/RusheyProjects
/Car Journey Exercise/Car Jouney Exercise program.py
414
4.28125
4
from decimal import * #Car Journey Exercise length=Decimal(input("What is the length of your journey(Miles)? ")) ##print(length)#+"Miles") miles=Decimal(input("What is the Miles Per Litre of your car? ")) ###print(miles)#+" Miles") petrol=Decimal(input("What is the cost of 1 litre of fuel for your car? ")) ####print(petrol) final=(length/miles)*petrol print (float("{0:.2f}".format(final))) #####
true
5d5a2e07a56182ca80a6239e179627b7557677e5
sudo-julia/utility_calculator
/utility_calculator/misc.py
2,361
4.21875
4
# -*- coding: utf-8 -*- """utilities that would clutter the main file""" import re import sys from typing import Pattern, Tuple, Union def choose(prompt: str, options: Tuple) -> str: """Returns a value that matches a given option from options Args: prompt (str): The prompt to display to the user options (Tuple): A tuple of choices that the user can select from Returns: str: The string selected from 'options' """ while True: option: str = clean_input(prompt) if option in options: return option print("Please choose between: ", *options) def clean_input(prompt: str) -> str: """Returns user input to a prompt, casefolded and stripped of whitespace Args: prompt (str): The prompt to display to the user Returns: str: The user's input to the prompt """ return input(prompt).casefold().strip() def confirm(prompt: str = None) -> bool: """Confirms a choice made by the user Args: prompt (str): The prompt to display to the user (default is None) Returns: bool: True if the user entered 'y' or 'yes', False otherwise """ if not prompt: prompt = "Does this information look correct? [Y/n] " return clean_input(prompt) in ("y", "yes") def get_float(prompt: str) -> float: """Returns user input to a prompt as a float Args: prompt (str): The prompt to display to the user Returns: float: The float input by the user """ while True: try: var: float = float(input(prompt)) return var except ValueError: print("Please enter a valid number!") continue def get_month() -> str: """Asks the user for the month and ensures correct formatting Returns: str: A month of a year, formatted as 'YYYY-MM' """ month_regex: Pattern[str] = re.compile(r"^(?:\d{4}-(?:0[1-9]|1[0-2]))$") while True: month: str = clean_input("Enter the month: ") if re.search(month_regex, month): return month print("Please enter month as 'YYYY-MM' (ex: 2021-10)") def print_error(error: Union[str, Exception]) -> None: """Prints a message to stderr Args: error (str): The error message to print """ print(error, file=sys.stderr)
true
8ebc916533ca720733e65138a35212b0a1e436bc
davesheils/ProgrammingScriptingExercises2018
/exercise6.py
734
4.15625
4
# Please complete the following exercise this week. Write a Python script containing a function called factorial() # that takes a single input/argument which is a positive integer and returns its factorial. # The factorial of a number is that number multiplied by all of the positive numbers less than it. # For example, the factorial of 5 is 5x4x3x2x1 which equals 120. # You should, in your script, test the function by calling it with the values 5, 7, and 10. def factorial(x): result = x for a in range(x-1,1,-1): result = result * a return result print("5! = ",factorial(5)) print("7! = ",factorial(7)) print("10! = ",factorial(10)) # Results checked using scientifict calculator factorial function
true
8b0c6d075d7a3e30d5b522cfbb038ecfc1f57592
jessieengstrom/hackbright-challenges
/rev-string-recursively/reverse.py
711
4.40625
4
"""Reverse a string using recursion. For example:: >>> rev_string("") '' >>> rev_string("a") 'a' >>> rev_string("porcupine") 'enipucrop' """ def rev_string(astring): """Return reverse of string using recursion. You may NOT use the reversed() function! """ return rev(astring, []) def rev(string, reverse): if len(string) == 0: return string elif len(string) == 1: reverse.append(string[0]) else: reverse.append(string[-1]) rev(string[:-1], reverse) return ''.join(reverse) if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. !KROW DOOG\n"
true
670d3b9fa2f5c01e5eab564fd4673e4eadad6aaf
vishalkumarmg1/PreCourse_2
/Exercise_2.py
776
4.15625
4
# Python program for implementation of Quicksort Sort # give you explanation for the approach def partition(arr,low,high): divider = low pivot = high for i in range(low, high): if arr[i]<arr[pivot]: arr[i], arr[divider] = arr[divider], arr[i] divider+=1 arr[pivot], arr[divider] = arr[divider], arr[pivot] return divider # Function to do Quick sort def quickSort(arr,low,high): #write your code here if low<=high: x = partition(arr, low, high) quickSort(arr,low, x-1) quickSort(arr,x+1, high) # Driver code to test above arr = [10, 7, 8, 9, 1, 5] n = len(arr) quickSort(arr,0,n-1) print ("Sorted array is:") for i in range(n): print ("%d" %arr[i])
true
e0025965fad1d3762a9ee0f088a610ec82b0d0fa
Akkiii23/Alphabetical-Patterns
/making D.py
463
4.15625
4
# 1st Way to print D ''' for n in range(7): for m in range(6): if (m==0 or m==5)or((n==0 or n==6)and (m>0)): print("*",end="") else: print(end=" ") print() ''' # 2nd Way to print D for n in range(7): for m in range(6): if (m==0) or(m==5 and (n!=0 and n!=6))or((n==0 or n==6)and (m>0 and m<4)): print("*",end="") else: print(end=" ") print()
false
0c2d4cb3120adc97754be9e56d9658824f836be4
ipiyushbhoi/Data-Structures-and-Algorithm-Problems
/advanced_recursion/string_permutations.py
742
4.125
4
''' Given a string S, find and return all the possible permutations of the input string. Note 1 : The order of permutations is not important. Note 2 : If original string contains duplicate characters, permutations will also be duplicates. Input Format : String S Output Format : All permutations (in different lines) Sample Input : abc Sample Output : abc acb bac bca cab cba ''' def returnPermutations(s): l = [] length = len(s) if length==1: return [s] for i in range(0, length): permutations = returnPermutations(s[0:i]+s[i+1:]) for perm in permutations: l.append(s[i] + perm) return l s = input() permutations = returnPermutations(s) print(*permutations, sep='\n')
true
e8ad5c3a208bba93462c2a4c01442cad1156e239
RahulGusai/data-structures
/python/binaryTrees/completeBTree_Set1.py
1,475
4.15625
4
#! /usr/bin/python3 # Linked List node class ListNode: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # Binary Tree Node structure class BinaryTreeNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None def pushToLL(head,val): newNode = ListNode(val) newNode.next = head head = newNode return newNode def constructBinaryTree(head): queue = [] root = BinaryTreeNode(head.data) queue.append(root) while True: node = queue.pop(0) if head.next is not None: head = head.next newNode = BinaryTreeNode(head.data) queue.append(newNode) node.left = newNode else: break if head.next is not None: head = head.next newNode = BinaryTreeNode(head.data) queue.append(newNode) node.right = newNode else: break return root def printInOrder(root): if root is not None: printInOrder(root.left) print(root.data) printInOrder(root.right) head = None head = pushToLL(head,36) head = pushToLL(head,30) head = pushToLL(head,25) head = pushToLL(head,15) head = pushToLL(head,12) head = pushToLL(head,10) root = constructBinaryTree(head) printInOrder(root)
true
c353f685b57b14f533c3e7acc13cb4614d8e90d2
Constracted/Quadratic-Equation-Solver
/main.py
717
4.28125
4
# This program will calculate the roots of a quadratic equation. def root_one(a, b, c): """This function returns the first root of a quadratic equation.""" return (-b + (b ** 2 - (4 * a * c)) ** 0.5) / (2 * a) def root_two(a, b, c): """This function returns the second root of a quadratic equation.""" return (-b - (b ** 2 - (4 * a * c)) ** 0.5) / (2 * a) a = int(input("Insert the 'a' value: ")) b = int(input("Insert the 'b' value: ")) c = int(input("Insert the 'c' value: ")) print() if (b ** 2 - 4 * a * c) == 0: print("Both roots of the equation are equal to", root_one(a, b, c)) else: print("Root one = ", root_one(a, b, c)) print() print("Root two = ", root_two(a, b, c))
true
b6238e4624d3dc634c55ad18155b9927086dd44a
huangchen1996/Python_Base
/PythonBase/Chapter2_StringList/StringOperation_01.py
1,700
4.15625
4
''' find命令 检测huang是否包含在mystr中,如果是返回开始的初始值,如果不是返回-1 ''' mystr = 'My Name is hc' print(mystr.find("h")) #mystr.find(huang, 0, 17) """ index 也是查询字符串是否在里面,如果不在会报异常 mystr.index(str, start=0, end=len(mystr)) """ print(mystr.index("My", 0, 2)) ''' count 返回字符串在start和end之间在字符串中出现的次数 mystr.count(str, start=0, end=len(mystr)) ''' MyName = "HuangChen" print(MyName.count("n", 0, 9)) ''' replace 把 myName 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次 myName.replace(str1,str2,mystr.count(str1)) ''' myName = "Python Java C" print(myName.replace("C", "Python", 2)) ''' split 以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串 mystr.split(stri=" ", 2) ''' myBook = "This is my favorite book" print(myBook.split(" ", 3)) ''' capitalize 把字符串第一个字符大写 mystr.capitallize() ''' mystring = "nihao" print(mystring.capitalize()) ''' title 把字符串的每个单词的首字母大写 a.title ''' mytitle = "da xiao xie" print(mytitle.title()) ''' startwith 检查字符串是否是以obj开头,是则返回True,否则返回False mystartwith.startswith(obj) ''' mystartwith = "obj是面向对象编程" print(mystartwith.startswith('obj')) ''' endwith 检查字符串是否以obj结束,如果是返回True,否则返回 False. myendwith.endswith('obj') ''' myendwith = "这是obj" print(myendwith.endswith('obj')) ''' lower 转换 mystr 中所有大写字符为小写 mystr.lower() ''' mylower = "ABCDEFGHIJKLMNOPQRST" print(mylower.lower())
false
1888fbb246b267a864d85dc4ebbda1611d0b5ad8
huangchen1996/Python_Base
/Python_Automation/Chapter_01_Basic/Practice_04_VariableAndName.py
1,708
4.15625
4
#变量名帮忙记住程序的内容,变量简单理解就是给一段代码或值取个名字,这个名字就是变量了,在编写代码的时候可以用变量名代指被命名的代码或值 #print()函数以及运算方式的基础上将值命名成为变量后进行运算并打印 #变量命名规则 #变量名只能使用字母、数字、下划线。但不能以数字开头 #变量名不能包含空格,但可以用下划线替代表示 #不要使用 Python 的关键字和函数名作为变量名。( Python 关键字可参考:37.复习各种符号 ) #变量名应该尽力简洁但更应具有具有描述性。 #慎用易混淆的字符,例如小写 l 和大写 O 它们很容易被当作数字。而中文的逗号、引号也容易和英文的混淆。 #汽车100辆 cars = 100 #一辆汽车的空间大小 space_in_a_car = 4.0 #30名司机 drivers = 30 #90个路人 passengers = 90 #不开(闲置)的车辆为汽车总数减去司机人数 cars_not_driven = cars - drivers #汽车司机的人数等于汽车的总数 cars_driven = drivers #一起使用汽车的利用率等于司机人数乘以汽车内部空间 carpool_capacity = cars_driven * space_in_a_car #平均每辆车搭载的游客数为游客数量除以司机人数 average_passengers_per_car = passengers / cars_driven print("这儿有",cars,"cars 是在使用的.") print("这儿只有",drivers,"drivers可以驾驶汽车") print("这儿将会有",cars_not_driven,"cars 是空的,不会被驾驶在今天") print("We can transport",carpool_capacity,"people today") print("We have",passengers,"to carpool today.") print("We need to put about",average_passengers_per_car,"in echo car.")
false
4e5112f0f4d894365f509e862684a18ad0d86fc1
GKliuev/learning_python
/lesson 1/homework/easy1.py
674
4.1875
4
# Задача-1: Дано произвольное целое число (число заранее неизвестно). # Вывести поочередно цифры исходного числа (порядок вывода цифр неважен). # Подсказки: # * постарайтесь решить задачу с применением арифметики и цикла while; # * при желании решите задачу с применением цикла for. number = 9782345 number = str(number) # for index, number in enumerate(number): # print(number) index = 0 while index < len(number): print(number[index]) index += 1
false
011d51ac45defe61a5ca8bc2994429f282aaa01c
MartynaKlos/codewars
/top_3_words.py
1,759
4.40625
4
# Write a function that, given a string of text (possibly with punctuation and line-breaks), returns an array of the top-3 most occurring words, in descending order of the number of occurrences. # Assumptions: # # A word is a string of letters (A to Z) optionally containing one or more apostrophes (') in ASCII. (No need to handle fancy punctuation.) # Matches should be case-insensitive, and the words in the result should be lowercased. # Ties may be broken arbitrarily. # If a text contains fewer than three unique words, then either the top-2 or top-1 words should be returned, or an empty array if a text contains no words. import string def top_3_words(text): list_text = text.split() final_list = [item.split("\n") for item in list_text if item != ' '] result = [item.strip('.').strip(',').lower() for i in final_list for item in i] result_set = set(result) unique_words = list(result_set) for word in unique_words: count = text.count(word) unique_words[unique_words.index(word)] = (word, count) sorted_words = sorted(unique_words, key=lambda x: x[1]) if len(sorted_words) >= 3: most_freq_words = sorted_words[-3:] else: most_freq_words = sorted_words top_3 = [word[0] for word in most_freq_words[::-1]] return top_3 print(top_3_words("""In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income."""))
true
6baf1e466751bdb827ace664442c5c45139b7d48
DionisisSkotidas/Myprojects
/day_10/day_10.py
824
4.125
4
def add(n1, n2): return n1 + n2 def subtract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def divide(n1, n2): return n1 / n2 def calc(prev_res=None): operation = { '+': add, '-': subtract, '*': multiply, '/': divide } if prev_res is None: num1 = int(input('first number')) else: num1 = prev_res num2 = int(input('second number')) for symbol in operation: print(symbol) operation_symbol = input('choose a symbol') calculation_function = operation[operation_symbol] result = calculation_function(num1, num2) print(result) again = input('another one?') if again == 'y': calc(prev_res=result) else: return result calc()
false
057ad46224274a195df517883a121f99d8b4d46e
kevinvervloet/Make1.2.3
/Rekenmachine.py
2,857
4.46875
4
#!/usr/bin/env python """ Een re-make van je rekenmachine die voldoet aan flowcontrol. Je vraagt de gebruiker om 2 getallen Je vraagt de gebruiker om een bewerking op te geven Je geeft correcte output """ # IMPORTS # import time # AUTHOR INFORMATION # # _____ # .' `. # / .-=-. \ \ __ # | ( C\ \ \_.'') # _\ `--' |,' _/ # /__`.____.'__.-' The coding snail~ __author__ = "Kevin Vervloet" __email__ = "kevin.vervloet@student.kdg.be" __Version__ = "(Code version)" __status__ = "Finished" # VARIABLES # # MAIN CODE # def error(): print('this is not a valid number, Please try again') # Print this message if the input was not a number time.sleep(0.5) main() def addition(number_1, number_2): """addition of the two numbers""" print(number_1, "+", number_2, "is", number_1 + number_2) # Do the calculation time.sleep(0.5) again = input("Do you want to calculate again?[yes/no]\n ") # asks the user to calculate again if again == "yes": main() else: print("Goodbye") def subtraction(number_1, number_2): """subtraction of the two numbers""" print(number_1, "-", number_2, "is", number_1 - number_2) time.sleep(0.5) again = input("Do you want to calculate again?[yes/no]\n ") if again == "yes": main() else: print("Goodbye") def multiplication(number_1, number_2): """multiplication of the two numbers""" print(number_1, "*", number_2, "is", number_1 * number_2) time.sleep(0.5) again = input("Do you want to calculate again?[yes/no]\n ") if again == "yes": main() else: print("Goodbye") def division(number_1, number_2): """division of the two numbers""" print(number_1, "/", number_2, "is", number_1 / number_2) time.sleep(0.5) again = input("Do you want to calculate again?[yes/no]\n ") if again == "yes": main() else: print("Goodbye") def main(): try: number_1 = int(input("Pick a number: ")) # Input, pick your first number number_2 = int(input("Pick another number: ")) # Input, it lets you pick a second number what = input('''What would you like to do? + for addition - for subtraction * for multiplication / for division ''') if what == "+": addition(number_1, number_2) elif what == '-': subtraction(number_1, number_2) elif what == '*': multiplication(number_1, number_2) elif what == '/': division(number_1, number_2) except ValueError: error() if __name__ == '__main__': # run tests if called from command-line main()
false
fc92e34f107f17f3a609f874e6741865deebaca1
nguyenmanhtrung/trungza1
/nguyenmanhtrung_44617_ca18a1a-cp4/nguyenmanhtrung_44617_ca18a1a/project1/project_09_page_132.py
912
4.21875
4
""" Author: Nguyễn Manh Trung Date: 24/09/2021 Problem:Write a script named numberlines.py. This script creates a program listing from a source program. This script should prompt the user for the names of two files. The input filename could be the name of the script itself, but be careful to use a different output filename! The script copies the lines of text from the input file to the output file, numbering each line as it goes. The line numbers should be right-justified in 4 columns, so that the format of a line in the output file looks like this example: 1> This is the first line of text. Solution: .... """ input_filename = input('Nhập file đầu vào: ') output_filename = input('Nhập file đầu ra: ') with open(input_filename, 'r') as f, open(output_filename, 'w') as w: number = 0 for line in f: number += 1 w.write('{:>4}> {}'.format(number, line))
true
28c19c69d1454176ed834d386a1083a1526454e6
nguyenmanhtrung/trungza1
/Nguyenmanhtrung_44617_cp7/Nguyenmanhtrung_44617/Exercises/page_218_exercise_06.py
509
4.53125
5
""" Author: nguyễn manh trung Date: 16/10/2021 Problem: The Turtle class includes a method named circle. Import the Turtle class, run help(Turtle.circle), and study the documentation. Then use this method to draw a filled circle and a half moon. Solution: .... """ import turtle # Initializing the turtle t = turtle.Turtle() r = 50 t.circle(r) turtle.Screen() turtle.bgcolor("magenta") turtle.color("red") turtle.begin_fill() turtle.circle(130, 180) turtle.end_fill() turtle.hideturtle()
true
7d1f79f08afcbf423ef06aa1264afbf610d6dd08
nguyenmanhtrung/trungza1
/nguyenmanhtrung_44617_ca18a1a-cp4/nguyenmanhtrung_44617_ca18a1a/excercise/page_118_exercise_01.py
599
4.375
4
""" Author: Nguyễn Manh Trung Date: 24/09/2021 Problem: Assume that the variable data refers to the string "Python rules!". Use a string method from Table 4-2 to perform the following tasks: a. Obtain a list of the words in the string. b. Convert the string to uppercase. c. Locate the position of the string "rules". d. Replace the exclamation point with a question mark. Solution: >> data = "Python rules!" # câu a >> len(data) 13 # câu b >> data.upper() 'PYTHON RULES!' # câu c >> data[7:12] 'rules' # câu d >> data.replace('!', '?') 'Python rules?' .... """
true
840f14e9c48726caaf7793f6e94dfd207c84100b
nguyenmanhtrung/trungza1
/Nguyenmanhtrung_44617_cp7/Nguyenmanhtrung_44617/Exercises/page_237_exercise_05.py
605
4.3125
4
""" Author: nguyễn manh trung Date: 16/10/2021 Problem:How would a column-major traversal of a grid work? Write a code segment that prints the positions visited by a column-major traversal of a 2-by-3 grid. Solution: A nested loop structure to traverse a grid consists of two loops, an outer one and an inner one. Each loop has a different loop control variable. The outer loop iterates over one coordinate, while the inner loop iterates over the other coordinate. .... """ width = 2 height = 3 for y in range(height): for x in range(width): print((x, y), end = " ") print()
true
32ff46f1bd054b7a46fc079e9e8ee4ddd68d235e
nguyenmanhtrung/trungza1
/nguyenmanhtrung_44617_cp5/nguyenmanhtrung_44617_cp5/Projects/page_165_project_08.py
766
4.15625
4
""" Author:Nguyễn Mạnh Trung Date: 11/10/2021 Problem: A file concordance tracks the unique words in a file and their frequencies. Write a program that displays a concordance for a file. The program should output the unique words and their frequencies in alphabetical order. Variations are to track sequences of two words and their frequencies, or n words and their frequencies Solution: ... """ import re import string fre={} document_text = open('test.txt','r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b [a-z]{1-15} \b',text_string) for word in match_pattern: count = fre.get(word,0) fre[word]=count+1 fre_list = fre.keys() for words in sorted(fre_list): print(words,fre[words])
true
de708d9bb7a43883f9ed73ad2dc91b93023d9ccf
Berea-College-CSC-226/a03-spring-2021
/A03_Kharela.py
2,312
4.4375
4
# Author: Anish Kharel # Username: Kharela # Assignment: A03: robotic turtle import turtle def make_base(): """This functions main purpose is to draw the base layout in which the phone will build off of""" base = turtle.Turtle() base.hideturtle() base.penup() base.pensize(3) base.forward(-150) base.left(90) base.forward(200) base.right(180) base.pendown() for i in range(2): base.forward(450) base.left(90) base.forward(235) base.left(90) def make_additions(): """THis functions purpose is to implement the bezels and camera and homebutton""" homeb = turtle.Turtle() #make the bottom bezel of the phone homeb.hideturtle() homeb.penup() homeb.forward(-140) homeb.right(180) homeb.forward(10) homeb.left(90) homeb.forward(205) homeb.left(90) homeb.pendown() homeb.pensize(2) homeb.forward(235) homeb.penup() #make the home button homeb.forward(-118) homeb.right(90) homeb.forward(25) homeb.pendown() homeb.circle(10) homeb.penup() #making the top bezel homeb.left(180) homeb.forward(390) homeb.left(90) homeb.forward(118) homeb.left(180) homeb.pendown() homeb.forward(235) homeb.penup() #making the camera and sesor homeb.forward(-140) homeb.left(90) homeb.forward(25) homeb.right(90) homeb.pensize(4) homeb.pendown() homeb.forward(25) homeb.penup() homeb.pensize(2) homeb.forward(15) homeb.pendown() homeb.circle(5) def make_apps(amount): """ This functions purpose is to construct the apps that will fill the iphone screen""" app = turtle.Turtle() app.hideturtle() app.penup() app.forward(-135) app.left(90) app.forward(145) app.right(90) app.pendown() for i in range(amount): app.pendown() for i in range(4): app.forward(40) app.right(90) app.penup() app.forward(50) def main(): """Main function which will call everything else and put it together""" wn = turtle.Screen() wn.bgcolor("light blue") make_base() make_additions() make_apps(3) wn.mainloop() main();
false
2230e5a682d642073894a5f5be96bfc840b2928e
seelander09/PythonWork
/Scores/scoresGrades.py
815
4.25
4
# # Write a function that generates ten scores between 60 and 100. # Each time a score is generated, your function should display what # the grade is for a particular score. Here is the grade table: # # # Score: 60 - 69; Grade - D # Score: 70 - 79; Grade - C # Score: 80 - 89; Grade - B # Score: 90 - 100; Grade - A import random def scoresAndGrades(): for value in range(0,10): randNum = random.randint(60,100) if randNum >= 90: print ("Score: {}; Your grade is A".format(randNum)) elif randNum >= 80: print ("Score: {}; Your grade is B".format(randNum)) elif randNum >= 70: print ("Score: {}; Your grade is C".format(randNum)) elif randNum >= 60: print ("Score: {}; Your grade is D".format(randNum)) scoresAndGrades()
true
edf53b758cde452219a1de64c8efe63bf5ffdb16
2023PHOENIX/Hackerrank-Python
/String_split_and_join.py
332
4.28125
4
S = input() """ In Python, a string can be split on a delimiter. Example: >>> a = "this is a string" >>> a = a.split(" ") # a is converted to a list of strings. >>> print a ['this', 'is', 'a', 'string'] Joining a string is simple: >>> a = "-".join(a) >>> print a this-is-a-string """ S = S.split(" ") Z = "-".join(S) print(Z)
true
e3cf726e6657a1a578317dbf474ce06a340a287d
Shubhampy-code/Data_Structure_Codes
/Array_Codes/SmallestNum_largestNum_num.py
480
4.125
4
#find largest and smallest number in the array. from array import* my_array = array("i",[56562,2222,563,2,65555,926,347,32,659,6181,9722,4533,1244,505,7566,9577,88]) i=0 largest_num = my_array[i] small_num = my_array[i] while i < len(my_array): if my_array[i]>=largest_num: largest_num = my_array[i] elif my_array[i]<=small_num: small_num = my_array[i] i=i+1 print("largest number = " + str(largest_num)) print("smallest number = " + str(small_num))
true
d3e48d569191df1bced6213e15647091350e509f
Shubhampy-code/Data_Structure_Codes
/Array_Codes/Count_odd_even_element.py
415
4.1875
4
# how many odd and how many even number present in array. from array import* my_array = array('i',[4,5,6,7,8,9,3,3,3,3,3,3,3,1,2]) i=0 found = 0 odd=0 even = 0 while i < len(my_array): if ((my_array[i])%2==0): even = even + 1 elif ((my_array[i])%2 != 0): odd = odd + 1 i=i+1 print("Odd number present in array is : " + str(odd)) print("Even number present in array is : " + str(even))
true
2bdebc1bd62f82252b5ed68cd7f1f1b1f80d01b7
Elena-May/MIT-Problem-Sets
/ps4/ps4a.py
2,366
4.28125
4
# Problem Set 4A # Name: <your name here> # Collaborators: # Time Spent: x:xx import random def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all permutations of sequence Example: >>> get_permutations('abc') ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] Note: depending on your implementation, you may return the permutations in a different order than what is listed here. base case = if the sequence is a single character ''' # if sequence is a single character if len(sequence) == 1: # return list containing 'sequence' sequence_result = list(sequence) return sequence_result # creating a method that gives a sequence of all permutations except the first character (recursion) #else: permutations = [] #make a permutation loop #starting to work... don't understand how # for a sequence of everything but the first character # why does it print c and not b to start with for p in get_permutations(sequence[1:]): print ('This is p:',p) # adds an empty space to p (+1) # starting with the first character in the sequence for i in range(len(p) + 1): # everything before and not including i + the first character in the sequence + everything after and including i permutations.append(p[:i] + sequence[:1] + p[i:]) return permutations # [:i] - means end the sequence with i # need it to unbuild the sequence till it gets to one and then keep adding them back in again # so remove the first character, if __name__ == '__main__': # #EXAMPLE example_input = 'abc' print('Input:', example_input) print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']) print('Actual Output:', get_permutations(example_input)) # # Put three example test cases here (for your sanity, limit your inputs # to be three characters or fewer as you will have n! permutations for a pass #delete this line and replace with your code here
true
aef2a8bc567764bc3b9ea89990d75e76e27d3cf7
hsharma267/python_programs-with-w3school
/Pythn_NumPy/numpy_data_type.py
1,115
4.28125
4
# Data Types in NumPy import numpy as np print("<-- Data Types in Numpy -->") """ 1.) i-> integer 2.) b-> boolean 3.) u-> unsigned integer 4.) f-> float 5.) c-> complex float 6.) m-> timedelta 7.) M-> datetime 8.) O-> Object 9.) S-> String 10.) U-> unicode string 11.) V-> fixed chunk of memory for other type(void) """ # checking the Data Type of an array:- print("<-- Checking Data Type of an array -->") arr = np.array([1, 2, 3, 4, 5, 6, 7]) print(arr.dtype) arr1 = np.array(['apple', 'banana', 'cherry']) print(arr1.dtype) arr2 = np.array([1, 2, 3, 4, 5], dtype="S") print(arr2) print(arr2.dtype) myarr = np.array([1, 2, 3, 4], dtype='i4') print(myarr) print(myarr.dtype) # Converting data type on existing array print("<-- converting data type on existing array -->") arr3 = np.array([1.1, 2.2, 3.2, 4.5]) newarr = arr3.astype("i") print(newarr) print(newarr.dtype) newarr1 = arr3.astype("int") print(newarr1) print(newarr1.dtype) arr4 = np.array([1, 0, 3, 0, 5]) newarr3 = arr4.astype("bool") print(newarr3) print(newarr3.dtype)
true
5c0d4da1c73e6f5a08e445e9c84f0ad3d33cfd04
hsharma267/python_programs-with-w3school
/Pythn_NumPy/numpy_random.py
1,023
4.3125
4
# Numpy Random from numpy import random as rand print("<-- Numpy Random -->") """ Random Introduction:- Random number does not mean different number everytime. Random means something that cannot be predicted logically. """ # Generate Random Number print("-- Generate Random Number --") x = rand.randint(100) print(x) print("-- Another example --") x = rand.randint(100, size=(3)) print(x) print("-- Another example 2 --") x = rand.randint(100, size=(3, 5)) print(x) # Generate Random Float print("-- Generate Random Float --") y = rand.rand() print(y) print("-- Another Example --") y = rand.rand(3) print(y) print("-- Another Example2 --") y = rand.rand(3, 5) print(y) # Generate Random Number From Array print("-- Generate Random Number From Array --") z = rand.choice([13, 5, 6, 7, 56, 5]) print(z) print("-- Another Example --") z = rand.choice([13, 5, 6, 7, 56, 5], size=(3)) print(z) print("-- Another Example2 --") z = rand.choice([13, 5, 6, 7, 56, 5], size=(3, 5)) print(z)
false
d0c615256540f0c7294066e4ebc8f1956710057b
hsharma267/python_programs-with-w3school
/Pythn_ tutorial/py_fileHandling.py
2,079
4.40625
4
# File Handling """ # Python File Open # File handling is an important part of any web application. # Python has several function for creating,reading,updating,and deleting files. # File Handling # There are several different methods(modes) for opening a file:- # 1. "r" - Default value. Open a file for reading,error if the file does not exist # 2. "a" - Open a file for appending,creates the file if it does not exist # 3. "w" - Open a file for writing,creates the file if it does not exist # 4. "x" - Create the specified file, returns an error if the file exist # 5. "t" - Default value. Text mode # 6. "b" - Binary mode (eg:-images) """ # Python File Open print("-- Python File Open --") f = open("demofile.txt", "r") print(f.read()) # Read Only Parts of file print("-- Read Only Parts of file --") f = open("demofile.txt", "r") print(f.read(10)) # Read Lines print("-- Readline method --") f = open("demofile.txt", "r") print(f.readline()) print("-- Readlines method --") f = open("demofile.txt", "r") print(f.readlines()) # file close print("-- file close --") f = open("demofile.txt", "r") print(f.readline()) f.close() # Python File write """ # 1.) "a" - Append - will append to the end of the file. # 2.) "w" - Write - will overwrite any existing contect. """ print("-- Append method --") f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() f = open("demofile2.txt", "r") print(f.read()) f.close() print("-- write method --") f = open("demofile3.txt", "a") f.write("Woops! I have deleted the content!") f.close() f = open("demofile3.txt", "r") print(f.read()) f.close() # Create a New File """ # "x" - will create a file,return an error if the file exist. # "a" - will create a file if the specified file does not exist. # "w" - will create a file if the specified file does not exist. """ print("-- Create a new file --") f = open("demo.txt", "x") f.close() f = open("demo.txt", "w") f.write("My name is Harish Kumar. I am 28 years old.") f.close() f = open("demo.txt", "r") print(f.read()) f.close()
true
94527ee978a23656af0f74d3bad36a65f5c93fd7
hsharma267/python_programs-with-w3school
/Pythn_NumPy/numpy_array_sorting.py
594
4.28125
4
# Numpy Sorting Arrays import numpy as np print("<-- NumPy Sorting Arrays -->") # Sorting Arrays print("-- Sorting Arrays --") arr = np.array([3, 2, 0, 4, 8, 6, 7, 1]) print(np.sort(arr)) # Another Example print("-- Another Example --") arr1 = np.array(['orange', 'cherry', 'lemon', 'mango', 'strawberry', 'banana', 'peech', 'apple']) print(np.sort(arr1)) # Another Example1 print("-- Another Example1 --") arr2 = np.array([True, False, True]) print(np.sort(arr2)) # Sorting 2-D Arrays print("-- Sorting 2-D Arrays --") arr3 = np.array([[3, 9, 2], [8, 4, 6]]) print(arr3)
false
bf0ed3a6ac93ed4748afd401cbc8aca715f499ac
AMao7/Project_Mr_Miyagi
/Mr_Miyagi.py
663
4.15625
4
while True: question = (input("what is your question sir ")).strip().lower() print("questions are wise, but for now. Wax on, and Wax off!") if "sensei" not in question: print("You are smart, but not wise, address me as sensei please") elif "block" or "blocking:" in question: print("Rememeber, best block, not to be there") elif "sensei im at peace" in question: print('Sometimes, what heart know, head forget') elif "sensei" or "block" or "blocking" or "sensei im at peace" not in question: print("do not lose focus. Wax on. Wax off") else: print("do not lose focus. Wax on. Wax off.")
true