blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
518595859e4b53609f08686d9cf80855b78b2f6b
portmannp/ICB_EX7
/Ex07Portmann.py
2,330
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 23 19:42:38 2018 Exercise 7: Patricia Portmann @author: Patricia """ import pandas # function that takes in the full dataframe argument # and returns only the odd numbered rows stored in a dataframe def OddRows(dataframe): OddDF = dataframe.iloc[1::2] # only puts odd numbered rows into OddDF dataframe return OddDF # function returns odd rows # function that takes in dataframe and species name argument # and returns the count for the specific species def NumObs(dataframe,species): count=0 # count initialized to 0 totalrows=dataframe.shape[0] # finds length of df for x in range(totalrows): # conditional that matches the 4th column to specified species if dataframe.iloc[x,4] == species: count += 1 return count # function that takes in dataframe and specified width limit # and returns a dataframe only with the row that are greater than the width limit def SepWidth(df, width_limit): return(df.loc[df['Sepal.Width']>width_limit]) # function that takes in dataframe and specified species # and makes a .csv file for the species with format "speciesname.csv" def toCSV(df,species): specific_df=df.loc[df['Species']==species] filename = "%s.csv" %species specific_df.to_csv(filename,header=True,index=False,sep=",") # main body code data=pandas.read_csv("iris.csv") # data loaded into a data frame # calls for function OddRows OddDF = OddRows(data) # print(OddDF) # calls for function NumObs species = raw_input("What species are you counting? ") number_observations = 0 if species == "setosa" or species == "versicolor" or species == "virginica": number_observations = NumObs(data,species) print(species, "has: ", number_observations, "observations") else: print("invalid species name") # ask for user input limit = float(input("Type sepal width: ")) # save user input as float variable limit # calls for function to return a dataframe w/ Sepal.Width greater than limit Sepal_Width_df = SepWidth(data,limit) print(Sepal_Width_df) sp_csv = raw_input("What species are you making a .csv file for? ") if species == "setosa" or species == "versicolor" or species == "virginica": toCSV(data,sp_csv) print(".csv file for:", sp_csv, "made.") else: print("invalid species name.")
true
ad373b929992a657e9bab74054da174144df867c
viswan29/Leetcode
/Array/reverse_pair.py
2,081
4.21875
4
''' https://leetcode.com/problems/reverse-pairs/ Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j]. You need to return the number of important reverse pairs in the given array. Example1: Input: [1,3,2,3,1] Output: 2 Example2: Input: [2,4,3,5,1] Output: 3 ''' # Use inversion count # Calculate separately the results for ranges [start,mid] and [mid+1,end] using recursion # Count elements in [start,mid] that are greater than 2 * elements in [mid+1,end] and add in result class Solution: def merge(self, s, e, mid, temp, nums): count = 0 j = mid+1 for i in range(s, mid+1): # count for each element while j <= e and nums[i] > 2*nums[j]: # find all elements in second half which is smaller j += 1 count += (j-(mid+1)) i = s j = mid+1 k = s while i <= mid and j <= e: if nums[i] <= nums[j]: temp[k] = nums[i] i += 1 k += 1 else: temp[k] = nums[j] j += 1 k += 1 while i <= mid: temp[k] = nums[i] i += 1 k += 1 while j <= e: temp[k] = nums[j] j += 1 k += 1 for i in range(s, e+1): nums[i] = temp[i] return count def mergesort(self, s, e, nums, temp): count = 0 if s < e: mid = (s+e)//2 count += self.mergesort(s, mid, nums, temp) count += self.mergesort(mid+1, e, nums, temp) count += self.merge(s, e, mid, temp, nums) #nums[s: e + 1] = sorted(nums[s: e + 1]) return count def reversePairs(self, nums: List[int]): n = len(nums) temp = [0]*n count = self.mergesort(0, n-1, nums, temp) return count
true
73f7e3b0b08fb51477eb248cf96da164d2b8eb4d
kgvconsulting/PythonDEV
/dayOfTheWeek.py
1,086
4.1875
4
# Created by Krasimir Vatchinsky - KGV Consulting Corp - info@kgvconsultingcorp.com # Program for user entry number 1-7 and display corresponding day of the week # seting a dictionary for days of the week and coresponding number weekDays = {1 :'Monday',2 :'Tuesday',3 :'Wednesday',4 :'Tursday',5 :'Friday',6 :'Saturday',7 :'Sunday'} # set the try/except/else method for eliminating/catching user input format errors try: # user input of day of the week as number and integer userDayInput = int(input('Enter day of the week from 1 to 7 in numerical format: ')) # boolean for defining the comparancement of user entry number with day of the week if userDayInput in weekDays: print("Your input number corespond to: ", weekDays[userDayInput]) # boolean raising error if user input number is not from range 1 to 7 else: print("You didn't enter number between 1 and 7. Please try again!") # exception to report an error in case user input is not in numerical format except Exception as e: print("Oops, something went wrong. Please enter only numerical format, from 1 to 7!")
true
ee45053f24aed181a69ec0cd9a3f22a7b94df853
kgvconsulting/PythonDEV
/finalGradesConverter1.py
1,632
4.125
4
# Created by Krasimir Vatchinsky - KGV Consulting Corp - info@kgvconsultingcorp.com # Program to help to convert user inputed grade numbers from 1 to 100 into letter grades, # def function to convert user input grades to letter grades def gradeScore(score): if score >= 93 and score <= 100: print("Your grade is : A") elif score >=90 and score <= 92: print("Your grade is : A-") elif score >= 87 and score <= 89: print("Your grade is : B+") elif score >= 83 and score <= 86: print("Your grade is : B") elif score >= 80 and score <= 82: print("Your grade is : B-") elif score >= 77 and score <= 79: print("Your grade is : C+") elif score >= 73 and score <= 76: print("Your grade is : C") elif score >= 70 and score <= 72: print("Your grade is : C-") elif score >= 67 and score <= 69: print("Your grade is : D+") elif score >= 63 and score <= 66: print("Your grade is : D") elif score >= 60 and score <= 62: print("Your grade is : D-") elif score >= 0 and score <=59: print("Your grade is : E") else: print("You didn't enter the number between 1 and 100, Please try again") return score # try/except to catch user non numerical format input try: # user input userGradeInput = int(input('Enter an grade number from 1 to 100 only in numerical format: ')) # calling the predefined functon gradeScore() output = gradeScore(userGradeInput) # exception if user input is not numericla format except Exception as e: print("Oops, something went wrong. Please enter only numerical format")
true
da82339ef8ccceda7c06ab7cffc98dbe34fe2368
kgvconsulting/PythonDEV
/costCubicFoot.py
690
4.25
4
# Created by Krasimir Vatchinsky - KGV Consulting Corp - info@kgvconsultingcorp.com # This program will calculate cost of water per cubic foot in a pool from math import * # assign the height of the pool poolHeight = 4 # accept user input for diameter and total cost of the water userPoolDiameter = float(input('Enter the diameter of the pool in numerical format: ')) userWaterCost = float(input('Enter the total cost of the water in numerical format: ')) # calculate the volume of the pool volumePool = (pi * ((userPoolDiameter/2)**2 * poolHeight)) # calculate the total cost per cubic feet totalCost = userWaterCost / volumePool # print the final result print("Cost per cubic feet is: ", format(totalCost, '.3f'))
true
4d3c841b4992796c3b2a81301db701888e06ad0d
alex-sa-ur/python-bte499
/bte499.hw3.alejandrosanchezuribe/bte499.hw3.p1.q4.alejandrosanchezuribe.py
734
4.40625
4
""" Author: Alejandro Sanchez Uribe Date: 29 January 2019 Class: BTE 499 Assignment: Assignment 3 - Part 1 - Question 4 """ import string # Input: phrase from the user # Process: remove punctuation and whitespace, # lowercase all letters, # evaluate for palindrome # Output: Evaluation as a palindrome (yes or no) phrase = input('Input a phrase for palindrome evaluation: ') phrase = ''.join(phrase.translate(str.maketrans('', '', string.punctuation)).lower().strip().split()) backwards = "".join(reversed(phrase)) print('\nEvaluation: {} == {} ?\n'.format(phrase, backwards)) if phrase == backwards: print('This phrase is a palindrome!') exit() print('This phrase is not a palindrome')
true
6519ff3850b3f6f40d47f601b17dfd5453d9ae0b
praveenrwl/ML-in-Python
/n1_Intro of Numpy Array.py
1,594
4.15625
4
#About Numpy '''Python library is a collection of functions and methods that allows you to perfrom many actions without writing of codes''' '''NUMPY stands for NUMERICAL PYTHON and is the core library for numeric and scientific computing ''' '''It consists of multi dimensional array objects and a collection of routines for processing those arrays ''' # Single Dimensional Array import numpy as np n1 = np.array([10,20,30,40,50]) print("#1 Single Dimensional Array :\n ", n1) print(type(n1), "\n") # Multi Dimensional Array import numpy as np n2 = np.array([[1,2,3,4,5],[11,12,13,14,15]]) print("#2 Multi Dimensional Array :\n", n2) # Initializing NumPy array with zeroes : # 1 import numpy as np n3 = np.zeros((1,2)) print("\n#3 Initializing NumPy array with zeroes :\n #A\n", n3) # 2 n4 = np.zeros((5,5)) print("\n #B\n", n4) # Initializing NumPy array with same number : # Will make matrix >> n5 = np.full((3,3),10) print("\n#4 Initializing NumPy array with zeroes :\n", n5) # Initializing NumPy array within a range : n6 = np.arange(11,21) print("\n#5 Initializing NumPy array within a range :\n", n6) n7 = np.arange(10,51,5) print("\n#6 Initializing NumPy array within a range :\n", n7) # Initializing NumPy array with random numbers : n8 = np.random.randint(1,100,5) print("\n#7 Initializing NumPy array with random numbers :\n", n8) # Check the shape of NumPy arrays : n9 = np.array([[1,2,3],[4,5,6]]) print("\n#8 Check the shape of NumPy arrays:\n #A\n", n9) n9.shape print("\n #B\n", n9) n9.shape = (3,2) print("\n #C\n", n9)
true
88a95b2005f578d81fb615007d81f29098566928
rrybar/pyCourseScripts
/idea/AdvPythonDemos/Chap05/Classes.py
815
4.21875
4
class MyClass(object): classVar = 42 def __init__(self, x, y): self.x = x self.y = y MyClass.z = 96 def method1(self): pass def method2(self): self.method1() print(MyClass) print(dir(MyClass)) # create an instance mc = MyClass(1, 2) print(mc, "__class__", mc.__class__) # the following is interesting. Is z an instance attribute? What about classVar? print("Instance:\n", dir(mc)) # let's look at what's inside the class object proper print("Class:\n", dir(MyClass)) print() # access the vars using the instance only print("Before: x {}, y {}, z {}, classVar {}".format(mc.x, mc.y, mc.z, mc.classVar)) # now hide z mc.z = 3 # really setattr(mc, 'z', 3) print('After: x {}, y {}, z {}, MyClass.z {}'.format(mc.x, mc.y, mc.z, MyClass.z))
false
b4a10d61895df532738b42d7fa61aa2f80708425
dhanraju/python
/practise/programs/class_inside_another_class.py
1,220
4.6875
5
"""This program demonstrates class inside another class.""" class Human(object): # value = None def __init__(self, some_val): # self.value = 5 self.name = 'Dhan' self.__class__.value = some_val self.head = self.Head(self.value) self.brain = self.Brain(self.value) # Declaring a class variable in instance method. self.__class__.value = some_val @classmethod def print_message(cls, arg_value): print("class value = %d" % cls.value) print("print(message arg_value = %d" % arg_value) class Head(object): def __init__(self, value): self.value = value def talk(self): return 'talking... %d' % self.value class Brain(object): def __init__(self, value): self.value = value def think(self): Human.print_message(10) return 'thinking... %d' % self.value if __name__ == '__main__': dhan = Human(2) print(dhan.name) print(dhan.head.talk()) print(dhan.brain.think()) # Ref: https://pythonspot.com/inner-classes/ ''' Notes: The usecase is - the inner class never be used outside the definition of the outer class. '''
true
883082f6461a1aadd7e8bedb72c4fd77f3cd6ee4
dhanraju/python
/hr_practise/basic_data_types/list_comps.py
1,221
4.5625
5
"""List comprehensions. Let's learn about list comprehensions! You are given three integers x, y and z representing the dimensions of a cuboid along with an integer 'n'. Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n. Here, 0 <= i <= x; 0 <= j <= y; 0 <= k <= z. Please use list comprehensions rather than multiple loops, as a learning exercise. Example x = 1 y = 1 z = 2 All permutations of [i,j,k] are: [ [0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2] ] Print an array of the elements that do not sum to n = 3. [ [0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 2] ] """ def get_possible_coordinates(x, y, z, n): """Generates possible coordinates and returns them.""" matrix = [ [i, j, k] for i in range(x + 1) for j in range(y + 1) for k in range(z + 1) if i + j + k != n ] return matrix if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) print(get_possible_coordinates(x, y, z, n))
true
8f084dd1fb3320e2bdc92a396664b146fb9b5cb1
dhanraju/python
/data_structures/probl_sol_with_algs_and_ds/ch03_basic_ds/paranthesis_checker.py
1,618
4.125
4
"""Paranthesis checker.""" from stack import Stack def paranthesis_checker(symbol_string): """Paranthesis checker.""" s = Stack() is_balanced = True index = 0 # Navigate character by character through the symbol_string. while index < len(symbol_string) and is_balanced: symbol = symbol_string[index] # Push the open paranthesis into the stack if symbol in "([{": s.push(symbol) elif symbol in ")]}": # Pop the corresponding open paranthesis for the close paranthesis. if s.is_empty(): is_balanced = False else: top = s.pop() # Make sure the most recent parenthesis matches the next close # symbol. If no open symbol on the stack to match a close # symbol, the string is not balanced. if not matches(top, symbol): is_balanced = False index = index + 1 # When all the symbols are processed, the stack should be empty for a balanced # paranthesis. Othewise, the paranthesis in the given string is not balanced. if is_balanced and s.is_empty(): return True return False def matches(open_paran, close_paran): """Checks the close paranthesis matches with the open paranthesis.""" opens = "([{" closes = ")]}" return opens.index(open_paran) == closes.index(close_paran) if __name__ == '__main__': st = '{{([][])}()}' print(f'Is {st} balanced?', paranthesis_checker(st)) st = '[{()]' print(f'Is {st} balanced?', paranthesis_checker(st))
true
ab49a7d236355d398a107d1be5bb2dba602da05b
dhanraju/python
/data_structures/py3MOTW/collections/ordereddict/collections_ordereddict_iter.py
794
4.15625
4
""" An OrderedDict is a dictionary subclass that rememebers the order in which its contents are added. """ import collections print('Regular dictionary:') d = {} d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' for k, v in d.items(): print(k, v) print('OrderedDict:') d = collections.OrderedDict() d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' for k, v in d.items(): print(k, v) ''' Notes: A regular dict does not track the insertion order, and iterating over it produces the values based on how the keys are stored in the hash table, which is in turn influenced by a random value to reduce collisions. In an OrderdDict, by contrast, the order in which the items are inserted is remembered and used when creating an iterator. ''' ''' OUTPUT: Regular dictionary: a A b B c C OrderedDict: a A b B c C '''
true
0dee1995b6ce993e9e337fa9d4da8145156d6d15
dhanraju/python
/data_structures/probl_sol_with_algs_and_ds/ch05_sorting_searching/binary_search_recursive.py
817
4.1875
4
"""Binary search in recursive way.""" def binary_search_recursive(given_list, item): if len(given_list) == 0: return False else: midpoint = len(given_list) // 2 if given_list[midpoint] == item: return True elif item < given_list[midpoint]: return binary_search_recursive(given_list[:midpoint], item) else: return binary_search_recursive(given_list[midpoint + 1:], item) if __name__ == "__main__": GIVEN_LIST = [0, 1, 2, 8, 13, 17, 19, 32, 42] ITEM1 = 3 print(f'Is the item {ITEM1} present in the given list {GIVEN_LIST} ?', binary_search_recursive(GIVEN_LIST, ITEM1)) ITEM2 = 13 print(f'Is the item {ITEM2} present in the given list {GIVEN_LIST} ?', binary_search_recursive(GIVEN_LIST, ITEM2))
false
8e5d0a34919d67fa0b258a7135ff62540a52a347
dhanraju/python
/algorithms/searching/searching_algs.py
1,545
4.15625
4
'''Searching techniques.''' class SearchingAlgs(object): '''Class that performs searching techniques on given data.''' def unorderedSequentialSearch(self, alist, item): '''Search an item using sequential/linear search technique .''' pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos = pos+1 return found def orderedSequentialSearch(self, alist, item): '''Search an item in an ordered list using sequential search technique.''' pos = 0 found = False stop = False while pos < len(alist) and not found and not stop: if alist[pos] == item: found = True else: if alist[pos] > item: stop = True else: pos = pos+1 return found if __name__ == '__main__': unordered_testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0] SEARCHING_ALG_OBJ = SearchingAlgs() # Negative test case. print(SEARCHING_ALG_OBJ.unorderedSequentialSearch(unordered_testlist, 3)) # Positive test case. print(SEARCHING_ALG_OBJ.unorderedSequentialSearch(unordered_testlist, 13)) ordered_testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42] # Negative test case. print(SEARCHING_ALG_OBJ.orderedSequentialSearch(ordered_testlist, 3)) # Positive test case. print(SEARCHING_ALG_OBJ.orderedSequentialSearch(ordered_testlist, 13))
true
49d826cff0dbdfa85fba247ca626b04b05188571
aTechGuide/python
/generators/argument_unpacking.py
1,622
4.5625
5
""" dictionary unpacking => It unpacks a dictionary as named arguments to a function. """ class User: def __init__(self, username, password): self.username = username self.password = password @classmethod def from_dict(cls, data): return cls(data['username'], data['password']) def __repr__(self): return f"<User {self.username} with password {self.password}>" users = [ {'username': 'kamran', 'password': '123'}, {'username': 'ali', 'password': '123'} ] user_objects = [ User.from_dict(u) for u in users ] ## With Dictionary Unpacking class User2: def __init__(self, username, password): self.username = username self.password = password # @classmethod # def from_dict(cls, data): # return cls(data['username'], data['password']) def __repr__(self): return f"<User2 {self.username} with password {self.password}>" users = [ {'username': 'kamran', 'password': '123'}, {'username': 'ali', 'password': '123'} ] ## It unpacks a dictionary as named arguments to a function. In this case it's username and password. # So username is data['username'] # Basically it is equivalent to "user_objects_with_unpacking = [ User2(username=u['username'], password=u['password']) for u in users ] " # It's important because dictionary may not be in order. And remember named arguments can be jumbled up and that's fine. user_objects_with_unpacking = [ User2(**u) for u in users ] print(user_objects_with_unpacking) # if data is in form of tuple users_tuple = [ ('kamran', '123'), ('ali', '123') ] user_objects_from_tuples = [User2(*u) for u in users_tuple]
true
77d90d91bdf0e0c3b38927cd4d39a2712ed3160a
seancyw/Programming-Foundations-with-Python
/mindstorms.py
1,210
4.21875
4
import turtle def main() : #initialize a screen window = turtle.Screen() window.bgcolor("red") drawSquare() drawCircle() drawTriangle() window.exitonclick() def rotateSquare(someTurtle, angle) : #add some degree to the turle someTurtle.right(angle) def drawSquare() : #draw square on the screen brad = turtle.Turtle() brad.shape("turtle") brad.color("yellow") brad.speed(2) for i in range(36) : for j in range(4) : #move forward on 100 pixel brad.forward(100) #rotates in-place for 90 degree clockwise brad.right(90) rotateSquare(brad, 10) def drawCircle() : #Initialize instance of turtle named angie angie = turtle.Turtle() angie.shape("arrow") angie.color("blue") angie.circle(100) def drawTriangle() : #Initialize instance of turtle named dan dan = turtle.Turtle() dan.shape("classic") dan.color("green") dan.right(45) dan.forward(100) dan.right(135) dan.forward(130) dan.right(130) dan.forward(100) main()
true
228a818aa19bd74ffe70e0c504a4031e54f26cf9
dionis-git/study
/practice_3.py
695
4.5
4
# Check if a number is positive, negative, or NULL. while True: user_input = (input('enter a number:\n')) if user_input == 'exit': break else: # Check user input can get converted to 'float' try: user_variable = float(user_input) # Check the sign of the number if user_variable > 0: print("This is a positive number.") elif user_variable < 0: print("This is a negative number.") else: print('This is a NULL') except ValueError: print("This is not a number. ") finally: print("Type 'exit' to quit, or ", end='')
true
771fca844b27fa6ea48bd4260ce32fabef2bf45a
eeshanjindal/Python-code
/08_even_odd.py
297
4.25
4
n = int(input("enter a number: ")) if(n%2 ==0): print("number is even") else: print("number is odd") print("--end of program--") """ python 08_even_odd.py enter a number: 66 number is even --end of program-- python 08_even_odd.py enter a number: 35 number is odd --end of program-- """
false
e14d23e115efc937a7cea622aa49a073320e522d
guoweifeng216/python
/python_design/pythonprogram_design/Ch6/6-3-E18.py
1,071
4.125
4
import turtle def main(): t = turtle.Turtle() t.hideturtle() drawFilledRectangel(t, 0, 0, 200, 40, "black", "black") drawFilledRectangel(t, 5, 5, 190, 30, "yellow", "yellow") t.up() t.goto(100,0) t.pencolor("red") t.write("PYTHON", align="center", font=("Ariel", 20, "bold")) def drawFilledRectangel(t, x, y, w, h, colorP="black", colorF="white"): # Draw a filled rectangle with bottom-left corner (x, y), # width w, height h, pencolor colorP, and fill color colorF. t.pencolor(colorP) t.fillcolor(colorF) t.up() # Disable drawing of lines. t.goto(x , y) # bottom-left corner of rectangle t.down() # Enable drawing of lines. t.begin_fill() t.goto(x + w, y) # Draw line to bottom-right corner of rectangle. t.goto(x + w, y + h) # Draw line to top-right corner of rectangle. t.goto(x, y + h) # Draw line to top-left corner of rectangle. t.goto(x , y) # Draw line to bottom-left corner of rectangle. t.end_fill() main()
false
2bf67b381d30ee21a6f8abb175a908c98fe248f6
SarahTeoh/Statistical-Analysis-in-Python
/第3回/linear_regression_function.py
1,605
4.1875
4
#課題4-3 import csv import pandas as pd import random import statistics import matplotlib.pyplot as plt def standardize(data): mean = statistics.mean(data) stdev = statistics.stdev(data) return [(i - mean) / stdev for i in data] def calc_mse(height_array, weight_array, a, b): square_error = [(weight_array[height_array.index(height)]-(a * height + b))**2 for height in height_array] mse = sum(square_error)/len(height_array) return mse def main(): #Read data from csv file data = pd.read_csv('weight-height.csv') #Read male's height and weight data m_height = data[data.Gender=='Male']['Height'].tolist() m_weight = data[data.Gender=='Male']['Weight'].tolist() #Read female's height and weight data f_height = data[data.Gender=='Female']['Height'].tolist() f_weight = data[data.Gender=='Female']['Weight'].tolist() #Bind two lists as tuple in list m_weight_height = list(zip(m_weight, m_height)) f_weight_height = list(zip(f_weight, f_height)) #Get user's input gender = input("Please input gender: ") n = int(input("Please input N: ")) a = int(input("Please input a: ")) b = int(input("Please input b: ")) #Randomly choose N data to plot if gender == "female": chosen_data = random.sample(f_weight_height, n) elif gender == "male": chosen_data = random.sample(m_weight_height, n) else: print("Please insert only female of male") standardized_height = standardize(list(zip(*chosen_data))[0]) standardized_weight = standardize(list(zip(*chosen_data))[1]) print(calc_mse(standardized_height, standardized_weight, a, b)) if __name__ == '__main__': main()
true
91365c771a00fbc883d0b045b31a1a131b644953
SWI-MIN/Python_practice
/05.判斷_迴圈.py
1,507
4.125
4
###########判斷########### # if 條件: # 條件成立做這事,不成立往下 # elif 條件: # 條件成立做這事,不成立往下 # else: # 以上條件都不成立做這事 x=input("請輸入數字") x=int(x) # 轉型態 if x>100: print("超過100") elif x>50: print("超過50") else: print("小於50") ###########迴圈########### # while # for # while + for OR for + while ####控制迴圈#### # break 终止迴圈,並且跳出整個迴圈 # continue 终止當前迴圈,跳出此次迴圈,執行下一次迴圈 # pass pass是空語句,是為了保持程式结構的完整 numbers = [12,37,5,42,8,3] even = [] odd = [] while len(numbers) > 0 : print(numbers) number = numbers.pop() if(number % 2 == 0): even.append(number) print(even) print(odd) else: odd.append(number) print(even) print(odd) ################################## for numm in range(10,20): # 印出 10 到 20 之间的数字(含頭不含尾) print(numm) ################################## for num in range(10,20): # 迭代 10 到 20 之间的数字 for i in range(2,num): # 根据因子迭代 if num%i == 0: # 确定第一个因子 j=num/i # 计算第二个因子 print ('%d 等于 %d * %d' % (num,i,j)) break # 跳出当前循环 else: # 循环的 else 部分 print (num, '是一个质数')
false
4759ff4c96b9ed25e245c5ba57e530e8704870c4
thiagolrpinho/solving-problems
/leetcode/344_reverse_string.py
1,037
4.25
4
''' Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. Example 1: Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"] ''' import pytest from typing import List @pytest.mark.parametrize('input_and_output', [ (["h", "e", "l", "l", "o"], ["o", "l", "l", "e", "h"]), (["H", "a", "n", "n", "a", "h"], ["h", "a", "n", "n", "a", "H"])]) def test_reverse_string(input_and_output): input_list_string = input_and_output[0] expected_output = input_and_output[1] reverse_string(input_list_string) assert expected_output == input_list_string def reverse_string(s: List[str]) -> None: """ Do not return anything, modify s in-place instead """ s.reverse()
true
287cd92355c3138e1c61a293ca0d11b146293777
thiagolrpinho/solving-problems
/leetcode/1295_find_numbers_with_even_number_of_digits.py
1,210
4.15625
4
''' Given an array nums of integers, return how many of them contain an even number of digits. Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits. Example 2: Input: nums = [555,901,482,1771] Output: 1 Explanation: Only 1771 contains an even number of digits. Constraints: 1 <= nums.length <= 500 1 <= nums[i] <= 10^5 ''' import pytest from typing import List # Need to import this so we can use List[int] in args from math import log10 @pytest.mark.parametrize('input_and_output', [([12,345,2,6,7896], 2), ([555,901,482,1771], 1)]) def test_num_dup_digits_at_most_n(input_and_output): duplicate_count = {} input_digit = input_and_output[0] expected_output = input_and_output[1] predicted_output = findNumbers(input_digit) assert predicted_output == expected_output def findNumbers(nums: List[int]) -> int: return sum([int(log10(number)+1)%2 == 0 for number in nums])
true
27c5017bf11ad6021775ae76c3189d9822d47386
thiagolrpinho/solving-problems
/leetcode/167_two_sum_ii_input_array_is_sorted.py
1,824
4.125
4
''' Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Example: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. ''' import pytest from typing import List # Need to import this so we can use List[int] in args @pytest.mark.parametrize('input_and_output', [(([2,7,11,15], 9), [1,2]), (([2,7,11,15], 22), [2,4]), (([0,0,3,4], 0), [1,2])]) def test_num_dup_digits_at_most_n(input_and_output): duplicate_count = {} input_list = input_and_output[0][0] input_target = input_and_output[0][1] expected_output = input_and_output[1] predicted_output = twoSum(input_list, input_target) assert predicted_output == expected_output def twoSum(numbers: List[int], target: int) -> List[int]: small_number_index = 0 big_number_index = len(numbers)-1 while(True): ''' As it's garanteed it'll find a valid sum for target. We'll look till find something''' summation = numbers[small_number_index] + numbers[big_number_index] if summation == target: return [small_number_index+1, big_number_index+1] elif summation > target: '''If it's bigger, then we have to look for a smaller number to sum''' big_number_index -= 1 else: ''' If it's smaller then we have to look for a bigger number''' small_number_index += 1
true
96ba4580c2fee719119787c63f7abe2a836cd452
rezapci/Algorithms-with-Python
/less2_task7.py
575
4.21875
4
# Link to flowcharts: # https://drive.google.com/file/d/12xTQSyUeeSIWUDkwn3nWW-KHMmj31Rxy/view?usp=sharing # Write a program proving or verifying, # that for the set of natural numbers the equality holds: 1 + 2 + ... + n = n (n + 1) / 2, where n is any natural number. print ( " Let's check if the equality is of the form 1 + 2 + ... + n = n (n + 1) / 2 " ) n = int ( input ( " Enter a positive integer n: " )) x = 0 for i in range(1, n+1): x = i + x y = n * (n + 1 ) // 2 if x == y: print ( " Equality Proved " ) else: print ( " Equality not proven " )
true
76226282768c84c0618628323d465996ea9e38a7
rezapci/Algorithms-with-Python
/less2_task3.py
655
4.40625
4
# Link to flowcharts: # https://drive.google.com/file/d/12xTQSyUeeSIWUDkwn3nWW-KHMmj31Rxy/view?usp=sharing # Form from the entered number the reverse in the order of the numbers included in it and display it on the screen. # For example, if the number 3486 is entered, then you need to print the number 6843. print("Form the Inverse Number") number = input("Enter the number: ") # One could solve without loops like this: # Subsidized = number [:: - 1] # Print (the situation) # Or after two cycles like this: number = int(number) won = [] while number>0: rebmun.append(number % 10) number //= 10 for num in rebmun: print(num, end='')
true
20d66a7a38fcbff067e09486b77e6167b23642e2
rezapci/Algorithms-with-Python
/less2_task1.py
1,400
4.5
4
# Link to flowcharts: # https://drive.google.com/file/d/12xTQSyUeeSIWUDkwn3nWW-KHMmj31Rxy/view?usp=sharing # Write a program that will add, subtract, multiply or divide two numbers. # Numbers and the operation sign are entered by the user. After the calculation is complete, the program should not end, # and should request new data for calculations. # Program termination should be performed when the character '0' is entered as an operation sign. # If the user enters an incorrect character (not '0', '+', '-', '*', '/'), then the program should inform him of the error and # request the operation sign again. # Also inform the user about the impossibility of dividing by zero if he entered 0 as a divisor. print ( " Enter two numbers and the operation on them: " ) operation = None while operation != "0": number1 = float(input("first number: ")) number2 = float(input("second number: ")) operation = input ( " What will we do with them (+, -, *, /): " ) if operation == "+": print(number1 + number2) elif operation == "-": print(number1 - number2) elif operation == "*": print(number1 * number2) elif operation == "/": if number2 == 0: print ( " Division by zero is not possible! " ) else: print(number1 / number2) else: print ( " Unknown operation " ) else: print ( " Goodbye " )
true
392ec03fcfcc8734e16837d81e079d7484d6e869
pranithmididoddi/PythonFlowControl
/pythonFloControl.py
929
4.125
4
# print("Enter the number between 1 and 10") # number=int(input()) # # if number<5: # print("guess a larger number: ") # number=int(input()) # if number==5: # print("You guessed it correct") # else: # print("yOu guessed it wrong") # elif number>5: # print("guess a smaller number") # number = int(input()) # if number==5: # print("You guessed it correct") # else: # print("yOu guessed it wrong") # else: # print("You guessed it right at the first guess") #fizzbuzz for number in range(1,101): if(number%15==0): print("FizzBuzz") elif(number%3==0): print("Fizz") elif(number%5==0): print("Buzz") else: print(number) #fizzBuzzImplementation2 print("Enter the number: ") number=int(input()) if(number%15==0): print("FizzBuzz") elif(number%3==0): print("Fizz") elif(number%5==0): print("Buzz") else: print(number)
false
885e3863e460a0f06d2caf413efa17b02cbf749c
puladeepthi/deepthi.p
/3.py
256
4.15625
4
ch = input("Input a letter of the alphabet: ") if (ch=='a', 'e', 'i', 'o', 'u'): print("%s is a vowel.") elif('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'): print("%s is a consonant.") else: print("invalid")
false
0b28d47ab5faee1fcdddb819620824286701faff
danielsarkwa/alx-higher_level_programming
/0x06-python-classes/3-square.py
747
4.1875
4
#!/usr/bin/python3 """A module for working with squares. """ class Square: """Represents a 2D Polygon with 4 equal and perpendicular sides. """ def __init__(self, size=0): """Initializes a Square with a given size. Args: size (int): The size of the square. """ super().__init__() if not isinstance(size, int): raise TypeError('size must be an integer') else: if size < 0: raise ValueError('size must be >= 0') else: self.__size = size def area(self): """Computes the area of this Square. Returns: int: The area of the Square. """ return self.__size ** 2
true
bbd4b453f3b4e254ebda77735f13b4cf75417017
kittledt/py_code
/test/ts_db/ts_sqlite.py
925
4.1875
4
# 导入SQLite驱动: import sqlite3 # 连接到SQLite数据库,数据库文件是test.db,如果文件不存在,会自动在当前目录创建: conn = sqlite3.connect('test.db') # 创建一个Cursor: cursor = conn.cursor() # 执行一条SQL语句,创建user表: try: cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') # 继续执行一条SQL语句,插入一条记录: cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')') # 通过rowcount获得插入的行数: print(cursor.rowcount) cursor.execute('INSERT INTO user VALUES (?,?)',[('2', 'foo'),('3', 'bar'),('4', 'baz')]) cursor.execute('select * from user where id=?', ('1',)) # 获得查询结果集: values = cursor.fetchall() print(values) finally: # 关闭Cursor: cursor.close() # 提交事务: conn.commit() # 关闭Connection: conn.close()
false
33e229d88d9f8f97f6b069e79ba0ed07e617d4c9
DvC99/El_Radar
/multas.py
2,640
4.1875
4
""" Modulo Multas Funciones para el cálculo de multas de tránsito Daniel Valencia Cordero Mayo 10-2021 """ # Definición de Funciones def velocidad(recorrido,tiempo): return(recorrido//tiempo) def recorrido(disInicial, disFinal): return (disFinal-disInicial) def multar_velocidad(distancia_uno, distancia_dos,tiempo): recorTotal = recorrido(distancia_dos,distancia_uno) velo = velocidad(recorTotal,tiempo) if(velo <= 20): return "llamado de atención por baja velocidad","No se hace" elif(velo >= 21 and velo <= 60): return "Normal" elif(velo >= 61 and velo <= 80): return "llamado de atención por alta velocidad","No se hace" elif(velo >= 81 and velo <= 120): print("Realizar prueba de alcoholimetria y digite el valor dado aqu: \n") grado = int(input()) return "multa tipo I",multar_alcoholemia(grado) elif(velo >= 121): print("Realizar prueba de alcoholimetria y digite el valor dado aqu: \n") grado = int(input()) return "multa tipo II e inmovilización del vehículo",multar_alcoholemia(grado) def multar_alcoholemia(grado_alcohol): #TODO: Documentar función if(grado_alcohol >= 20 and grado_alcohol <= 39): return "Por tener entre 20 y 39 mg de etanol/l00ml, además de las sanciones previstas en la presente ley, se decretará la suspensión de la licencia de conducción entre seis (6) y doce (12) meses." elif(grado_alcohol >= 40 and grado_alcohol <= 99): return "Primer grado de embriaguez entre 40 y 99 mg de etanol/100 ml de sangre total, adicionalmente a la sanción multa, se decretará la suspensión de la Licencia de Conducción entre uno (1) y tres (3) años." elif(grado_alcohol >= 100 and grado_alcohol <= 149): return "Segundo grado de embriaguez entre 100 y 149 mg de etanol/100 ml de sangre total, adicionalmente a la sanción multa, se decretará la suspensión de la Licencia de Conducción entre tres (3) y cinco (5) años, y la obligación de realizar curso de sensibilización, conocimientos y consecuencias de la alcoholemia y drogadicción en centros de rehabilitación debidamente autorizados, por un mínimo de cuarenta (40) horas." elif(grado_alcohol >= 150): return "Tercer grado de embriaguez, desde 150 mg de etanol/100 ml de sangre total en adelante, adicionalmente a la sanción de la sanción de multa, se decretará la suspensión entre cinco (5) y diez (10) años de la Licencia de Conducción, y la obligación de realizar curso de sensibilización, conocimientos y consecuencias de la alcoholemia y drogadicción en centros de rehabilitación debidamente autorizados, por un mínimo de ochenta (80) horas."
false
31462de4cf721f570076d8fa6f78ecd6165ece89
Flagman2015/projekt
/les2_task_3_2.py
482
4.1875
4
dict = {1 : 'winter', 2 : 'spring', 3 : 'summer', 4 : 'autumn'} month = int(input("Введите месяц по номеру ")) if month ==1 or month == 12 or month == 2: print(dict.get(1)) elif month == 3 or month == 4 or month ==5: print(dict.get(2)) elif month == 6 or month == 7 or month == 8: print(dict.get(3)) elif month == 9 or month == 10 or month == 11: print(dict.get(4)) else: print("Такого месяца не существует")
false
9e4dc8f62459e8457f1e2869dc11291b607d43b4
ntire/AdventOfCode2020
/day2-py/passwordchecker/check_real_toboggan_policies.py
934
4.3125
4
def is_password_compliant(raw_rule): result = False # Step 1. Split input into three tokens # ( first: first and second position of letter, # second: letter, # third: password to be checked) tokens = raw_rule.split(" ") positions = tokens[0].split("-") first = int(positions[0]) second = int(positions[1]) letter = tokens[1].split(":")[0] password = tokens[2] if len(password) < first: result = False elif (len(password) >= first and len(password) < second): result = password[first - 1] == letter elif (len(password) >= second): # print("Letter: {}, First: {}, Second: {}".format(letter, password[first-1], password[second-1])) result = ((password[first - 1] == letter) and (password[second - 1] != letter)) or ((password[first -1 ] != letter) and (password[second - 1] == letter)) return result
true
a067663c6effb6f9ad3c52b5577aa177c6ce576a
perinm/ThinkPython
/05.2.py
276
4.125
4
def check_fermat(a,b,c,n): if(a**n+b**n==c**n): print("Holy smokes, Fermat was wrong!") else: print("No, that doesn't work") a=int(input("Digita a:\n")) b=int(input("Digite b:\n")) c=int(input("Digite c:\n")) n=int(input("Digite n:\n")) check_fermat(a,b,c,n)
false
ba865c675e220057d1f3244c55ce7e5a3f8f633c
marwahaha/PythonPractice
/File practice/file_practice.py
1,039
4.125
4
import os #Python file to practice with putting files in a dictionary with their extension #User input requested user_input = input("Voer de master directory in: ") #Loop die een variabele met het path naar een file update zodat iedere file in de directory wordt afgelopen. #Vervolgens worden de subdir en de file gejoind in de variabele current_dir #Hierna wordt een betreffende directory meegegeven aan een splitext commando die de extensie van de file afhaald for subdir, dirs, files in os.walk(user_input): for file in files: current_dir = (os.path.join(subdir, file)) filename, file_extension = os.path.splitext(current_dir) print(filename + file_extension) print(file_extension) #Tussen de haakjes moet een path komen die naar een bestand toe leidt. Dit moet dus elke keer geupdate worden. #De variabele filename wordt dan het path naar het bestand en file_extension wordt de extension. #filename, file_extension = os.path.splitext() #Alles uitprinten #print(filename) #print(file_extension)
false
17923f1736250c3e2bbf83bfff441965aeb95d4e
DanielLiMing/DesignMethod
/VistorMethord.py
1,942
4.21875
4
#!/usr/bin/python3 ''' 访问者模式: 表示一个作用于某对象结构中的各元素的操作,他可使你在不改变各元素的类的前提下定义作用于这些元素的新操作 ''' class Person: def Accept(self,visitor): pass class Man(Person): type = 'Man' def Accept(self, visitor): visitor.GetManConclusion(self) class Woman(Person): type = 'Woman' def Accept(self, visitor): visitor.GetWomainConclusion(self) class Action: def GetManConclusion(self,person): pass def GetWomainConclusion(self,person): pass class Success(Action): type = 'success' def GetManConclusion(self, person): print('%s %s时,背后多半有一个伟大的女人' %(person.type, self.type)) def GetWomainConclusion(self, person): print('%s %s时,背后大多有一个不成功的男人' %(person.type, self.type)) class Failing(Action): type = 'fail' def GetManConclusion(self, person): print('%s %s时,闷头喝酒,谁也不用劝' %(person.type, self.type)) def GetWomainConclusion(self, person): print('%s %s时,眼泪汪汪,谁也劝不了' %(person.type, self.type)) class ObjectStructure: elements = [] def Attch(self,element): self.elements.append(element) def Detach(self,element): self.elements.remove(element) def Display(self,visitor): for e in self.elements: e.Accept(visitor) def main(): o = ObjectStructure() o.Attch(Man()) o.Attch(Woman()) o.Display(Success()) o.Display(Failing()) return if __name__ == "__main__": main()
false
3a99d2db7a428dc7db8ef69b276bd30018a7681e
blakelobato/DS-Unit-3-Sprint-2-SQL-and-Databases
/sprint_3_2_SQL/northwind.py
2,762
4.34375
4
import sqlite3 conn = sqlite3.connect('northwind_small.sqlite3') cursor = conn.cursor() #if connected there should be demo_data.sqlite3 file where we are currently working so print this if that is the case print('No errors on connection') #### SPRINT PART 2 #### #--------------------------------------- #- What are the ten most expensive items (per unit price) in the database? cursor.execute('''SELECT ProductName, UnitPrice FROM Product ORDER BY UnitPrice DESC Limit 10;''') print(cursor.fetchall()) # SELECT ProductName, UnitPrice # FROM Product # ORDER BY UnitPrice DESC # LIMIT 10 #------------------------------------------------------ #What is the average age of an employee at the time of their hiring? (Hint: a lot of arithmetic works with dates.) cursor.exectue('''SELECT ROUND(AVG(HireDate - BirthDate)) FROM Employee);''' print(cursor.fetchall()) # SELECT ROUND(AVG(HireDate - BirthDate)) # FROM Employee #------------------------------------------------------- #(*Stretch*) How does the average age of employee at hire vary by city? cursor.execute('''SELECT City, ROUND(AVG(HireDate - BirthDate)) FROM Employee GROUP BY City''';) print(cursor.fetchall()) # SELECT City, ROUND(AVG(HireDate - BirthDate)) # FROM Employee # GROUP BY City; #### SPRINT PART 3 #### #What are the ten most expensive items (per unit price) in the database *and* their suppliers? cursor.execute('''SELECT ProductName, UnitPrice, CompanyName FROM Product JOIN Supplier ON product.SupplierId = supplier.Id ORDER BY UnitPrice DESC LIMIT 10;''') print(cursor.fetchall()) # SELECT ProductName, UnitPrice, CompanyName # FROM Product # JOIN Supplier ON product.SupplierId = supplier.Id # ORDER BY UnitPrice DESC # LIMIT 10 #What is the largest category (by number of unique products in it)? cursor.execute('''SELECT COUNT(ProductName), CategoryName FROM Product JOIN Category ON Product.CategoryId=Category.Id GROUP BY CategoryId ORDER BY COUNT(CategoryId) DESC LIMIT 1;''') print(cursor.fetchall()) # SELECT COUNT(ProductName), CategoryName # FROM Product # JOIN Category ON Product.CategoryId=Category.Id # GROUP BY CategoryId # ORDER BY COUNT(CategoryId) DESC # LIMIT 1 #(*Stretch*) Who's the employee with the most territories? Use `TerritoryId` (not name, region, or other fields) as the unique identifier for territories. cursor.execute('''SELECT COUNT(TerritoryID), FirstName, LastName FROM Employee JOIN EmployeeTerritory ON Employee.Id = EmployeeTerritory.EmployeeId GROUP BY Employee.Id ORDER BY COUNT(TerritoryId) DESC;''') print(cursor.fetchall()) # SELECT COUNT(TerritoryID), FirstName, LastName # FROM Employee # JOIN EmployeeTerritory ON Employee.Id = EmployeeTerritory.EmployeeId # GROUP BY Employee.Id # ORDER BY COUNT(TerritoryId) DESC
true
7c92bac6c558b5763cd8973347cf6f4673be3957
Baloshi69/Udacity-Project-Labs
/nd000 - Intro To Programing Nanodegree Program/nd000-04-Intro to Python, Part 1/nd000-04-LS02-Function Part 1/nd000-04-LS02-Tringal Color Circle.py
479
4.40625
4
import turtle tur = turtle.Turtle() # Write a function here that creates a # turtle and draws a shape with it. def shape(distance, sides, color, width, quantity): tur.color(color) tur.width(width) for side in range(quantity): for side in range(sides): tur.forward(distance) tur.right(360/sides) tur.left(15) # Call the function multiple times. shape(80, 3, "blue", 3, 7) shape(80, 3, "yellow", 3, 7) shape(80, 3, "red", 3, 7)
true
28dcebf00628303c97da301415d1d68d9b976b09
udaram/Data-Structure
/Infix_To_Postfix.py
2,522
4.375
4
'''######################################################################### Program to convert infix expression into postfix expression Ex. A+(B*C-(D/E-F)*G)*H ---->> ABC*DE/F-G*-H*+ NOTE::-Please take care that here we are not using expression involving mathematical operators like ^,** etc.. and use only '()' in expression if neccessary ######################################################################### ''' #Node class definition class Node: def __init__(self,data): self.data=data self.next=None #Stack class definition class Stack: #constructor def __init__(self): self.top=None def push(self,data): a=Node(data); if self.top is None: self.top=a else: a.next=self.top self.top=a def pop(self): if self.top is None: return else: self.top=self.top.next def isempty(self): if self.top is None: return True else: return False def precedence(a,b): if ((a is '+' or a is '-') and ( b is '-' or b is '+')) or ((a is '*' or a is '/') and (b is '/' or b is '*')) : return True if (a is '*' or a is '/') and (b is '-' or b is '+'): return True else: return False # End of Stack class #main() def main(): exp=input("Enter a valid infix Expression::") s=Stack() post_exp=[] for i in range(len(exp)): if exp[i] is '+' or exp[i] is '-' or exp[i] is '*' or exp[i] is '/'or exp[i] is '('or exp[i] is ')': if s.isempty() is True or exp[i] is '(' or s.top.data is '(': s.push(exp[i]) else: if exp[i] is ')': while s.top.data is not '(': post_exp.append(s.top.data) s.pop() s.pop() elif precedence(s.top.data,exp[i]) is True: #while s.top is not None or s.top.data is not '(': post_exp.append(s.top.data) s.pop() s.push(exp[i]) else: s.push(exp[i]) else: post_exp.append(exp[i]) if s.top is not None: while s.top is not None: post_exp.append(s.top.data) s.pop() print("The Postfix conversion is::",end="") for i in range(len(post_exp)): print(post_exp[i],end="") main()
true
9cb69ece904da8d30e32bf96175fd8176a95e2b2
Shreejan-git/allpy
/Faulty calculator.py
1,277
4.15625
4
def cal(u): '''This calculator can only calculate 2 numbers''' if u == 'l': first = int(input("Enter your first number: ")) second = int(input("Enter your second number: ")) print("Select the operator: ") operator = input("* for multiply, / for divide, + for add, - for subtract") if first == 45 and second == 3 and operator == '*': print("The multiplication of", first, "and", second, "is", 555) elif operator == '+': print("The addition of", first, "and", second, "is", first + second) elif operator == '-': print("Substraction is:", first - second) elif operator == '*': print("Multiplication is:", first * second) else: print("Division is:", first / second) again() else: print("Multiple operation") userformulti=input("Type your operations:") result=eval(userformulti) print(result) again() def againn(): u=input("Do you want to calculate 2 or more than 2\n l or m: ") return u def again(): print("\nDo you want to calculate again??") useri=input("Yes:Y No:N \n") if useri == 'Y': againn() else: print("Okay") a=againn() cal(a)
true
e229957d5d9678d311772debc48bb6ea39fcc995
KevinChen1994/leetcode-algorithm
/problem-list/Tree/145.binary-tree-postorder-traversal.py
1,153
4.125
4
# !usr/bin/env python # -*- coding:utf-8 _*- # author:chenmeng # datetime:2021/1/19 14:12 from typing import List ''' solution1: 使用辅助栈,与前序和中序不同的是,答案依次插入数组头部 solution2: 递归 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] result = [] stack = [root] while stack: root = stack.pop() result.insert(0, root.val) if root.left: stack.append(root.left) if root.right: stack.append(root.right) return result def postorderTraversal(self, root: TreeNode) -> List[int]: self.result = [] self.postorder(root) return self.result def postorder(self, root): if not root: return self.postorder(root.left) self.postorder(root.right) self.result.append(root.val)
false
1567d7fffd00927565936a49c9b953086e4a15ae
KevinChen1994/leetcode-algorithm
/algorithm-pattern/binary_search/35.py
624
4.15625
4
# !usr/bin/env python # -*- coding:utf-8 _*- # author:chenmeng # datetime:2020/7/20 22:45 class Solution: def searchInsert(self, nums, target): left = 0 right = len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] > target: right = mid - 1 elif nums[mid] < target: left = mid + 1 return left if __name__ == '__main__': solution = Solution() nums = [1, 3, 5, 6] target = 4 print(solution.searchInsert(nums, target))
true
946ac3df4489d48e9e08151c38f926b0e69a783f
houhailun/algorithm_code
/LeftRotateString.py
1,787
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 题目描述:左旋转字符串 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc” 解题思路:方法一:可以简单把前k位当作str1,后N位当作str2,直接str2+str1;缺点:针对n大于s长度时不生效 方法二:利用s翻转len(s)后仍然是s,则最终移位n%len(s) 方法二:利用三次翻转 """ class Solution: def left_rotate_string(self, s, n): # 当n大于s的长度时出现问题,不进行翻转 if not s or n <= 0: return s str1 = s[:n] str2 = s[n:] return str2+str1 def left_rotate_string_2(self, s, n): if not s or n <= 0: return n = n % len(s) # 解决n大于s长度的问题 return s[n:]+s[:n] def left_rotate_string_3(self, s, n): if not s or n <= 0: return s n = n % len(s) # 解决n大于len(s)的问题 # 字符串是不可变对象,不能通过下表改变值,这里转换为list s = list(s) self.reverse(s, 0, n-1) # 翻转前字串 self.reverse(s, n, len(s)-1) # 翻转后字串 self.reverse(s, 0, len(s)-1) # 翻转整个字符串 return ''.join(s) # 转换位str def reverse(self, s, start, end): while start <= end: s[start], s[end] = s[end], s[start] start += 1 end -= 1 if __name__ == "__main__": cls = Solution() print(cls.left_rotate_string('abcdfge', 8)) print(cls.left_rotate_string_2('abcdfge', 8)) print(cls.left_rotate_string_3('abcdfge', 8))
false
c6ff32f355825c3c0469cf7e31fcc0418a6b14cb
quamejnr/Python
/Dictionary/Inventory.py
836
4.21875
4
# code to count an inventory or number of characters in a message def character_count(message): # input a variable containing strings when calling function count = {} for character in message: count.setdefault(character, 0) # set key and make default value = 0 count[character] = count[character] + 1 # add one to the value of the key return len(count) stuff = {"rope": 1, 'torch': 6, 'gold coin': 42, "dagger": 1, 'arrow': 12} def display_inventory(inventory): # function for displaying the keys and values in a dictionary print('Inventory:') result = 0 for k, v in inventory.items(): result = result + v print(f'{v} {k}') # prints the key and its value in the inventory print(f'Total number of items:{result}') # prints the sum of the values in the inventory
true
e0dec705f0f7f150412b864359a009f73b85783f
quamejnr/Python
/Projects/guessing_game.py
1,067
4.3125
4
secret_word = "APPLE" guess_word = "" guess_count = 0 guess_limit = 3 out_of_guesses = False name_of_player = input("Enter your name: ") print("WELCOME " + name_of_player.upper() + "! THIS IS A GUESSING GAME") print("The rules are simple: You have three attempts and three clues to guess the secret word.\n") while guess_word.casefold() != secret_word and not out_of_guesses: if guess_count == 0: print("Clue 1: It is used as a symbol of love") guess_word = input("Enter guess word: ") guess_count += 1 elif guess_count == 1: print("\nClue 2: Mostly favoured by Wicked stepmothers") guess_word = input("Enter guess word: ") guess_count += 1 elif guess_count == 2: print("\nClue 3: It is a fruit") guess_word = input("Enter guess word: ") guess_count += 1 else: out_of_guesses = True if out_of_guesses: print("\nSorry " + name_of_player.upper() + " You are out of guesses, You lose!") else: print("\nCongratulations " + name_of_player.upper() + " You win!")
true
15dbce03cc583fa8ef474940ff5c823577312ee4
quamejnr/Python
/Itertools Module/itertoools.py
1,544
4.15625
4
import itertools counter = itertools.count(0, 2) # print(next(counter)) data = [10, 20, 30, 40] daily_data = list(zip(counter, data)) print(daily_data) # itertools.zip_longest unlike zip will continue to pair until the iterable runs out daily_data = list(itertools.zip_longest(range(10), data)) # itertools.cycle is used when running a cycle # switch = itertools.cycle(("On", "Off")) # print("Switch on light") # print(f'Light is {next(switch)}') # print("Switch off light") # print(f'Light is {next(switch)}') squares = map(pow, range(10), itertools.repeat(2)) # itertools.starmap allows one to be able to run a function like map with just one arg (iterable) star_squares = itertools.starmap(pow, [(0, 2), (1, 2), (2, 2)]) pass # itertools.combinations gives you the different combinations of a list where order is not a factor letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4, 5] names = ['Quame', 'Jnr'] comb = itertools.combinations(letters, 2) for item in comb: pass # itertools.permutations gives you the different permutations of a list where order is a factor comb = itertools.permutations(letters, 2) for item in comb: pass # itertools.product gives you the different combinations of a list where item can be repeated many times comb = itertools.product(numbers, repeat=4) for item in comb: pass # itertools.chain allows you to combine two or more lists combined = itertools.chain(letters, numbers, names) for item in combined: pass dic = {'house A':('Kofi', 'Ama'), 'house B': ('Kwaku', "Abena")}
true
f2f0eb88f69012d61992ab2bfa81e70540016784
quamejnr/Python
/CSV - files/csv_practice.py
924
4.1875
4
import csv with open('names.csv', 'r') as csv_file: # csv.DictReader outputs the file in dictionary mode which helps in using the keys to output values csv_dict_reader = csv.DictReader(csv_file) # csv.reader just outputs the file in the same format as it is csv_reader = csv.reader(csv_file) with open('new_file.csv', 'w') as new_file: # when using csv.DictReader, fieldnames are to be provided before writing them off fieldnames = ['first_name', 'last_name', 'email'] # csv.DictWriter is used when writing in Dictionary mode with fieldnames passed as argument csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t') # The writeheader() method allows csv.DictWriter to write the heading of the csv file or it will be omitted csv_writer.writeheader() for line in csv_dict_reader: csv_writer.writerow(line)
true
bf319773e531552ad6c1fdb316030c964687e69b
abhishm/cs61a
/pallindrome_string.py
2,408
4.125
4
def pallindrome(s): """Return the largest pallindrome in the string >>> pallindrome("abcba") 'abcba' >>> pallindrome("abcbd") 'bcb' """ if len(s) <= 1: return s elif s[0] != s[-1]: begining_pallindrome = pallindrome(s[:-1]) ending_pallindrome = pallindrome(s[1:]) if len(begining_pallindrome) >= len(ending_pallindrome): return begining_pallindrome else: return ending_pallindrome else: middle_pallindrome = pallindrome(s[1:-1]) if len(middle_pallindrome) == len(s[1:-1]): return s[0] + middle_pallindrome + s[-1] else: return middle_pallindrome def pallindrome2(s): """Return the largest in a string in O(n**2) time and constant memory >>> pallindrome2("abcba") 'abcba' >>> pallindrome2("abcbd") 'bcb' >>> pallindrome2("hackerrekcahba") 'hackerrekcah' """ def pallindrome_at_i(s, i): """Return the starting position and length of the largest pallindrome string starting from position i >>> pallindrome_at_i("abcbd", 0) (0, 1) >>> pallindrome_at_i("abcbd", 2) (1, 3) >>> pallindrome_at_i("abcbd", 1) (1, 1) >>> pallindrome_at_i("abbd", 1) (1, 2) >>> pallindrome_at_i("abcbb", 2) (1, 3) """ lower_lim = i upper_lim = i is_pallindrome = True if lower_lim >= 1 and upper_lim < len(s) - 1 and s[lower_lim - 1] == s[upper_lim + 1]: lower_lim -= 1 upper_lim += 1 elif upper_lim < len(s) - 1 and s[lower_lim] == s[upper_lim + 1]: upper_lim += 1 else: return lower_lim, (upper_lim - lower_lim + 1) while lower_lim >= 1 and upper_lim < len(s) - 1: if s[lower_lim - 1] == s[upper_lim + 1]: lower_lim -= 1 upper_lim += 1 else: return lower_lim, (upper_lim - lower_lim + 1) return lower_lim, (upper_lim - lower_lim + 1) start_max_pallindrome = 0 len_max_pallindrome = 0 for i in range(len(s)): start, length = pallindrome_at_i(s, i) if length > len_max_pallindrome: start_max_pallindrome, len_max_pallindrome = start, length return s[start_max_pallindrome:start_max_pallindrome + len_max_pallindrome]
false
5be233e885c7ec1c45c8ecf604686fa7cd2240a3
CoffeyBlog/Python-Programming-Guide
/python-basics/python-basics-1.1-intro/basics-1.1.py
483
4.15625
4
x = 3 y = 2 print('Hello World') # String - single quotes print(1 + 2) # expression - addition print(7 * 6) # expression - multiplication print() # empty print("The End") # String - double quotes print('And she said "Good Morning Class" ') # To quote someone in a string use a "different type of quotes "" '' print('Hello' + " World") # String Concatenation greeting = "Hello " name = "Willie" print(greeting + name)
true
bf63b72f87ae6a0bfd062bb8b33c8e3b2ae20c0f
andriika/problem-solving
/diameter-of-binary-tree.py
1,492
4.25
4
# https://leetcode.com/problems/diameter-of-binary-tree/ # Given a binary tree, you need to compute the length of the diameter of the tree. # The diameter of a binary tree is the length of the longest path between any two nodes in a tree. # This path may or may not pass through the root. # # Given a binary tree # # 1 # / \ # 2 3 # / \ # 4 5 # Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. from tree import TreeNode def diameter(node: TreeNode): # running maximum of diameters res = 0 # DFS postorder traversal. Returns max depth of the node. # As side-effect, computes def depth(node: TreeNode, cb): nonlocal res # base case if not node: # depth of a node beyond leaf node is -1 (so depth of the leaf node is 0) return -1 # get max depth of children l, r = depth(node.left, cb), depth(node.right, cb) # expose children depth via callback cb(l, r) # return max depth of the current node return max(l, r) + 1 # running maximum of diameters res = 0 # callback function that calculates diameter of the node based on # their children depth and updates running maximum of diameters def onDepth(l, r): nonlocal res diameter = l + r + 2 res = max(res, diameter) depth(node, onDepth) return res # Test assert diameter(TreeNode.create([1, 2, 3, 4, 5])) == 3
true
897c6958c782591ea88a1096389393c7a97c0554
Bzan96/python-stuff
/Intermediate/sum_all_numbers_in_a_range.py
460
4.25
4
''' We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first. ''' def sumAll(arr): arr.sort() sumArr = 0 for i in range(arr[0], arr[1]+1): #arr[1]+1 because the loop runs up TO, but not INCLUDING sumArr += i return sumArr print(sumAll([1, 4]) ) print(sumAll([1, 4]) ) print(sumAll([4, 1]) ) print(sumAll([5, 10]) ) print(sumAll([10, 5]) )
true
0d85082bffc6f1a28517f7dd09bfaae157202619
Bzan96/python-stuff
/Intermediate/sum_all_primes.py
837
4.28125
4
''' Sum all the prime numbers up to and including the provided number. A prime number is defined as a number greater than one and having only two divisors, one and itself. For example, 2 is a prime number because it's only divisible by one and two. The provided number may not be a prime. ''' # The variable 'boo' is a bandaid-fix to stop the looping ## Sidenote: Do people not realise that the formula "prime=(X % 2 === 0)" ## doesn't actually give us prime numbers, but ALL odd numbers? def sumPrimes(num): primeArr = [] sum = 0 boo = False primeArr.append(2) for i in range(3,num+1,2): if boo==False: for j in primeArr: if (i % j == 0): boo = True if boo == False: primeArr.append(i) boo = False for num in primeArr: sum+=num return sum print(sumPrimes(10) ) print(sumPrimes(977) )
true
253965af09ae46a4a00a6865537c8b592dffe9ee
skokal01/Interview-Practice
/salesforce_top_3_closest_address.py
1,261
4.34375
4
''' # Write a program to produce a list of 3 closest addresses to the city center # based on the supplied distance from the city center per address for a given # set of addresses i/p: (address,d), k -- number of closest addresses o/p: List[(address,distance)] ''' # Code for implementing custom comparators, # this is not currently used in the solution # wrote it for reference purposes class Address(object): def __init__(self,distance,address): self.distance = distance self.address = address def __cmp__(self,other): return cmp(self.distance,other.distance) import heapq def getKClosestAddresses(addresses,k): ''' :addresses list of pairs with address and distance ''' if k < 0: return [] if not addresses: return [] h = [] for i in addresses: #a,d = i.address,i.distance heapq.heappush(h,i) ret = [] for i in xrange(k): a = heapq.heappop(h) ret.append((a.address,a.distance)) return ret if __name__ == "__main__": addresses = [Address(5,"FRE"),Address(10,"SFO"),Address(4,"OAK"),Address(20,"SJC"),Address(100,"LAX"),Address(2,"MIL")] print getKClosestAddresses(addresses,3)
true
4fcccf2ca09a90240179bb8afe6c26256f6718bd
that-danya/HB-Classes-Assessment-Practice
/practice.py
2,524
4.4375
4
""" Parts 1-4 Create your classes and class methods here according to the practice instructions. As you are working on Parts 1, 2, and 4, you can run the test python file corresponding to that section to verify that you are completing the problem correctly. ex: python part_1_tests.py. """ class Student(object): """Capture personal data about student.""" def __init__(self, first_name, last_name, address): """Define name and address at initialization.""" self.first_name = first_name self.last_name = last_name self.address = address class Question(object): """Capture question and correct answer""" def __init__(self, question, correct_answer): """define question and answer at initialization.""" self.question = question self.correct_answer = correct_answer def ask_and_evaluate(self): """Ask random question from test; evaluate T/F.""" # print q to console # prompt user for answer # return T/F ## ex call: e.questions[0].ask_and_evaluate() user_i = raw_input('{} > '.format(self.question)) if user_i == self.correct_answer: return True else: return False class Exam(object): """Capture exam data""" def __init__(self, name): """Define exam name and set at initialization.""" self.name = name self.questions = [] def add_question(self, question_label): """Add Question to (type of) exam questions list.""" # add label to questions list self.questions.append((question_label)) def administer(self): """Ask all q's and return score.""" # assign how many items to count, 0 for score # loop over questions, if correct add to score # divide score after looping by count question_count = len(self.questions) score_right = 0 for i in range(len(self.questions)): check = self.questions[i].ask_and_evaluate() if check is True: score_right += 1 score = score_right / float(question_count) return score class StudentExam(object): """Student to take exam, capture data.""" def __init__(self, name, exam, score=None): """Instantiate name, exam, score for student""" self.name = name self.exam = exam self.score = score def take_test(self): """Administer exam and set score.""" score = self.exam.administer()
true
f12566c43f53410e5d524618dd77b990b6096b68
shirleylau/algorithms
/crackingCode/python/1_1.py
329
4.15625
4
# Implement an algorithm to determine if a string has all unique characters. # What if you can not use additional data structures?? string = 'banana' ordered = ''.join(sorted(string)) prev = '' redundant = [] for char in ordered: if char == prev: redundant.append(char) prev = char print len(redundant) == 0
true
fb3e13822404130c43dda7ed7875623d8d31b999
tommysuen/Code-Academy-Challenges
/Code Academy Challenges/Coding challenge 1.py
525
4.28125
4
#Write a program that prints the numbers from 1 to 100. #But for multiples of three print Fizz instead of the number and for #the multiples of five print Buzz. #For numbers which are multiples of both three and five print FizzBuzz. def FizzBuzz(): for x in range(1, 101): if x % 3 == 0 and x % 5 == 0: print("FizzBuzz") elif x % 5 == 0: print("Buzz") elif x % 3 == 0: print("Fizz") else: print(x) FizzBuzz()
true
626df32dd4dc5296426159d1ed153a2c420d8c3b
hunjinee/GitHub_Public_Repository
/python/fundamentals/fundamentals/for_loop_basic1.py
2,951
4.15625
4
#1. Basics - Print all integers from 0 to 150 # While Loop 0-150 count = 0 while count <= 150: print(count) count += 1 #For Loop 0-150 for count in range(0,151): print(count) #2. Multiples of 5 - Print all the multiples of 5 from 5 to 1,000 # For Loop with 3 arguments for x in range(5,1005,5): print(x) # While Loop count = 5 while count <= 1000: print(count) count += 5 #3. Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print 'Coding' instead. If divisible by 10, print 'Coding Dojo' for i in range(1,101): #integer(i) in range including 1, excluding 101 if i % 10 == 0: #if i divided by 10 gives remainder 0 print("Coding Dojo") elif i % 5 == 0: #if i divided by 5 gives remainder 0 print("Coding") else: print(i) #print integer #4. Whoa. That Sucker's Huge - Add ODD integers from 0 to 500,000, and print the final sum. n = 500000 #final range number sum = 0 #sum of numbers for i in range(1,n+1,2): #integer (i) in range 1 (odd) to 500000 increasing by +2 -- no need to include 0 sum += i #sum = sum + i -- current sum + integer(i) print(sum) #prints 62500000000 as final sum of all ODD integers within specified range #another way to write it sum = 0 for i in range (1,500001): if i % 2 != 0: #if i divided by 2 is NOT equal to 0, then condition is TRUE -- so true for ODD numbers sum += i #sum = sum + i -- i = ODD numbers only within specified range print(sum) #prints 62500000000 as final sum of all ODD integers within specified range #5. Countdown by Fours - Print positive numbers starting at 2018, counting down by 4s for x in range (2018,-1,-4): #-1 from lower range in case 0 may be included in the countdown print(x) #prints all positive numbers from 2018 down to 0, counting down by 4s #another way to write it -- slightly longer, but more clear n = 0 #final number target for x in range (2018,n-1,-4): print(x) #6. Flexible Counter - Set 3 variables: lowNum, highNum, mult. Starting at lowNum and going through highNum, #print only the integers that are multiples of mult. lowNum = 5 highNum = 1000 mult = 5 for x in range (5,highNum+1,mult): #x in range 0 to 1000 inclusive by increments of mult (5) if x % mult == 0: #if remainder is 0 after dividing x by mult (5) condition is TRUE print(x) #prints numbers that satisfy condition as TRUE #another way to write it lowNum = 5 highNum = 1000 mult = 5 for x in range (5,highNum+1): if x % mult == 0: print(x) #or another way highNum = 1000 mult = 5 lowNum = mult for x in range (lowNum,highNum+1,mult): print(x) #different harder example lowNum = 0 highNum = 1000 mult = 7 for x in range (0,highNum+1,mult): if x == 0: continue elif x % mult == 0: print(x) #different even harder example lowNum = 0 highNum = 2000 mult = 27 for x in range (lowNum, highNum+1, mult): if x % mult == 0: print(x)
true
73b9f7f5055a576a4c7b1677dae57b8cda681d57
hopestar06/data-structures
/parenthetics.py
884
4.28125
4
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ The parens() function takes in a string containing O or more parentheses Returns: - 0 if the parentheses are balanced: the opening parentheses, '(', is the first parentheses in the string and the number of opening, '(', and number of closing ')' parentheses are equal - 1 if there are open parentheses that are not closed - -1 if a closing parentheses has not bee proceeded by one that that opens """ def parens(astring): parens_list = [] for char in astring: if char == '(': parens_list.append(char) elif char == ')': try: parens_list.pop() except Exception: return -1 if len(parens_list) != 0: return 1 elif len(parens_list) == 0: return 0
true
6b851265c8c986969997d59f68165431c34814d1
hassanaliaskari/CanvassCodeChallenge
/challenge1.py
840
4.1875
4
import math # Checks if digits in a number are even # Returns boolean of the check and returns smallest place-value of the odd digit def are_digits_even(num): factor = 1 while num >= 1: digit = num%10 if digit%2 == 1: return (False, factor) num = math.floor(num/10) factor *= 10 return (True, -1) # Returns a list of numbers between 'start' and 'end' (inclusive) whose digits are all even def get_even_digit_numbers(start, end): numbers = [] number = start while number <= end: is_valid_number, factor = are_digits_even(number) if is_valid_number == True: numbers.append(number) number += 2 else: number += factor return numbers numbers = get_even_digit_numbers(1000, 3000) print(*numbers, sep=",")
true
43e9d5a6b26ae3309cbc188f22510a98eedbb207
Din0101/GBPythonBasics
/les3/task3.py
615
4.53125
5
"""3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.""" def my_func(var1: float, var2: float, var3: float) -> float: """ Вернём сумму двух наибольших! :param var1: float :param var2: float :param var3: float :return: float """ return var1 + var2 + var3 - min(var1, var2, var3) print(my_func(-1, 2, 3)) print(my_func(2, 3, -1)) print(my_func(3, 2, -1)) print(my_func(2, -1, 3))
false
bcb85fa6ae4ecd64ba6e984c0b2a652c582037e6
Din0101/GBPythonBasics
/les3/task1.py
1,221
4.34375
4
"""1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.""" def func(var1: float, var2: float, *args, **kwargs) -> float or None: """ Делим первое значение на второе. :param var1: float - делимое :param var2: float - делитель :param args: прочее :param kwargs: для совместимости :return: float - частное от деления, или None, если делитель 0. """ if var2: return var1 / var2 return None while True: var1 = input('Введите делимое\n') try: var1 = float(var1) break except ValueError as e: print('Ожидается число!') while True: var2 = input('Введите делитель\n') try: var2 = float(var2) break except ValueError as e: print('Ожидается число!') print(func(var1, var2))
false
f26c5c5c70cadfb318380990ed10983a7e0a6422
fernandoso4res/exerciciosDeLogica
/EX1.py
497
4.15625
4
#Faça um algoritmo que troque o valor de duas variáveis. #Por exemplo, o algoritmo lê n1 igual a 3 e n2 a 17, e mostra n1 igual a 17 e n2 a 3. print("Faça um algoritmo que troque o valor de duas variáveis.") print("Por exemplo, o algoritmo lê n1 igual a 3 e n2 a 17, e mostra n1 igual a 17 e n2 a 3.") n1 = int(input("Digite um número: ")) n2 = int(input("Digite outro número: ")) print(n1, n2) num1 = n2 num2 = n1 print(f"Essa é a ordem invertida dos números: {num1, num2}") input()
false
bdbc295b8e41251f04863331a6c346eded509a2d
fernandoso4res/exerciciosDeLogica
/LISTA2ex8.py
864
4.15625
4
#Os endereços IP versão 4 são divididos em cinco classes: #A, B, C, D e E. #Os endereços no intervalo de 0 à 127 são classe A, #de 128 à 191 são classe B, de 192 à 223 são classe C, #de 224 à 239 são classe D e a partir de 240 são classe E. #Faça um algoritmo que leia o primeiro octeto, no formato decimal, de um endereço IP e informe a sua classe. ip = int(input("Digite o primeiro octeto do IP: ")) if ((ip >= 0) and (ip <= 127)): print(f"O IP {ip}, pertence a classe A.") elif ((ip >= 128) and (ip <= 191)): print(f"O IP {ip}, pertence a classe B.") elif ((ip >= 192) and (ip <= 223)): print(f"O IP {ip}, pertence a classe C.") elif ((ip >= 224) and (ip <= 239)): print(f"O IP {ip}, pertence a classe D.") elif (ip >= 240): print(f"O IP {ip}, pertence a classe E.") else: print("Não existe esse IP.") input()
false
5b5252d8ff36cfe2a2ecff5172c7d3b9f187bb08
fernandoso4res/exerciciosDeLogica
/EX8.py
551
4.3125
4
#Faça um algoritmo que calcule a área de um círculo, sendo que o comprimento do #raio é informado pelo usuário. A área do círculo é calculada multiplicando-se Pi ao #raio ao quadrado. print("Faça um algoritmo que calcule a área de um círculo,") print("sendo que o comprimento do raio é informado pelo usuário.") print("A área do círculo é calculada multiplicando-se Pi ao raio ao quadrado.") raio = float(input("Digite o raio do círculo: ")) calculoraio = (raio ** 2) * 3.14 print(f"A area do circulo é: {calculoraio}") input()
false
bdd89ed86ecc29bee6f29888f19beec0b87bc826
DanielPra/-t-Andre
/e20.py
692
4.15625
4
# Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest) and # another number. The function decides whether or not the given number is inside the list and returns (then prints) an appropriate # boolean. number = [99] list = [3, 4, 5, 6, 7, 9, 99, 111] #list = ["3", "4", "5", "6", "14", "44", "77", "88", "99" ] if number in list: print("Correct") else: print("Incorrect") """ length = (len(list)) middle_value = length / 2 #print(middle_value) print(list(middle_value)) def basic_search(): for element in list: if element in number: print("I found the number")"""
true
9e2a91ad1b2662e8eec172574539763b38fef996
MPTauber/Machine_Learning
/Part2_LinearRegression_Machine_Learning_Exercise.py
2,598
4.15625
4
## Reimplement the simple linear regression case study of Section 15.4 using the average yearly temperature data. ## How does the temperature trend compare to the average January high temperatures? import pandas as pd nyc = pd.read_csv("ave_yearly_temp_nyc_1895-2017 (2).csv") nyc.columns = ["Date","Temperature","Anomaly"] nyc.Date = nyc.Date.floordiv(100) # used for integer division of the dataframe with 100 print(nyc.head(3)) ### SPLITTING THE DATA FOR TRAINING AND TESTING from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split( nyc.Date.values.reshape(-1,1), nyc.Temperature.values, # reshape infers the number of rows (124) with -1, to fit into 1 column random_state=11 ) ## TRAINING THE MODEL from sklearn.linear_model import LinearRegression linear_regression= LinearRegression() linear_regression.fit(X=x_train, y=y_train) LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False) # fit returns the estimator ## LinearRegression tries to ifnd the best fitting regression line by iteratively adjusting the slope and intercept values # to minimize the sum of the squares of the data points' distances from the line. print(linear_regression.coef_) print(linear_regression.intercept_) # y =mx+b # So: # y = 0.03157x - 7.8929 ### TESTING THE MODEL predicted = linear_regression.predict(x_test) expected = y_test for p,e in zip(predicted[::5], expected[::5]): print(f"predicted: {p:.2f}, expected: {e:.2f}") ## seems not too far off ### PREDICTING FUTURE TEMPERATURES AND ESTIMATING PAST TEMPERATURES predict = (lambda x: linear_regression.coef_ * x + linear_regression.intercept_) print(predict(2019)) # 55.85584 print(predict(1890)) # 51.7827 ### VISUALIZING THE DATASET WITH THE REGRESSION LINE import seaborn as sns axes = sns.scatterplot(data=nyc, x="Date", y="Temperature", hue = "Temperature", palette="winter", legend=False) # no legend for this graph axes.set_ylim(10,70) import numpy as np # to display the regression line # coordinates for regression lnie's start and end points: x = np.array([min(nyc.Date.values), max(nyc.Date.values)]) y= predict(x) # passing the array x to the lambda from ealier import matplotlib.pyplot as plt line = plt.plot(x,y) plt.show() ### ANSWER TO QUESTION: print(np.average(nyc.Temperature.values)) # average is 53.8569 # As graph and equation shows, temperature is trending upwards. print(predict(22000)) # For example, Model predicts that the temperature in 19,980 years is very hot........ # But we will all be dead by then
true
781434bd88a6d6d4cecc6201d4642cef7be7a406
B-Lei/ScriptPractice
/CSVmaker/maxOfColumn.py
628
4.125
4
#!/usr/bin/python # FUNCTION: Returns the maximum value in column $2 of file $1. Must be a CSV. import csv import sys # Saves the column of a csv to a dictionary def csv_col_to_dict(filename, column): dict = {} reader = csv.DictReader(open(filename, 'r')) for line in reader: key = line.values()[0] value = int(line.values()[int(column)-1]) dict[key] = value return dict def main(): dictionary = csv_col_to_dict(sys.argv[1], sys.argv[2]) max_value = max(dictionary.values()) print "Max value: " + str(max_value) if __name__ == "__main__": main()
true
a54c4546d2e72d315e0679572bdec8ccaf0bf12e
mentecatoDev/python
/UMDC/03/11a.py
412
4.21875
4
""" Ejercicio 11a Escribir una función que reciba dos números como parámetros, y devuelva cuántos múltiplos del primero hay, que sean menores que el segundo. a) Implementarla utilizando un ciclo for, desde el primer número hasta el segundo. """ def numMulFor(m, n): numMul = 0 for i in range(m, n+1): if i % m == 0: numMul += 1 return numMul print(numMulFor(12, 360))
false
b7429b78dd8cdb96b0eb0d23ad09607ba27f52d0
mentecatoDev/python
/UMDC/03/03.py
798
4.3125
4
""" Ejercicio 03 Escribir un programa que reciba una a una las notas del usuario, preguntando a cada paso si desea ingresar más notas, e imprimiendo el promedio correspondiente. """ print("Introduzca sus notas") print("====================") i = 0 total = 0 masNotas = True while masNotas: leyendo = True while leyendo: try: n = float(input("Introduzca nota : ")) leyendo = False except ValueError: print("Introduzca un valor numérico") total += n i += 1 leyendo = True while leyendo: respuesta = input("¿Otra nota? (S/N)") if (respuesta in "SNsn") and len(respuesta) == 1: leyendo = False if respuesta in "Nn": masNotas = False print("Su promedio es de", total / i, "puntos")
false
e6bac3fcc23f85ebeb97b58b3b5f8c3c7cd54a47
mentecatoDev/python
/UMDC/03/11bc.py
599
4.15625
4
""" Ejercicio 11bc Escribir una función que reciba dos números como parámetros, y devuelva cuántos múltiplos del primero hay, que sean menores que el segundo. b) Implementarla utilizando un ciclo while, que multiplique el primer número hasta que sea mayor que el segundo. """ def num_mul(m, n): i = 1 mul = m while mul <= n: i += 1 mul *= i return (i-1) print(num_mul(12, 360)) """ c) Comparar ambas implementaciones: ¿Cuál es más clara? ¿Cuál realiza menos operaciones? La primera es más clara pero la segunda es manifiestamente más rápida. """
false
d597f2f2abb9ef1823d573cfebc7c7ef2f9c417a
newsoftmx/python
/arreglos.py
1,492
4.21875
4
#Si deseo importar solo la propiedad array de NumPy #cuando se utilizan vectores o matrices utilizare Numpy import numpy as np import random import time #defino el tamaño del arreglo de forma directa #a=np.array([0,0,0]) #defino el tamaño del arreglo de forma automática a=np.arange(3) #defino el tamaño del arreglo desde un rango con incrementable arreglo_rango=np.arange(1,1000,1) #Solicito la captura de los valores del rango for posicion in range(0,3,1): numero=int(input("escribe el valor del arreglo de la posición: " )) a[posicion]=numero for posicion in range(0,3,1): print("El valor del arreglo en la posición: ", posicion ," es: ", a[posicion]) #for posicion in range(0,a.size): # numero=int(input("escribe el valor del arreglo de la posición: ")) # a[posicion]=numero print("En 1 segundos se mostrará el tamaño del arreglo") time.sleep(1) print(a.size) print("En 1 segundos se mostrará el arreglo") time.sleep(1) print(a) print("En 1 segundos se ordenará el arreglo") time.sleep(1) a.sort() print(a) print("En 1 segundos se mostrará el arreglo de 1000 valores") time.sleep(1) print(arreglo_rango) print("En 1 segundos se mostrará el arreglo de 1000 valores pero ordenado") time.sleep(1) arreglo_rango.sort() print(arreglo_rango) arreglo_aleatorio=np.arange(1000) for x in range(1,1000,1): numeroAleatorio=random.uniform(1,10000) arreglo_aleatorio[x]=numeroAleatorio print(arreglo_aleatorio) #genere una pausa y ordene el arreglo e imprima el arreglo
false
60cdfbf29686e1ed616d5c66f9f57cbd19bfb00e
VSmith21/CTI110
/Debugging.py
592
4.15625
4
#Vondre Smith #CTI - 110 #P3LAB - Debugging #03.12.2018 def main(): #This program takes a number grade and outputs a letter grade. #This system uses a 10-point grading scale #TO DO: define the rest of the scores print("Hey there!") main() score = int(input("Enter grade: ")) if score >= 90: print("Your grade is: A") elif score >= 80: print("Your grade is: B") elif score >= 70: print("Your grade is: C") elif score >= 61: print("Your grade is: D") else: print("Your grade is: F")
true
7f5b56ab129f087af9986708c5533da547dd1fdd
SDSS-Computing-Studies/004d-for-loops-ye11owbucket
/task2.py
641
4.53125
5
#! python3 """ ###### Task 2 Ask the user to enter a name. Check the name against a tuple that contains a series of names to see if it is a match. Use a for loop this time instead of a single if with multiple logical operators (2 points) inputs: str name outputs: "That name is in the list" "That name is not in the list" example: Enter a name: Grace That name is not on the list example: Enter a name: Lebron That name is on the list """ nameList = ("Lebron","Kobe","Michale","Shaq","Dennis") x = str(input("Enter a name: ")) if x in nameList: print( "That name is on the list") else: print("That name is not on the list")
true
4aabe2d5467949defed829b8b6dffdeb618ab242
zenyuca/study-python3
/OOP/Property.py
742
4.21875
4
# @property 将类的方法变成属性调用 class Student(object): @property def name(self): return self.__name @name.setter def name(self, name): if isinstance(name, str): self.__name = name else: raise TypeError('name 应该是一个 String') # hello 属性为只读 @property def hello(self): print('Hello %s! Welcome to Python world!' % self.__name) s = Student() s.name = 'Jack' # 像属性调用一样的调用设置方法 name = s.name # 像获取属性一样地调用获取方法 print(name) # hello 看起来像是一个属性,背后绑定的却是一个方法 s.Hello # => Hello Jack! Welcome to Python world!
false
b80db295c6c059974528c04d32ea51c2a894244f
cbuie/ThinkPython
/code/cb_tuples.py
2,365
4.25
4
''' Tuples are immutable A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable. ''' s = 'a' t = 'a', # a tuple of one needs comma else it is a str print type(s), type(t) t = 'a', 'b', 'c' # or t = ('a', 'b', 'c') # not necessary print t, type(t) # creating multiple tuples at the same time is as easy as: a, b, c = 'one', 'two', 3 print a, b, c def sumIt(x): result = 0 for i in x: result = + i return result def sum_all(*args): return sum(args) def sum_all(*args): return sum(args) print sum_all(1, 2, 3) print sum_all(1, 2, 3, 4, 5) print sum_all(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ''' zip is a built-in function that takes two or more sequences and zips them into a list of tuples where each tuple contains one element from each sequence. In Python 3, zip returns an iterator of tuples, but for most purposes, an iterator behaves like a list. ''' s = 'abc' t = [0, 1, 2] z = zip(s, t); print z # If the sequences are not the same length, the result has the length of the shorter one. print(zip('anne', 'elk')) # You can use tuple assignment in a for loop to traverse a list of tuples: t = [('a', 0), ('b', 1), ('c', 2)] for letter, number in t: print number, letter ''' If you combine zip, for and tuple assignment, you get a useful idiom for traversing two (or more) sequences at the same time. For example, has_match takes two sequences, t1 and t2, and returns True if there is an index i such that t1[i] == t2[i]: ''' def has_match(t1, t2): for x, y in zip(t1, t2): if x == y: return True return False # If you need to traverse the elements of a sequence and their indices, you can use the built-in function enumerate: for index, element in enumerate('christopher Buie'): print index, element # For example, suppose you have a list of words and you want to sort them from longest to shortest: def sort_by_length(words): t = [] for word in words: t.append((len(word), word)) t.sort(reverse=True) res = [] for length, word in t: res.append(word) return res t = [] for i in l: t.append((len(i),i)) print t import sys sys.path.append( '/Users/chrisbuie/PycharmProjects/ThinkPython/code')
true
d613a753c4b4b4aaade01203fda9cda6f3a62776
mecozma/100DaysOfCode-challenge
/weekly-challenge/week1/simple-grep.py
927
4.40625
4
""" Given a filename and a string on the commandline, print all lines from the file that contain the string. Example: grep world input.txt input.txt Hello world, today is Monday and I say hello to the world. Output: Hello world, to the world. """ import sys if len(sys.argv) < 3: print("Please provide a string and the source list!") exit() string = sys.argv[1] source_file = sys.argv[2] output = "" # Open the source file. with open(source_file, "r") as file: # Iterate each line in the file. for line in file: # Check if the the passes string is contained by the text line. if string.lower() in line.lower(): # If the condition is true concatenate the line with he output var. output += line + "\n" print(output) # Write the output value to the output.txt file. with open("output.txt", "a") as output_data: output_data.write(output)
true
70e9826569336e1d6c1b86aa026e830101528675
mecozma/100DaysOfCode-challenge
/day5/q16.py
259
4.125
4
def square_odd(numbers): return [i * i for i in numbers if i % 2 != 0] list_of_numbers = [int(i) for i in input("Type a sequence of comma-separated" + "numbers: ").split(",")] print(square_odd(list_of_numbers))
true
591cfe05c69919d90baea19f133462cdf70c65fa
mecozma/100DaysOfCode-challenge
/day2/q8.py
476
4.34375
4
""" Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world """ def reverse_string(): input_value = [i for i in input("Type a phrase: ").split(" ")] input_value.sort() return ",".join(input_value) print(reverse_string())
true
511cb77a0a73748a3a7d842ffc9cb85f28da6369
mecozma/100DaysOfCode-challenge
/day5/q17.py
1,209
4.15625
4
account = 0 question = input("To make a deposit type D, to withdraw money press W, to see" + "the ballance press B to exit the app type exit: ") while True: if question == "end": break elif question.upper() == "D": value = input("Please type the value you want to deposit: ") account += int(value) question = input("To make a deposit type D, to withdraw money press W, to see" + "the ballance press B to exit the app type exit: ") elif question.upper() == "W": value = input("Please type the value you want to widraw: ") account -= int(value) question = input("To make a deposit type D, to withdraw money press W, to see" + "the ballance press B to exit the app type exit: ") elif question.upper() == "B": print("You have $:", account) question = input("To make a deposit type D, to withdraw money press W, to see" + "the ballance press B to exit the app type exit: ") else: print("We couldn't process your transaction!") question = input("To make a deposit type D, to withdraw money press W, to see" + "the ballance press B to exit the app type exit: ")
false
85abc53f25c97a8a12103ae4637380ed907ed4c0
prachipradhan12/Core-Python-Programs
/postitiveandnegative.py
488
4.15625
4
#wapp to read array of n integers from user #and count number of positive integers , number of #integers and number of 0's import array data=array.array('i',[]) n= int(input("Enter the number of elements ")) for i in range(n): ele=int(input("Enter the data ")) data.append(ele) np=0 nn=0 nz=0 for d in data: if( d > 0): np=np+1 elif(d < 0): nn=nn+1 else: nz=nz+1 print("Number of positive elements ",np) print("Number of negative elements ",nz) print("Number of 0's ",nz)
true
b5e5c6b195b945dc51aeedb2ea36e4cb5878cfc6
cxysailor/my-learning-note
/data_analisis/matplotlib_figure_basic.py
1,250
4.40625
4
#!/usr/bin/env python3 # encoding: utf-8 # coding style: pep8 # ==================================================== # Copyright (C) 2020 cxysailor-master All rights reserved. # # Author : cxysailor # Email : cxysailor@163.com # File Name : matplotlib_figure_basic.py # Last Modified : 2020-12-15 22:26 # Describe : # # ==================================================== from matplotlib import pyplot as plt import numpy as np import pandas as pd x = np.linspace(0, 2, 100) # there are essentially two ways to use Matplotlib: # Explicitly create figures and axes, and call methods on them (the "object-oriented (OO) style") # Rely on pyplot to automatically create and manage the figures and axes, and use pyplot functions for plotting # So one can do (OO-style) fig, ax = plt.subplots() ax.plot(x, x, label='linear') ax.plot(x, x ** 2, label='quadratic') ax.plot(x, x ** 3, label='cubic') ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_title('Simple Plot') ax.legend() # or (pyplot-style) plt.figure(num=2) plt.plot(x, x, label='linear') plt.plot(x, x ** 2, label='quadratic') plt.plot(x, x ** 3, label='cubic') plt.xlabel('x label') plt.ylabel('y label') plt.title('Simple Plot') plt.legend() plt.show()
true
6f46917c9f1f738cd2b11ae4cb892ec0226f2c3a
krishnakesari/Math-for-Machine-Learning-Py
/Python Built In fuctions.py
2,607
4.15625
4
# First we will explore python's built in match functions # Standard libraries - built in functions & built in imported modules # Boolean isRaining = True isSunny = False # logical operator - AND, OR, NOT if isRaining and isSunny: print("you might see a rainbow") if isRaining or isSunny: print("It might be rainy or sunny") if not isSunny: print("It is Rainy") # Example: ages = [12,18, 39, 7, 2] for age in ages: isAdult = age > 17; if not isAdult: print("Being " + str(age) + " does not make you adult") # Comparision Operators ## Greater than, equal to , less than print(10 < 75) if 10 < 75: print("This is bigger") kitten = 10 tiger = 76 if kitten < tiger: print("Tiger is bigger") mouse = 1 if mouse < kitten and mouse < tiger: print("mouse is smaller") # calculating length: firstName = "Taylor" print(len(firstName)) firstName.__len__() ages = [0,11,43] print(len(ages)) i=0 for i in range(0, len(ages)): print(ages[i]) candyCollection = {"bob": 10, "mary": 15} print(len(candyCollection)) # Range function: numberedContestants = range(30) print(len(numberedContestants)) for c in list(numberedContestants): print("Contestant " + str(c) + " is here") luckyWinners = range(7,30,5) print(list(luckyWinners)) # Minimum and Maximum values playerOneScore = 10 playerTwoScore = 20 print(min(playerOneScore, playerTwoScore)) print(min(-1, 5, -10)) print(min("Angela", "Bob")) print(max(playerOneScore, playerTwoScore)) print(max(-1, 5, -10)) print(max("Angela", "Bob")) # Rounding, absolute value and exponents myscore = 36.6 print(round(myscore)) myscore2 = 14.4 print(round(myscore2)) trip = -1.4 print(round(trip)) ## Average value distanceaway = -13 print(abs(distanceaway)) ## Exponents (base, exponent) chanceT = 0.5 inARowT = 3 print(pow(chanceT, inARowT)) # Sorted function - lists, tuples, strings, dictionaries pointsInaGame = [0, -10, 15, -2, 1, 12] sortedGame = sorted(pointsInaGame) print(sortedGame) print(sorted(pointsInaGame, reverse = True)) kids = ["sue", "Jerry", "Lynda"] print(sorted(kids)) kids2 = ["sue", "jerry", "Lynda"] print(sorted(kids2)) print(sorted("My favorite mouse is jerry".split(), key=str.upper)) students = [('alice', 'B', 32), ('Kate', 'C', 48)] print(sorted(students, key = lambda students:students[1])) # Type r = range(0,30) print(type(r)) ## isinstance class car: pass class truck(car): pass c = car() t = truck() print(type(c)) print(type(t)) print(type(c) == type(t)) print(isinstance(c, car)) print(isinstance(t, car)) # truck inherits from car
true
944d3b59e0ca33b26ef7dba516528b391d1c53a9
syfiawoo/30DayLeetCodeChallenge
/April/Day8/linked_list_middle.py
1,140
4.1875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def append_node(self, item: int): # create the new node to be added to end of list new_node = ListNode(item) # check to see if list is empty # head should become the new_node if not self.head: self.head = new_node else: # self.tail.next = new_node self.tail = new_node class Solution: @staticmethod def middle_node(head: ListNode) -> ListNode: """ :param head: :return: middle node """ curr = head # start from the first item m_list = [] # an empty list to which nodes would be appended # add all elements in linked list to our list while curr: m_list.append(curr) # add current node to list curr = curr.next # advance current node to next mid = len(m_list) // 2 # find middle of list return m_list[mid]
true
944431bcff6f0129afa64a0473ea0b38af8b391d
mbutkevicius/Functions_Intro
/variable_number_of_args.py
604
4.15625
4
def sum_numbers(*numbers: float) -> float: """Find the sum of a variable amount of numbers.""" result = 0 for i in numbers: result += i return result print(sum_numbers(1, 2, 3)) print(sum_numbers(8, 20, 2)) print(sum_numbers(12.5, 3.147, 98.1)) print(sum_numbers(1.1, 2.2, 5.5)) # Oops, I messed up. I didn't write the code as concisely which I will do now. # values = 1, 2, 3 # print(sum_numbers(*values)) # # values = 8, 20, 2 # print(sum_numbers(*values)) # # values = 12.5, 3.147, 98.1 # print(sum_numbers(*values)) # # values = 1.1, 2.2, 5.5 # print(sum_numbers(*values))
true
49303041b96a1f261056948abaf41534a7b62264
juliaviolet/Google_IT_Python_Crash_Course
/Palindrome.py
698
4.375
4
def is_palindrome(input_string): # We'll create two strings, to compare them new_string = "" reverse_string = "" input_string=input_string.lower() input_string=input_string.replace(" ","") # Traverse through each letter of the input string for letter in input_string: # Add any non-blank letters to the # end of one string, and to the front # of the other string. if letter !="": new_string = input_string reverse_string = new_string[::-1] # Compare the strings if reverse_string==new_string: return True return False print(is_palindrome("Never Odd or Even")) # Should be True print(is_palindrome("abc")) # Should be False print(is_palindrome("kayak")) # Should be True
true
dd03c8b4653a6b10a0d945fe423f152c37432452
shashankvishwakarma/Python-Basic
/DataTypes.py
2,080
4.28125
4
print('============ Number data type =================') division = 8 / 5 # division always returns a floating point number print('division always returns a floating point number', division); division = 17 / 3 # classic division returns a float print('classic division returns a float... ', division); division = 17 // 3 # floor division discards the fractional part print('floor division discards the fractional part... ', division); division = 17 % 3 # the % operator returns the remainder of the division print('the % operator returns the remainder of the division... ', division) print('============ String data type =================') text = 'spam eggs' # single quotes print('single quotes... ', text); text = 'doesn\'t' # use \' to escape the single quote... print('Use of escape the single quote... ', text) text = '"Yes," they said.' # ...or use double quotes inside single quote print('use double quotes inside single quote... ', text) text = 'First line.\nSecond line.' # \n means newline print('newline ... ', text) print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) text = ('Put several strings within parentheses ' 'to have them joined together.') print('string in several line with parentheses... ', text) ''' +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 ''' text = 'Python' print('character in position 0... ', text[0]) # print('character in position 6... ',text[6]) print('last character ... ', text[-1]) print('second last character... ', text[-6]) print('characters from position 0 (included) to 2 (excluded)... ', text[0:2]) print('characters from position 0 (included) to 2 (excluded last 2 char)... ', text[0:-2]) print('character from the beginning to position 2 (excluded)... ', text[:2]) print('characters from position 4 (included) to the end... ', text[4:]) print('characters from the second-last (included) to the end... ', text[-2:])
true
737a2a373a3dd50e4f9977a5ec27753f99729565
jJayyyyyyy/python_learning
/code/oop/attr_instance_or_class.py
1,005
4.4375
4
#由于Python是动态语言,根据类创建的实例可以任意绑定属性 #或者通过self变量,或者通过实例变量。 class Student(object): def __init__(self, name): self.name = name s = Student('Bob') s.score = 90 print(s.name, s.score) print() #但是,如果Student类本身需要绑定一个属性呢? #可以直接在class中定义属性,这种属性是类属性,归Student类所有 class Student(object): name = 'Stu' #当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到。来测试一下 s = Student() print(s.name) print(Student.name) s.name = 'Bob' print(s.name) print(Student.name) print() del s.name print(s.name) ''' 从上面的例子可以看出,在编写程序的时候, 千万不要把实例属性和类属性使用相同的名字, 因为相同名称的实例属性将屏蔽掉类属性, 但是当你删除实例属性后,再使用相同的名称, 访问到的将是类属性。 '''
false
4d007804b8c00fc1485317b62737d86abacc12aa
lakazzie87/WeThinkCode_-Semester_1_work
/submission_001-pyramids/triangle_Test.py
407
4.28125
4
height = int(input("Enter the height: ")) x = 0 y = 0 for x in range(0, height): for y in range(0, height): if y == 0 or x == (height-1) or x == y: print("*", end="") else: print(end=" ") print() height = 0 for x in range(1, pyramid+1) # rows for y in range(1, pyramid): print(' ', end= '') while(height != (2 * x - 1)):
true
199c699af95cbbf5fda0c9f3e0631de31e18abdf
isabelaaug/Python
/loop_for.py
2,015
4.15625
4
""" loop for nome = 'isabela augusta' lista = [1, 3, 5, 4] numeros = range(1, 10) enumerate((0, 'i'), (1, 's'),...) for valor, letra in enumerate(nome): print(valor) ------------------- for letra in nome: # iterando em uma string print(letra) for letra in nome: # iterando em uma string na mesma linha print(letra, end='') ------------------------------ for numero in lista: # iterando em uma lista print(numero) ------------------------ for numeros_range in numeros: # iterando em uma range 1 à 9 (valor final -1) print(numeros_range) for indice, letra in enumerate(nome): print(nome[indice]) for indice, letra in enumerate(nome): print(letra) for _, letra in enumerate(nome): -- o underline significa que descartamos o valor print(letra) for valor, letra in enumerate(nome): print(valor) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 for valor in enumerate(nome): print(valor) (0, 'i') (1, 's') (2, 'a') (3, 'b') (4, 'e') (5, 'l') (6, 'a') (7, ' ') (8, 'a') (9, 'u') (10, 'g') (11, 'u') (12, 's') (13, 't') (14, 'a') qntd = int(input('Quantas vezes ele deve rodar?')) for n in range(1, qntd+1): print(f'Imprimindo {n}') qntd = int(input('Quantas vezes ele deve rodar? ')) soma = 0 for n in range(1, qntd+1): num = int(input(f'Informe o valor {n}/{qntd}: ')) soma = soma + num print(f'A soma é {soma}') nome = 'isabela' nome + ' augusta' # concatenando no terminal BREAK for numero in range(1, 11): if numero == 6: break else: print(numero) print('sai do loop') """ lista = [] cont = 0 qtd = int(input('quantos numeros voce deseja digitar ? : ')) for c in range(qtd): num = int(input('digite um numero : ')) lista.append(num) print(f'Maior número: {max(lista)}') print(f'Menor número: {min(lista)}') """ adicionando emojis https://apps.timwhitlock.info/emoji/tables/unicode # Original U+1F60D # modificado U0001F60D for _ in range(4): for numero in range(1, 11): print('\U0001F60D' * numero) """
false
40aa61ceee77e122cc19f418b6f5a48be33830a8
isabelaaug/Python
/default_dict.py
654
4.125
4
""" Collections Default Dict https://docs.python.org/3/library/collections.html dicio = {'curso': 'python'} print(dicio['curso']) print(dicio['outro']) # key error -permite por meio de um lambda criar um valor default para caso a chave não tenha um valor definido e caso a chave não exista ela será criada também com o valor default atribuido -lambdas são funções sem nome, que podem ou não receber parâmetros de entrada e retornar valores. """ from collections import defaultdict dicionario = defaultdict(lambda: 0) dicionario['curso'] = 'python' print(dicionario) print(dicionario['curso']) print(dicionario['outro']) print(dicionario)
false
0463678cca55e7ffe042b23b30e47e86f3396bcd
isabelaaug/Python
/named_tuple.py
526
4.15625
4
""" Named Tuple -é uma tupla que podemos especificar nome e parametros """ from collections import namedtuple dog1 = namedtuple('cachorro', 'idade raca nome') dog2 = namedtuple('cachorro', 'idade, raca, nome') dog3 = namedtuple('cachorro', ['idade', 'raca', 'nome']) barack = dog3(idade=3, raca='SRD', nome='Barack') print(barack) print(barack[0]) print(barack[1]) print(barack[2]) print(barack.idade) print(barack.raca) print(barack.nome) print(barack.index('SRD')) # indice print(barack.count('SRD')) # repetição
false
c01a42fc7857d96502b4e2e575e14479c499de05
isabelaaug/Python
/reversed.py
641
4.40625
4
""" Reversed - inverte o iteravel """ lista = [1, 2, 5, 8, 7, 4] print(list(reversed(lista))) # [4, 7, 8, 5, 2, 1] print(tuple(reversed(lista))) # (4, 7, 8, 5, 2, 1) print(set(reversed(lista))) # {1, 2, 4, 5, 7, 8} não temos como definir ordem de um conjunto for letra in reversed('Isabela Augusta'): print(letra, end='') # end para escrever tudo na mesma linha -- atsuguA alebasI print(' ') print(''.join(list(reversed('Isabela Augusta')))) # join junta uma lista de caracteres em uma string -- atsuguA alebasI print('Isabela Augusta'[::-1]) for n in reversed(range(0, 11)): print(n) for n in range(10, -1, -1): print(n)
false
2a2ff0d4908102d56a306dd384e33111c034fa62
isabelaaug/Python
/tipo_numerico.py
2,591
4.28125
4
""" Tipo numerico 5/2 = 2.5 -- resulta em um numero real 5//2 = 2 -- resulta em um numero inteiro (int(5/2)) 5 % 2 = 1 -- modulo ou resto da divisão 2 ** 2 = 4 -- potência (2^2) 1_000_000 = 1000000 -- facilita visualização num = 2 num + 1 = 3 -- serve apenas para um calculo num += 1 = 3 ou num = num + 1 = 3 -- incrementa a variável type(num) <class 'int'> dupla atribuição: valor1, valor2 = 2, 3 ---------------------------------- tipo float / real / decimal valor = 2.3 numero complexo 23j -- numero+j arredondar float: num = 3.143424332 num_2 = round(num, 2) print(num) print(num_2) ----------------------------- tipo Booleano True or False ativo = True Negação (NOT) print(not ativo) -- False Ou (or) T OR T = T T OR F = T F OR T = T F OR F = F E (And) T E T = T T E F = F F E T = F F E F = F ------------------------- TIPO String frase = 'isabela augusta" print(frase.split()) = 'isabela''augusta'-- transforma em uma lista vetor[0-...] frase[0-6] print(frase.split()[0]) = 'isabela' print(frase.split()[1]) = 'augusta' print(frase[0:3]) = isa -- slice de string inverte a string print(frase[::-1]) -- vai do primeiro ao ultimo elemento e inverte substitui caracteres print(frase.replace('i','y') = ysabela ---------------------- Escopo de variaveis variaveis globais e locais - se temos duas variaveis com o mesmo nome, a varialvel local irá sobrepor a global em uma função - funçoes necessitam de variaveis locais, do contrario é necessário avisar com 'global <nome_variavel_global>' def diz_oi(instrutor): instrutor = 'isa' return f'oi {instrutor}' instrutor = 'bela' print(diz_oi(instrutor)) --------------------------------- Tipo NONE tipo sem tipo (class 'NoneType') ou tipo vazio é sempre especificado com a primeira maiuscula podemos utiliza la quando não sabemos qual será seu valor final numeros = None """ num_1 = int(input('Digite um inteiro: ')) print(f'O inteiro digitado foi {num_1}') num_2 = float(input('Digite um numero real: ')) print(f'O numero digitado foi {num_2}') num_31 = int(input('Digite o primeiro numero: ')) num_32 = int(input('Digite o segundo numero: ')) num_33 = int(input('Digite o terceiro numero: ')) print(f'A soma é igual a {num_31 + num_32 + num_33}') num_4 = float(input('Digite um numero: ')) print(f'O quadrado desse numero é igual a {num_4 ** 2}') num_5 = float(input('Digite um numero: ')) print(f'A quinta parte desse numero é igual a {num_5 / 5}') num_6 = float(input('Digite uma temperatura em graus Celsius: ')) print(f'Conversão para Fahrenheit: {num_6 * (9 / 5) + 32}')
false
bd4e2b80f9133c0bb180727fb83e9512ab081dc8
fredy-glz/Ejercicios-de-Programacion-con-Python---Aprende-con-Alf
/02_Condicionales/10_CondicionalesPython.py
2,121
4.28125
4
# JOSE ALFREDO ROMERO GONZALEZ # 12/10/2020 respuesta = input("Vegetariana o no vegetariana? (V/NV): \n") if respuesta.upper() == 'V': print("**** INGREDIENTES ****") print("> Pimiento\n> Tofu") tipo = "vegetariana" ingrediente = input("Ingrese el ingrediente escogido: \n") if ingrediente == "Pimiento": escogido = ingrediente elif ingrediente == "Tofu": escogido = ingrediente else: ingrediente = "" elif respuesta.upper() == 'NV': print("**** INGREDIENTES ****") print("> Peperoni\n> Jamón\n> Salmón") tipo = "no vegetariana" ingrediente = input("Ingrese el ingrediente escogido: \n") if ingrediente == "Peperoni": escogido = ingrediente elif ingrediente == "Jamón": escogido = ingrediente elif ingrediente == "Salmón": escogido = ingrediente else: ingrediente = "" else: ingrediente = "" if ingrediente == "": print("Tipo de pizza o ingrediente no disponible") else: print("*** TICKET ***") print("Su pizza es de tipo " + tipo + " y los ingredientes son queso mozzarella, tomate y " + ingrediente) # SOLUCION DE https://aprendeconalf.es/ # Presentación del menú con los tipos de pizza print("Bienvenido a la pizzeria Bella Napoli.\nTipos de pizza\n\t1- Vegetariana\n\t2- No vegetariana\n") tipo = input("Introduce el número correspondiente al tipo de pizza que quieres:") # Decisión sobre el tipo de pizza if tipo == "1": print("Ingredientes de pizzas vegetarianas\n\t 1- Pimiento\n\t2- Tofu\n") ingrediente = input("Introduce el ingrediente que deseas: ") print("Pizza vegetariana con mozzarella, tomate y ", end="") if ingrediente == "1": print("pimiento") else: print("tofu") else: print("Ingredientes de pizzas no vegetarianas\n\t1- Peperoni\n\t2- Jamón\n\t3- Salmón\n") ingrediente = input("Introduce el ingrediente que deseas: ") print("Pizza no vegetarina con mozarrella, tomate y ", end="") if ingrediente == "1": print("peperoni") elif ingrediente == "2": print("jamón") else: print("salmón")
false
480b429f99f6e44987cb4afe9c12e3a8df9596aa
robg128/book_python_crash_course
/book_python_crash_course/ch10/remember_me.py
1,276
4.125
4
# (1) Create program to remember username # import json # ## Define initial variables for program # filename = 'username.json' # try: # ## Read file and print username # with open(filename, 'r') as f_obj: # username = json.load(f_obj) # except FileNotFoundError: # ## Write username to file # w_username = input('What is your name, please? ') # with open(filename, 'w') as f_obj: # json.dump(w_username, f_obj) # print('We will remember you when you come back ' + username + '!') # else: # print('Welcome back, ' + username) # (2) Refactor code import json def get_stored_username(): '''Obtain stored user name''' filename = 'username.json' try: with open(filename, 'r') as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return username def get_new_username(): '''Create new username''' username = input('What is your name? ') filename = 'username.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username def greet_user(): '''Create function to greet the user by name''' username = get_stored_username() if username: print('Welcome back, ' + username) else: username = get_new_username() print('We will remember you next time, ' + username + '.') greet_user()
true
f19446488a33dc28604ddf7f28a4e16d18eb9c6c
robg128/book_python_crash_course
/book_python_crash_course/ch08/formatted_name.py
1,086
4.125
4
# (1) Using the return statement to send value from inside function, back to # the line that called the function... # def get_formatted_name(first_name, last_name): # '''Return a full name neatly formatted''' # full_name = first_name + ' ' + last_name # return full_name.title() # f_name = input('What is your favorite musicians first name? ') # l_name = input('What is your favoriate musicians last name? ') # musician = get_formatted_name(f_name, l_name) # print(musician) # (2) Incorporating Optional Arguments def get_formatted_name(first_name, last_name, middle_name = ''): '''Return a full name neatly formatted''' if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name else: full_name = first_name + ' ' + last_name return full_name.title() f_name = input('What is your favorite musicians first name? ') m_name = input('What is your favorit musicians middle name? ') l_name = input('What is your favoriate musicians last name? ') musician = get_formatted_name(f_name, l_name, m_name) print(musician)
true
5fc96e7eb7eebb557559329ec293d69568d6092a
robg128/book_python_crash_course
/book_python_crash_course/ch05/conditional_tests.py
668
4.1875
4
# (5-2) More Conditional Tests - print(len('This is a great day') == len('Tthis is not a bad day')) string_1 = 'Jack and Jill went up the Hill' string_2 = 'jack and jill went up the hill' print( string_1.lower() != string_2) number_0 = 10 number_1 = 15 number_2 = 20 number_3 = 25 number_4 = 30 print(number_0 != number_1) print((number_1 + number_0) == number_3) print((number_1 <= number_2) and (number_0 <= number_4)) print((number_4 >= number_2*3) or (number_3 >= number_0**2)) cars = ['bmw', 'audi', 'nissan', 'ford', 'gmc'] print('Is Nissan in the list of cars') print('nissan' in cars) print('Is GMC not in the list of cars') print('gmc' not in cars)
true
3c9d84105d232233e056df651901a862a8e873f0
nina-mir/w3-python-excercises
/pandas/DataFrames.py
1,699
4.1875
4
import pandas as pd import numpy as np # 1. Write a Pandas program to get the powers of an array values element-wise. Go to the editor # Note: First array elements raised to powers from second array # Sample data: {'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]} # Expected Output: # X Y Z # 0 78 84 86 # 1 85 94 97 # 2 96 89 96 # 3 80 83 72 # 4 86 86 83 def prob_1(data): return pd.DataFrame(data) print(prob_1({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]})) # 2. Write a Pandas program to create and display a DataFrame from a specified dictionary data which has the index labels. Go to the editor # Sample Python dictionary data and list labels: # exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'], # 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], # 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], # 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} # labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] # Expected Output: # attempts name qualify score # a 1 Anastasia yes 12.5 # b 3 Dima no 9.0 # .... i 2 Kevin no 8.0 # j 1 Jonas yes 19.0 exam_data = { 'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],\ 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],\ 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],\ 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] def prob_2(data, labels): return pd.DataFrame(data=data, index=labels) print(prob_2(exam_data, labels))
true
5a9dec0befcbe39f6b1afaf7855d9038a434357c
anudeep404/excercise_classes
/class_test_1_definations.py
641
4.1875
4
#Defining a class class Computer: #Defining a Method #Attributes ---> Variables #Behaviour ----> Methods (Function) def config(self): print("i5, 16gb, 1TB") com1 = Computer() com2 = Computer() #since the Method is within a class, we have to call the Method by prefixing it with the class name. #You also have to pass objects to it, like com1 Computer.config(com1) #Hey Computer, show me your configuration for com2 Computer.config(com2) #Universally used syntax #We are using object itself to call the object. #It works because, com1 belongs to class Computer and config belongs to it as well. com1.config() com2.config()
true