blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
01bdc3d5d6fe576ec1d509d7045e64f4029c634e | anooprerna/How-to-Solve-it-By-Computer-Solutions-in-Python | /algo2_4_5.py | 445 | 4.3125 | 4 | #Design an algorithm to simulate multiplication by addition. Your program should accept as input two integers (They may be zero, positive or negative).
def multiply(x,y):
if(y == 0):
return 0
if(y > 0 ):
return (x + multiply(x, y - 1))
if(y < 0 ):
return -multiply(x, -y)
x = int(input("Enter x: "))
y = int(input("Enter y: "))
print(multiply(x, y))
| true |
6ecc6704534d7355fa37d16197cba167afb6e96c | anooprerna/How-to-Solve-it-By-Computer-Solutions-in-Python | /algo2_8.py | 232 | 4.4375 | 4 | number = int(input("Enter a number to convert into octal: "))
result = ""
while number != 0:
remainder = number % 8
number = number // 8
result = str(remainder) + result
print("The octal representation is", result) | true |
7c3f48e68abc8147fba662bf6859b988c5519dc5 | anooprerna/How-to-Solve-it-By-Computer-Solutions-in-Python | /algo2_6_1.py | 479 | 4.15625 | 4 | import math
def Fibonacci():
n1 = int(input("Enter the first Fibonacci Number"))
n2 = int(input("Enter the second Fibonacci Number"))
diff = abs(n1 - n2)
print("Difference of numbers is", diff)
minimum = min(n1, n2)
print("Minimum of two numbers is", minimum)
if diff > minimum:
print("Numbers are not consecutive in Fibonacci series!")
else:
return n1 + n2
print("The resulting Fibonacci Number is", Fibonacci())
| true |
4ab97a4ba2066d720de86591ce07327dd89e7644 | eldydeines/flask-greet-calc | /calc/app.py | 1,194 | 4.15625 | 4 | """ Build a simple calculator with Flask, which uses URL query
parameters to get the numbers to calculate with.
Make a Flask app that responds to 4 different routes.
Each route does a math operation with two numbers, a and b,
which will be passed in as URL GET-style query parameters.
"""
import operations
from flask import Flask, request
app = Flask(__name__)
@app.route('/add')
def add_page():
"""Gets a & b, adds the two, returns answer"""
a = request.args.get("a")
b = request.args.get("b")
return str(operations.add(int(a), int(b)))
@app.route('/sub')
def subtract_page():
"""Gets a & b, subtracts the two, returns answer"""
a = request.args.get("a")
b = request.args.get("b")
return str(operations.sub(int(a), int(b)))
@app.route('/mult')
def multiply_page():
"""Gets a & b, multiplies the two, returns answer"""
a = request.args.get("a")
b = request.args.get("b")
return str(operations.mult(int(a), int(b)))
@app.route('/div')
def divide_page():
"""Gets a & b, divides the two, returns answer"""
a = request.args.get("a")
b = request.args.get("b")
return str(operations.div(int(a), int(b)))
| true |
1ba19c5665f1607a1075ec71d8474d98d5cc9965 | JacksonDudenhoeffer/FizzBuzz | /FizzBuzzClean.py | 380 | 4.1875 | 4 | #num is theholder for the printed number and tested for fizzbuzz
for num in range(1, 101):
#output is the holder for what will be printed
output = ""
#tests for a number divisible by 3
if num % 3 == 0:
output += "Fizz"
#tests for a number divisible by 5
if num % 5 == 0:
output += "Buzz"
#output is printed
print(output)
| true |
c71bf464ec94199ed2aab1c417ac3baa33e202ef | reepicheep/Python-Crash-Course-2-ed-by-Mathes-E. | /Chapter3/3.4_guest_list.py | 657 | 4.375 | 4 | # If you could invite anyone, living or deceased, to dinner, who would you invite?
# Make a list that includes at least three people you’d like to invite to dinner.
# Then use your list to print a message to each person, inviting them to dinner.
guest_list = ["Peter", "Lucy", "Reepicheep"]
invite_peter = f"Dear {guest_list[0]}, I would like to invite you to dinner on Saturday at 8 pm."
invite_lucy = f"Dear {guest_list[1]}, I would like to invite you to dinner on Saturday at 8 pm."
invite_reepicheep = f"Dear {guest_list[-1]}, I would like to invite you to dinner on Saturday at 8 pm."
print(invite_peter)
print(invite_lucy)
print(invite_reepicheep) | true |
902486036e31ba7e0ac2a62fff2933fbe2bc921c | EnglishIllegalImmigrant/project1 | /project1-v1.py | 678 | 4.1875 | 4 | # Import modules
import random
# Define variables
computer_number = random.randint(1, 100)
tries = 3
# While user has tries left, repeat this block of code
while(tries != 0):
user_number = int(input('Guess a number between 1-100: '))
if(user_number == computer_number):
print('Congratulations! You won a small loan of a billion dollars!')
tries = 0
elif(user_number > computer_number):
print('You guessed higher.')
tries = tries - 1
print('You have', tries, 'tries left.')
elif(user_number < computer_number):
print('You guessed lower.')
tries = tries - 1
print('You have', tries, 'tries left.')
| true |
b701d5b68225a7a7614c0cd3fc4ba8fa575ab812 | RaviSankarRao/PythonBasics | /5_Lists.py | 891 | 4.1875 | 4 |
random = ["Ravi", 2, True]
friends = ["Ravi", "Sankar", "Rao", "Dasari", "John", "Doe"]
lucky_numbers = [4, 8, 10, 16, 23, 42]
print(friends)
print(friends[2])
print(friends[3].upper())
friends = ["Ravi", "Sankar", "Rao", "Dasari", "John", "Doe", "John"]
lucky_numbers = [42, 8, 15, 10, 23, 4]
# adding two lists
friends.extend(lucky_numbers)
print(friends)
# adding item to list
friends.append("New value")
print(friends)
# insert item to list
friends.insert(1, "New inserted value")
print(friends)
# remove item
friends.remove("New inserted value")
print(friends)
# pop an item - Pops the last item
friends.pop()
print(friends)
# find item index
print(friends.index("Dasari"))
# count of repeated items
print(friends.count("John"))
# sorting a list
lucky_numbers.sort()
print(lucky_numbers)
friends2 = friends.copy()
print(friends2)
# clear list
friends.clear()
print(friends) | true |
194c9f21ad1105585452d5ce543b80b6ecfac5e1 | xlui/PythonExamples | /Sqlite/sqlite.py | 2,384 | 4.1875 | 4 | # A simple example to use sqlite
import sqlite3
database_name = 'Sqlite.db'
# connect
connect = sqlite3.connect(database_name)
print("Successfully connect to database [{}]\n".format(database_name))
cursor = connect.cursor()
# delete exist table
try:
cursor.execute("DROP TABLE company")
except sqlite3.OperationalError as e:
print("No such table: company")
# create table
print("Now create table: company")
cursor.execute("""CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);""")
connect.commit()
print('Successful!\n')
# insert data into database
print('Now insert data into database.')
cursor.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00 )")
cursor.execute("INSERT INTO COMPANY VALUES (2, 'Allen', 25, 'Texas', 15000.00 )")
cursor.execute("INSERT INTO COMPANY VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )")
cursor.execute("INSERT INTO COMPANY VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )")
connect.commit()
print('Successful!\n')
# query data
print('Now query data from database:')
results = cursor.execute("select id, name, address, salary from COMPANY")
print("Now, data in database is:")
for row in results:
print("ID =", row[0])
print("Name =", row[1])
print("Address =", row[2])
print("Salary =", row[3])
print()
# update data
print('Now update data in database:')
cursor.execute("update COMPANY set SALARY = 25000.00 WHERE ID = 1")
connect.commit()
print("Total number of rows updated:", connect.total_changes)
results = cursor.execute("SELECT id, name, ADDRESS, salary FROM COMPANY")
print("Now, data in database is:")
for row in results:
print("ID =", row[0])
print("Name =", row[1])
print("Address =", row[2])
print("Salary =", row[3])
print()
# delete data
print('Now delete data from database:')
cursor.execute('delete FROM COMPANY where id = 2')
connect.commit()
print("Total number of rows deleted:", connect.total_changes)
results = cursor.execute("select id, name, address, salary FROM COMPANY")
print("Now, data in database is:")
for row in results:
print("ID =", row[0])
print("Name =", row[1])
print("Address =", row[2])
print("Salary =", row[3])
print()
connect.close()
| true |
deadca5763769bd61cc6dd01f40329880f1a21ea | May-Beu/OpenCV-for-NObbies-using-Python | /open cv/3.how to get image information in open cv/image_info.py | 783 | 4.15625 | 4 | #in this section i will show you how to see or get information about image
#the information will tell you the the height and width of image in terms of pixel
import cv2
image=cv2.imread("messi.jpg")
cv2.imshow("output image",image)
#now to see the information of image we will use "shape ()"module/function of opencv
#it will give the information in tuple
#it will give the information of Pixel in Width
#it will give the information of Pixel in Height
#it will give the information of layer
#it gives the output as (height,width,layer)
print(image.shape)
#if we want to print the height and width seprate
print("Height Pixel Value: ",image.shape[0]) #here 0,1 represent the index location in tuple
print("Height Pixel Value: ",image.shape[1])
cv2.waitKey(0)
cv2.distroyAllWindow() | true |
8a3af32afde6c59e1810e65a0a73939a572ee9b8 | May-Beu/OpenCV-for-NObbies-using-Python | /open cv/2.how to write a image in open cv/image_write.py | 838 | 4.21875 | 4 | author:Mayank Priy
# In this section i will show you how you can write a image on directory.Here when we write a image it create a clone of image or we can say that it create a dupicate of image in directory where we stored this python file.
#we can change this directory by giving the file location where we want to save the clone of this image.
import cv2
image=cv2.imread("messi.jpg")
cv2.imshow("output image",image)
#now we will use "imwrite" module or function of open cv to create a clone of image
#we have to give the name of the clone image with extention of our choice like(.jpg,.png)
cv2.imwrite("clonemessi.jpg",image)# here we gave the name of our clone image with an extention (.jpg)
cv2.imwrite("clonemessi.png",image)#here we gave the name of our clone image with an extention (.png)
cv2.waitKey(0)
cv2.distroyAllWindow()
| true |
24fab305eedfb184890f98ef580e5a4f35201bc6 | gabrypol/algorithms-data-structure-AE | /longest_peak.py | 1,744 | 4.28125 | 4 | '''
Write a function that takes in an array of integers and returns the length of the longest peak in the array.
A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), at which point they become strictly decreasing. At least three integers are required to form a peak.
For example, the integers 1, 4, 10, 2 form a peak, but the integers 4, 0, 10 don't and neither do the integers 1, 2, 2, 0. Similarly, the integers 1, 2, 3 don't form a peak because there aren't any strictly decreasing integers after the 3.
Sample Input
array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
Sample Output
6 // 0, 10, 6, 5, -1, -3
'''
def longest_peak(input_list):
length_of_longest_peak = 0
for i, num in enumerate(input_list[1:len(input_list) - 1], 1):
left_idx = i - 1
right_idx = i + 1
if input_list[left_idx] < input_list[i] and input_list[right_idx] < input_list[i]:
current_peak_length = 3
while left_idx > 0 and input_list[left_idx] > input_list[left_idx - 1]:
current_peak_length += 1
left_idx -= 1
if left_idx < 1:
break
while right_idx < len(input_list) - 1 and input_list[right_idx] > input_list[right_idx + 1]:
current_peak_length += 1
right_idx += 1
if right_idx > len(input_list) - 1:
break
else:
continue
length_of_longest_peak = max(length_of_longest_peak, current_peak_length)
return length_of_longest_peak
my_list = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
print(longest_peak(my_list))
'''
Time: O(n)
Space: O(1)
''' | true |
18bdc25a236c8cb223e17f617ef77b5120be4a80 | shabnam49/Geeks_For_Geeks | /Easy/Level-order-traversal.py | 2,164 | 4.15625 | 4 | '''
You are given a tree and you need to do the level order traversal on this tree.
Level order traversal of a tree is breadth-first traversal for the tree.
Level order traversal of above tree is 1 2 3 4 5
Input:
First line of input contains the number of test cases T. For each test case, there will be only a single line of input which is a string representing the tree as described below:
The values in the string are in the order of level order traversal of the tree where, numbers denotes node values, and a character “N” denotes NULL child.
For example:
For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N
Output:
The function should print the level order traversal of the tree as specified in the problem statement.
Your Task:
You don't have to take any input. Just complete the function levelOrder() that takes the root node as parameter and returns an array containing the level order traversal of the given Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= T <= 100
1 <= Number of nodes<= 104
1 <= Data of a node <= 104
Example:
Input:
2
1 3 2
10 20 30 40 60 N N
Output:
1 3 2
10 20 30 40 60
Explanation:
Testcase1: The tree is
1
/ \
3 2
So, the level order would be 1 3 2
Testcase2: The tree is
10
/ \
20 30
/ \
40 60
So, the level order would be 10 20 30 40 60
'''
class Node:
def __init__(self, value):
self.left = None
self.data = value
self.right = None
# Your task is to complete this function
# Function should return the level order of the tree in the form of a list of integers
def levelOrder( root ):
if root is None:
return
q = []
l = []
q.append(root)
l.append(root.data)
while( len(q) > 0 ):
node = q.pop(0)
if(node.left != None):
q.append(node.left)
l.append(node.left.data)
if(node.right != None):
q.append(node.right)
l.append(node.right.data)
return l
| true |
6c1f8a9f78968c86a6be62b0527f598861d1cb10 | Jochizan/data-structure | /python/data_structure.py | 1,112 | 4.15625 | 4 | list = [1, 2, 3, 4, 5]
obj = {
'firs_name': 'Joan',
'last_name': 'Roca Hormaza'
}
print(list, obj)
messy_list = [13, 1, 2, 3, 11, 20, 9, 1, -10, 14]
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
# algoritmo más eficiente que el bubble sort
def sort_algorithm(list):
n = len(list)
print(list)
for i in range(0, n):
tmp = i
for j in range(i + 1, n):
if list[j] < list[tmp]:
tmp = j
swap(list, tmp, i)
# print(list)
print(list)
return list
sort_algorithm(messy_list)
def linearSearch(item, my_list):
found = False
position = 0
while position < len(my_list) and not found:
if my_list[position] == item:
found = True
position = position + 1
return found
bag = ['book', 'pencil', 'pen', 'note book', 'sharpener', 'rubber']
item = input('¿Cúal es el item que quiere buscar?\nIngrese su nombre: ')
itemFound = linearSearch(item, bag)
if itemFound:
print('Ese item se encuentra en su lista')
else:
print('Oops, ese item NO se encuentra en su lista')
| false |
c2860adfe169e898fe4f9d0319f00120a4e84653 | martinmeagher/UCD_Exercises | /Module5_Data_Manipulation_Pandas/Subsetting_Pivot_Tables.py | 1,240 | 4.15625 | 4 | # Import pandas using the alias pd
import pandas as pd
# import homelessness.csv
temperatures = pd.read_csv("temperatures.csv", parse_dates=["date"])
# Add a year column to temperatures
temperatures["year"] = temperatures["date"].dt.year
# Pivot avg_temp_c by country and city vs year
temp_by_country_city_vs_year = temperatures.pivot_table(values="avg_temp_c", index=["country", "city"], columns="year")
# See the result
print(temp_by_country_city_vs_year)
# Subset for Egypt to India
print(temp_by_country_city_vs_year.loc["Egypt":"India"])
# Subset for Egypt, Cairo to India, Delhi
print(temp_by_country_city_vs_year.loc[("Egypt", "Cairo"):("India","Delhi")])
# Subset in both directions at once
print(temp_by_country_city_vs_year.loc[("Egypt", "Cairo"):("India","Delhi"),"2005":"2010"])
# Get the worldwide mean temp by year
mean_temp_by_year = temp_by_country_city_vs_year.mean()
# Filter for the year that had the highest mean temp
print(mean_temp_by_year[mean_temp_by_year == mean_temp_by_year.max()])
# Get the mean temp by city
mean_temp_by_city = temp_by_country_city_vs_year.mean(axis="columns")
# Filter for the city that had the lowest mean temp
print(mean_temp_by_city[mean_temp_by_city == mean_temp_by_city.min()]) | true |
d898b9313802cf3e94b865d11e5cca38e4e30659 | martinmeagher/UCD_Exercises | /Module3_Intermediate_Python/2a_Dictionaries_Pt1.py | 844 | 4.34375 | 4 | # Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
# Get index of 'germany': ind_ger
ind_ger = countries.index('germany')
# Use ind_ger to print out capital of Germany
print(capitals[ind_ger])
# Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
# From string in countries and capitals, create dictionary europe
europe = { 'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }
# Print europe
print(europe)
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }
# Print out the keys in europe
print(europe.keys())
# Print out value that belongs to key 'norway'
print(europe['norway'])
| false |
19802898bc771ee8e0e4feb245714659b50f872f | kianaghassabi/Data-Structures- | /Sort Algorithms/selection_sort/selection_sort.py | 680 | 4.1875 | 4 | #defining the selection sort function
def Selection_sort(mylist):
for i in range (0,len(mylist)-1):
minimum=i #the element is set to the minumum
#checking whether the other elements are smaller than the current minimum
for j in range (i+1,len(mylist)):
if mylist[j] < mylist[minimum]:
minimum=j
#swapping the minimum element with the current min
temp=mylist[i]
mylist[i]=mylist[minimum]
mylist[minimum]=temp
return mylist
#defining list
mylist=[4,19,7,16,3,21,1,0,11,80]
#calling the sort function for the list
sorted=Selection_sort(mylist)
#displaying the sorted list
print(sorted)
| true |
d654c42cd075d7123b2f03260463bf80cc0a4abd | alexqfredrickson/code-examples | /gists/python3.7/sorts/mergesort.py | 1,345 | 4.46875 | 4 | """
complexity: О(n) -> O(n log n) -> O(n log n)
author: john von neumann; 1945
"""
def mergesort(arr):
"""
Returns a sorted array.
"""
if len(arr) <= 1:
return arr # because it's already sorted
# otherwise, sort the array. start by splitting the array into halves
unsorted_left_half = arr[0:(len(arr) // 2)]
unsorted_right_half = arr[(len(arr) // 2):len(arr)]
# recurse on each to obtain a sorted array - after all, mergesort() returns a sorted array
sorted_left_half = mergesort(unsorted_left_half)
sorted_right_half = mergesort(unsorted_right_half)
# merge the smaller, sorted arrays into a bigger one
combined_sorted_array = []
while len(sorted_left_half) > 0 and len(sorted_right_half) > 0:
if sorted_left_half[0] < sorted_right_half[0]:
combined_sorted_array.append(sorted_left_half[0])
sorted_left_half = sorted_left_half[1: len(sorted_left_half)]
else:
combined_sorted_array.append(sorted_right_half[0])
sorted_right_half = sorted_right_half[1: len(sorted_right_half)]
if len(sorted_left_half) > 0:
combined_sorted_array += sorted_left_half
if len(sorted_right_half) > 0:
combined_sorted_array += sorted_right_half
# return the combined sorted array
return combined_sorted_array | true |
cadb8f4806a39b7bb68088f3fadc9479cb2dcfeb | xent3/Python | /Sayı Dizmece/Sayı Dizmece.py | 1,000 | 4.125 | 4 | sayı1 = int(input("Lütfen 1.Sayıyı giriniz :"))
sayı2 = int(input("Lütfen 2.Sayıyı giriniz :"))
sayı3 = int(input("Lütfen 3.Sayıyı giriniz :"))
print("Hesaplanıyor....")
if (sayı1>sayı2 and sayı1>sayı3 and sayı2>sayı3):
print("Sayılar Büyükten Küçüğe {} > {} > {}".format(sayı1,sayı2,sayı3))
elif(sayı1>sayı2 and sayı1>sayı3 and sayı3>sayı2):
print("Sayılar Büyükten Küçüğe {} > {} > {}".format(sayı1, sayı3, sayı2))
elif(sayı2>sayı1 and sayı2>sayı3 and sayı1>sayı3):
print("Sayılar Büyükten Küçüğe {} > {} > {}".format(sayı2, sayı1, sayı3))
elif(sayı2>sayı1 and sayı2>sayı3 and sayı3>sayı1):
print("Sayılar Büyükten Küçüğe {} > {} > {}".format(sayı2, sayı3, sayı1))
elif(sayı3>sayı1 and sayı3>sayı2 and sayı1>sayı2):
print("Sayılar Büyükten Küçüğe {} > {} > {}".format(sayı3, sayı1, sayı2))
else:
print("Sayılar Büyükten Küçüğe {} > {} > {}".format(sayı3, sayı2, sayı1))
| false |
9e70dfa20270d0b1de36a6cde0487e185c54e710 | jguerrero10/misiontic2020R1 | /Modulo 1/Seccion 1.2/Operadores/programa3.py | 375 | 4.21875 | 4 | """
Se desea calcular la distancia
recorrida (m) por un móvil
que tiene velocidad constante (m/s)
durante un tiempo t (s), considerar
que es un MRU (Movimiento Rectilíneo Uniforme).
"""
v = float(input("Digite la velocidad m/s "))
t = float(input("Digite el tiempo (s) de duracion del recorrido "))
distancia = v * t
print(f"La distancia recorrida es {distancia}") | false |
5dd66d7c729b88d7b1e5ae10fc6865204ab3215b | andreaq/python-Course-6.00.1x- | /problem-set-1/counting vowels.py | 407 | 4.125 | 4 | '''
Assume s is a string of lower case characters.
Write a program that counts up the number of vowels contained in the string s.
Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print:
Number of vowels: 5
'''
vowels = list('aeiou')
count = 0
for letter in s:
if letter in vowels:
count+=1
print 'Number of vowels: {}'.format(count)
| true |
77198f5a9e805e690af6c0fb89f768a430cb516d | yokomotoh/python_excercises | /np_array_eye_identity.py | 527 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 15:27:06 2019
numpy array eye and identity
@author: yoko
"""
import numpy
def arrays(arr,n,m):
tmp=numpy.array(arr,int)
return numpy.reshape(tmp,(n,m))
N, M = input().split(' ')
numpy.set_printoptions(sign=' ')
#print(numpy.identity(3))
print(numpy.eye(int(N), int(M), k = 0))
#arr=[]
#for i in range(int(N)):
# arr.append(input().strip().split(' '))
#
#result = arrays(arr,int(N),int(M))
#print(result.transpose())
#print(result.flatten()) | false |
d39362699a40b14ecb106d52c9cc88dc63cd0779 | AvinashIkigai/Art-of-Doing | /FactorGeneratorApp.py | 686 | 4.1875 | 4 | print("Welcome to the Factor Generator App")
running = True
while running:
number = int(input("\nEnter a number to determine all factors of that number: "))
factors = []
for i in range(1, number+1):
if number % i == 0:
factors.append(i)
print(i)
print("\nFactors of " + str(number) + " are: ")
for factor in factors:
print(factor)
print("\nIn summary: ")
for i in range(int(len(factors)/2)):
print(str(factors[i]) + " * " + str(factors[-i-1]))
choice = input("\nRun again(y/n): ").lower()
if choice != 'y':
running = False
print("Thank you for using the program. Have a great day.") | true |
b6a0cfa7c2460ae4c8d8e6664734bc9442c3992b | AvinashIkigai/Art-of-Doing | /Units/simpe_if_else.py | 629 | 4.1875 | 4 | colors = ['red','green','blue']
for color in colors:
print(color)
for color in colors:
if color == 'red':
print("I love the color: " + color.upper())
else:
print("The color " + color +" is okay...")
age = int(input("\nWhat is your age: "))
if age >= 21:
print("Have a drink! ")
else:
print("Ah, no drinks for you")
first_name = "John"
last_name = "Smith"
if first_name == "Dave" and last_name == "Smith":
print("You are a cool guy!")
else:
print("Not cool enough!")
if first_name == "John" or last_name == "Jones":
print("You are a great guy")
else:
print("Not at all! ")
| true |
81dabcfda7d7279220e8c99379cdbf6fd5219c64 | AvinashIkigai/Art-of-Doing | /QuadraticSolverApp.py | 1,222 | 4.34375 | 4 | #Quadratic Equation Solver App
import cmath
#Print Welcome Information
print("Welcome to the Quadratic Solver App.")
print("A quadratic equation is of the form ax^2 + bx + c = 0")
print("Your solutions can be real or complex numbers.")
print("A complex number has two parts: a + bj")
print("Where a is the real portion and bj is the imaginary portion.\n")
#Get user input
eq_number = int(input("How many equations would you like to solve today: "))
#Loop through and solve each solution
for i in range(eq_number):
print("\nSolving Equation #" + str(i + 1))
print("--------------------")
a = float(input("\nPlease enter your value of a (coefficient of x^2: "))
b = float(input("Please enter your value of b (coefficient of x: "))
c = float(input("Please enter your value of c (coefficient: "))
#Solving the Quadratic formula
x1 = (-b + cmath.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
x2 = (-b - cmath.sqrt(b ** 2 - 4 * a * c)) / (2 * a)
print("\nThe solutions to " + str(a) + " x^2 + " + str(b) + " x + " + str(c) + " = 0 are: ")
print("\n\tx1 = " + str(x1))
print("\tx2 = " + str(x2) + "\n")
print("Thank You for using the Quadratic Equation Solver App. GoodBye.\n")
| true |
47b865124ae294b31640a18584f871334ef8996f | asif-iqbal-ba/AI-Class | /divisiblilty.py | 587 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
while True:
res = ""
try:
numerator = input("Please Enter numerator: ")
denominator = input("Please Enter Denominator: ")
rem = int(numerator) % int(denominator)
if int(rem) == 0:
res = "Number " + str(numerator) + " is Completly divisible by " + str(denominator)
else:
res = "Number " + str(numerator) + " is not Completly divisible by " + str(denominator)
break
except:
print("You should only enter integer/number")
print(res)
# In[ ]:
| false |
ff6d52543ac42d47f03ce72268fdd7f08cad7ad3 | peter-akworo/Strings-Python | /format.py | 1,630 | 4.1875 | 4 | # Value conversion
Number1 = "One"
Number2 = "Two"
Sentence2 = f"First two numbers are {Number1} {Number2}" # Simple positional formatting
print(Sentence2)
# Aligning
test = "test"
Sentence2 = f"{test:>10}" # Align left
print(Sentence2)
test2 = "test2"
sentence3 = f"{test2:_<10}" # Align right
print(sentence3)
test3 = "test3"
sentence4 = f"{test3:^10}" # Align centre
print(sentence4)
# Truncating
xylophone = "xylophone"
sentence5 = (
f"{xylophone:.5}" # number after . specifies precision length. Trancation length.
)
print(sentence5)
# Truncating and padding
Xylophone2 = "xylophone"
sentence6 = f"{Xylophone2:10.5}" # Trauncating at 5 and padded 10
print(sentence6)
# Simple number value conversion
num1 = 42
number1 = f"{num1:d}" # integers
print(number1)
pi = 3.141592653589793
number2 = f"{pi:f}" # floats
print(number2)
# padding numbers
num3 = 42
number3 = f"{num3:4d}"
print(number3)
# padding and truncating numbers
pi2 = 3.141592653589793
number4 = f"{pi2:06.2f}" # six characters with two decimal points
print(number4)
# signed numbers
num4 = 42
number5 = f"{num4:+d}" # positive integer
print(number5)
num5 = -42
number6 = f"{num5: d}" # negative integer
print(number6)
num1 = 3.1463259
num2 = 10.290452
# print('num1 is', num1,' and num2 is', num2)
# print('num1 is {0} and num2 is {1}'.format(num1,num2))
# print('num1 is {0:.3} and num2 is {1:.3}'.format(num1,num2))
# print('num1 is {0:.3f} and num2 is {1:.3f}'.format(num1,num2))
# print(f'num1 is {num1} and num2 is {num2}')
# print(f'num1 is {num1:.3} and num2 is {num2:.3}')
print(f"num1 is {num1:.3f} and num2 is {num2:.3f}")
| true |
4cdcb3f98ddcec82fd6d4b28ade2aa0e988b5a6d | austinsonger/CodingChallenges | /Hackerrank/_Contests/Project_Euler/Python/pe001.py | 508 | 4.15625 | 4 | '''
Problem 1
If we list all the natural numbers below 10 that are multiples of
3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
__author__ = 'SUN'
import time
def calculate():
count = sum(x for x in range(0, 1000, 3)) + \
sum(x if x % 3 != 0 else 0 for x in range(0, 1000, 5))
print(count)
if __name__ == '__main__':
start = time.clock()
calculate()
print("Run time is", time.clock() - start) | true |
e372ef2a62d72abec5ba965d40ac64c52e42e1cd | austinsonger/CodingChallenges | /Hackerrank/_Contests/Project_Euler/Python/pe009.py | 596 | 4.3125 | 4 | '''
Special Pythagorean triplet
Problem 9
A Pythagorean triplet is a set of three natural
numbers, a < b < c, for which, a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet
for which a + b + c = 1000.
Find the product abc.
'''
__author__ = 'SUN'
if __name__ == '__main__':
for a in range(1, 333):
for b in range(a + 1, 500):
c = 1000 - a - b
if a ** 2 + b ** 2 == c ** 2:
print("a =", a, ", b =", b, ", c =", c, ', a * b * c = ', a * b
* c)
exit()
| false |
3a1bd32ff9a7280978dfc65307228803ad0e0e7c | SheikhFahimFayasalSowrav/100days | /days001-010/day010/steps/ste02.py | 863 | 4.1875 | 4 | def add(n1, n2):
return n1 + n2
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return n1 * n2
def div(n1, n2):
return n1 / n2
operations = {
'+': add,
'-': sub,
'*': mul,
'/': div
}
num1 = int(input("What's the first number? "))
print(" ".join(operations))
operation_symbol = input("Pick an operation from the line above: ")
num2 = int(input("What's the second number? "))
calculation_function1 = operations[operation_symbol]
answer1 = calculation_function1(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer1}")
operation_symbol = input("\nPick another operation: ")
num3 = int(input("What's the next number? "))
calculation_function2 = operations[operation_symbol]
answer2 = calculation_function2(calculation_function1(num1, num2), num3)
print(f'{answer1 } {operation_symbol} {num3} = {answer2}')
| false |
366ff55925ed520c1e1ad8ba2824e89f49708ee0 | SheikhFahimFayasalSowrav/100days | /days001-010/day005/lectures/lec02.py | 240 | 4.1875 | 4 | for number in range(1, 10):
print(number)
print()
for number in range(1, 11):
print(number)
print()
for number in range(1, 11, 3):
print(number)
print()
total = 0
for number in range(1, 101):
total += number
print(total)
| true |
54094274c96d9d2ee6bc8a5440b8657d3ecfe112 | SheikhFahimFayasalSowrav/100days | /days011-020/day019/project/turtle_race.py | 1,064 | 4.21875 | 4 | from random import shuffle, randint
from turtle import Turtle, Screen
def create_turtles():
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
turtles = []
for color in colors:
turtles.append(Turtle('turtle'))
turtles[-1].color(color)
turtles[-1].pu()
y = -90
for turtle in turtles:
turtle.goto(-230, y)
y += 30
return turtles
def move(turtles):
shuffle(turtles)
for turtle in turtles:
turtle.fd(randint(0, 10))
if turtle.xcor() >= 230:
return turtle.pencolor()
return move(turtles)
def race():
turtles = create_turtles()
bet = screen.textinput(
title='Make your bet!', prompt='Which turtle will win the race? Enter a rainbow color: ').lower()
winning_color = move(turtles)
print(f"The {winning_color} turtle won the race!")
if winning_color == bet:
print("You won!")
else:
print("You lost!")
screen = Screen()
screen.setup(width=500, height=400)
race()
screen.exitonclick()
| true |
c99765fb1df4f188e751e285154417ba17b4c186 | druplall/Python_BootCamp_CE | /Python_BootCamp_CE/Class_Inheritance.py | 978 | 4.34375 | 4 | # What is inheritance ?
# It is a way to form new classes using already defined classes
# What is the benefits ? We can reuse existing code and reduce complexity of a program
## Base Class
class Animal():
def __init__(self):
print('Animal Created !')
def who_am_i(self):
print('I am an animal ')
def eat(self):
print('I am eating')
myanimal = Animal()
myanimal.eat()
myanimal.who_am_i()
## Derived class
class Dog(Animal): # Notice we are passing in the animal class in the Dog class, this will allow us to inhert from the Animal class
def __init__(self):
Animal.__init__(self) # Here we are creating an instance of the animal class which dog.
print('Dog Created')
# We can overwrite the base class functions -- Just use the same function name
def who_am_i(self):
print('I am dog now')
def bark(self):
print('Woof !')
myDog = Dog()
myDog.eat()
myDog.who_am_i()
myDog.bark() | true |
3cfdf46068af2a686c700f5f9fcfe0557102c20e | FranklinHarry/DevOPS-Examples | /codeexamples/Python3/YouTube-Examples/Variables.py | 640 | 4.15625 | 4 | # Print Variables Example from Youtube Python3 video https://www.youtube.com/watch?v=rfscVS0vtbw&feature=youtu.be
character_name = "David"
character_age = "25"
print ("Hi my name is " + character_name + ", I love coding, Im young")
print ("I think I'm doing quite well but im only " + character_age + " years old.")
#Changing the variable values for the next sentences but not name of the variable itself
character_name = "Steve"
character_age = "75"
print ("My Variable has been changed, so name is now " + character_name + ", I hate coding")
print ("but Im am doing quite well for " + character_age + " years old, don't you think ?")
| true |
fe0a0b15622ac8350ebe18f812c890d8dd45592f | wjones907/python-tutorial | /listtuplesjson.py | 631 | 4.4375 | 4 | # for making a tuple
MyTuple = (89,32)
MyTupleWithMoreValues = (1,2,3,4,5,6)
# To concatenate tuples
AnotherTuple = MyTuple + MyTupleWithMoreValues
print AnotherTuple
# it should print 89,32,1,2,3,4,5,6
# To get Value from tuple
firstVal = MyTuple[0]
secondVal = MyTuple[1]
print 'firstVal:',firstVal
print 'secondVal:',secondVal
# usage is more like a list
# if you got a function that returns a tuple than you might do this
Tup = (1,2)
Tup2 = (3,4,5)
Tup3 = [{"x":"1","y":"2","z":"3"}]
x=Tup()[0] # x=1
y=Tup()[1] # y=4
#or This
v1,v2 = Tup()
def tup():
return (2,"hello")
i = 5 + tup()[0]
#return first element
| true |
1e09567a0aad9807c3ea7f4b1cf09f9609a7c252 | sandrastokka/phython | /new.py | 334 | 4.625 | 5 | #here we want to take an input from the user
print ("Please enter the radius of the circle:")
radius = float(input())
print ("you have entered a radius of", radius)
myConstPi = 3.14
print("the circumference of a circle is :", 2*myConstPi*radius)
if (radius < 0):
print ("The radius of a circle cannot be a negative number")
| true |
32c0652b04a8cc93b7d484ddf1f9967e198ec4bb | postfly/geekbrains | /python/lesson_1/hw_3.py | 395 | 4.15625 | 4 | n = input('Enter a positive integer: ')
while n:
if n.isdigit():
# функция .isdigit() проверяет, состоит ли строка
# только из цифр
result = f"{int(n) + int(n * 2) + int(n * 3)}"
print(result)
break
else:
print("Number must be whole and positive")
n = input('Enter a positive integer: ')
| false |
a7bf7209dab03d705a22e6f7b09960668f703ec9 | full-time-april-irvine/kent_hervey | /python/python_fundamentals/practice_file.py | 1,592 | 4.25 | 4 | is_hungry=True
has_freckles=False
age = 25
weight = 160.57 #float
name = "Joe Blue" #literal string
#Tuples
dog = ('Bruce', 'cocker spaniel', 19, False)
#print(dog[0]) #output: Bruce
#dog[1] = 'anything' makes and error becuase tuples are immutable
#Lists - A type of data that is mutable and can hold a group of values. Usually meant to store a collection of related data.
print("begin lists")
empty_list = []
ninjas = ['Rozen', 'KB', 'Oliver']
# print(ninjas[2])
ninjas[0] = 'Francis'
ninjas.append('Michael')
print("\n")
# print(ninjas)
# ninjas.pop()
# print(ninjas)
# ninjas.pop(1)
# print("after pop(1)", ninjas)
#I note that Python allows removal of a value in any positi of a list
dictionary = "Dictionaries - A group of key-value pairs. Dictionary elements are indexed by unique keys which are used to access values. "
print(dictionary)
enpty_dict = {}
new_person = {'name': 'John', 'age': 38, 'weight': 160.2, 'has_glasses': False}
new_person['name'] = 'Jack' #updates if the key exists
new_person['hobbies'] = ['climbing', 'coding'] #adds a key-value pair if the kye doesn't exist
w = new_person.pop('weight') # removes the specified key and returns the value
print (w)
#print(new_person)
print("\n")
what_type = "If we're ever unsure of a value or variable's data type, we can use the type function to find out. For example:"
print(what_type)
print(type(2.63))
print(type(new_person))
print(len(new_person))
print(len('Coding Dojo'))
print("\n")
print("\n")
print("Hello " + str(42))
total = 35
user_val = "26"
total = total + int(user_val)
print(total)
| true |
a7bea868d029aab6f824716dfc2ceea028c41e91 | Th3lios/Python-Basics | /8 loops.py | 2,902 | 4.15625 | 4 | #!/usr/bin/python
#En python tenemos 2 tipos de loos
#While
#For
########### WHILE LOOP #################
#Recordad que pass es una sentencia que no ejecuta nada
#Así se define un while, al igual que el if el parentesis es opcional
while ():
pass
while :
pass
#Un while (mientras) ejecuta un codigo (en este caso el pass) repetitivamente
#Ejemplo
i = 0 #definimos i como 0
while i <= 10: #Mientras que "i" sea "menor o igual" a "10" que ejecute el codigo de abajo
print("hola") #Se imprime hola
i = i + 1 # i aumenta en 1
#Va a llegar un punto en que i va a aumentar tanto que va a superar el 10 y en ese instante
#el while se detendrá
#Al igual que el if el while tambien tiene por default el !=False
while ()!=False:
pass
#Esto significa que si hacemos lo siguiente
while True:
pass
#El loop será infinito, ya que no hay ninguna condicion que lo detenga
#Debido a esto podemos anidarle un if y detenerlo con alguna condicion. Ejemplo
i = 0
while True: #Mientras True sea distinto de False
if i == 10: #Si i es igual a 10
break #Romper el ciclo (Su explicación mas abajo)
else: #Sino
i+=1 #Incrementar i en 1. Esto es la abreviacion de i = i + 1
# i+=1 es distinto de i=+1
# en i+=1, i aumenta en 1 (i = i + 1)
# en la segunta, i = (+1), significa que se le asigna el unario "+" a 1
# Mini ej i=+(-1) / i seria igual a -1, porque + por - es igual a menos
#En este ejemplo conocimos el BREAK, este comando especial detiene cualquier ejecución, en
#este caso la ejecución del while
#Hay otro comando que se llama CONTINUE. Este comando lo que hace es saltarse una ejecución
#sin detener la ejecucion por completo como el break. En el caso del while, se saltaría una vuelta
i = 0
while True: #Mientras True sea distinto de False
if i < 10: #Si i es menor a 10
i+=1 #i aumenta en 1
continue #Saltarse esta vuelta (implica que lo de abajo no se ejecutará aún)
else: #El while también puede tener else (se comporta igual que el del if)
print("Ya terminó") #Cuando i sea mayor o igual a 10, se imprimirá Ya terminó
break #Se rompe el ciclo while
########################################
################## FOR LOOP #######################
#Un for se define asi:
for x in xrange(1,10): # x funciona como un auxiliar que recore el rango o lista, xrange genera su propio tipo de dato xrange
pass # Ejecuta esta sentencia según el recorrido de x
#Ejemplo
for x in range(0,10): # range retorna una lista de los parametros que se le da range(0,n) e imprime hasta n-1
print(x) # Esto imprime x en cada ciclo del for 0,1,2,3,4,5,6,7,8,9
#El for igual tiene un else
for x in xrange(1,10):
pass
else: # Trabaja igual que el del while
pass
################################################### | false |
47f30df58da59007778f5b290ab8ff3293db6be4 | Th3lios/Python-Basics | /5 manejoDeTuplas.py | 1,582 | 4.4375 | 4 | #!/usr/bin/python
# Las tuplas son identicas a las listas, la única diferencia es que se usan
# () y las listas usan []
a = ('hola',"mundo",200,200) # Esto es una Tupla
a = ['hola',"mundo",200,200] # Esto es una lista
# Otro aspecto de las tuplas es que no pueden ser cambiadas como las listas
# Para definir una sola variable en una tupla, se debe incluir una coma
a = ('hola',)
# El acceso a las variables se hace igual que en las listas
print(a[0]) # Esto muestra hola
print(a[:]) # Esto muestra todo el contenido de a
#### ACTUALIZAR TUPLA ######
# Las tuplas no pueden ser editables, pero se pueden crear otras tuplas a base de las tuplas existentes. EJ
tup1 = (1,2,3,4)
tup2 = ('c','b','a')
tup3 = tup1+tup2
print(tup3) # Esto va mostrar (1,2,3,4,'c','b','a')
#############################
### ELIMINAR TUPLAS #####
# Eliminar un valor especifico de una tupla es imposible, solo se puede eliminar una tupla completa Ej:
del tup1
#########################
#### FUNCIONES DE TUPLAS ####
len(tup1) # Entrega el tamaño de la tupla
tup + tup1 # Une o concatena estas 2 tuplas
('tup'!)*4 # Crea una tupla con 4 strings tup ('tup','tup','tup','tup')
3 in tup # Retorna true si el valor está en la tupla y false si no está
cmp(tup,tup2) # Compara 2 tuplas, retonando true si son iguales y false si no lo son
max(tup) # Retorna el valor mas grande de la tupla
min(tup) # Entrega el valor mas chico de la tupla
tuple(lista) # Convierte una lista en una tupla
#############################
| false |
4eaf29589730fcc63aca08ae3e62dfbd5dbaca9a | romildodcm/learning_python | /extra_codes/chapter_3/exercise_3_3_grid.py | 1,347 | 4.40625 | 4 | '''
The exercise was more simple, but I wanted to make a general function
that creates an ASCII matrix with the input of lines and columns.
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
'''
'''
A function to make the horizontal grid:
"+ - - - - + - - - - +..."
'''
def horizontal_grid(total_columns):
for i in range(total_columns):
print('+', end=' ')
for n in range(4):
print('-', end=' ')
print('+')
'''
A function to make the vertical grid:
"| | |..."
'''
def vertical_grid(total_columns):
for i in range(total_columns):
print('| ', end="")
print('|')
'''
A function to runs n times a function with an argument,
in this case, used to make the vertical grids.
'''
def do_n(n, f, argument):
for i in range(n):
f(argument)
'''
Makes the grids with the number of columns and lines,
and the previous functions.
'''
def grid_maker(columns, lines):
for i in range(lines):
horizontal_grid(columns)
do_n(4, vertical_grid, columns)
horizontal_grid(columns)
l = int(input("Line number: "))
c = int(input("Column number: "))
grid_maker(c, l) | false |
1a51d3cec5cd64069eaa949ba2f642127c267d88 | romildodcm/learning_python | /more_python_for_Beginners/more_py_8_9_Inheritance.py | 1,471 | 4.34375 | 4 | # INHERITANCE
# Creates an "is a" relationship
# -> Student is a Person
# -> SqlConnection is a DatabaseConnection
# -> MySqlConnection is a DatabaseConnection
#
# COMPOSITION (with properties) creates a "has a" relationship
# -> Student has a Class
# -> databaseConnection has a ConnectionString
#
# Python inheritance in action
# All methods are "virtual"
# -> Can override or redefine their behavior
# Keyword *super* to access parent class
# -> Constructor
# -> Properties in methods
# Must always call parent constructor
# Inheritance from a class
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print('Hello, ' + self.name)
class Student(Person):
def __init__(self, name, school):
super().__init__(name)
self.school = school
def sing_school_song(self):
print('Ode to ' + self.school)
# Using a derived class
student = Student('Romildo', "UMD")
student.say_hello()
student.sing_school_song()
# What are you?
# Is this in instance of additional classes?
print(f'Is this a student? {isinstance(student, Student)}') # return true becouse student is Student
# student is a person return true
print(f'Is this a person? {isinstance(student, Person)}') # return true becouse student is a Person
# is a Student a subclass of Person? In another words, does it inherit?
# return true becouse of the fact that we inherit
print(f'Is Student a Person? {issubclass(Student, Person)}')
| true |
9f7f5dda8ce094253c33597c8a6cc97dba199633 | romildodcm/learning_python | /python_for_Beginners/aula11_a.py | 1,193 | 4.25 | 4 | first_name = input('What is your first name? ')
last_name = input('What is your last name? ')
# Modo 1 de manipular e formatar strings
output = 'Hello, ' + first_name + ' ' + last_name
model_number = 1
final_out = 'Model: {0}:\n{1}\n-----------------------------'.format(model_number,output)
print(final_out)
# Modo 2 de manipular e formatar strings
output = 'Hello, {} {}'.format(first_name, last_name)
model_number += 1
final_out = 'Model: {0}:\n{1}\n-----------------------------'.format(model_number,output)
print(final_out)
# Modo 3 de manipular e formatar strings
# Esse tem uma apicação interessante, quando num documento vamos usar
# a mesma variável em várias partes, ai colocamos op index dela 0, 1,..., n
output = 'Hello, {0} {1}'.format(first_name,last_name)
model_number += 1
final_out = 'Model: {0}:\n{1}\n-----------------------------'.format(model_number,output)
print(final_out)
# Modo 4 de manipular e formatar strings
# Only available in Python 3
# achei a mais prática e mais clara, autoexplicativa
output = f'Hello, {first_name} {last_name}'
model_number += 1
final_out = 'Model: {0}:\n{1}\n-----------------------------'.format(model_number,output)
print(final_out) | false |
bfeab8b6174fb5dd21948c95ab32a5d8dafa4080 | lindsaymarkward/in_class_2019_2 | /week_05/warmup_lists_fn.py | 825 | 4.21875 | 4 | """
Write code for a function that takes two lists:
- a list of names
- a corresponding list of ages
(That is, elements at the same list index represent the same person.)
The function should return the name of the oldest person in the list.
(Return the first name if multiple people have the same oldest age.)
"""
def main():
# first_names = []
# numbers = []
first_names = ["A", "B", "C", "D"]
numbers = [3, 1, 0, 2]
print(find_oldest_name(first_names, numbers))
def find_oldest_name(names, ages):
if not ages:
return None
index_of_oldest = 0
age_of_oldest = ages[0]
for i, age in enumerate(ages[1:], 1):
if age > age_of_oldest:
index_of_oldest = i
age_of_oldest = age
return names[index_of_oldest]
if __name__ == '__main__':
main()
| true |
6ebcbe2dd42b4115407eb312708a2f84ab85cb73 | CosyCagesong/PythonCrashCourse | /06dictionaries01.py | 1,719 | 4.21875 | 4 | alien_0 = {} # an empty dictionary
alien_0['color'] = 'green' # add a new key-value pair
alien_0['points'] = 5
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0['color']) # green
print(alien_0['points']) # 5
alien_0['color'] = 'yellow' # change values in a dictionary
del alien_0['points'] # remove a key-value pair
languages = { # This is a recommended format. It's not compulsory,
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python', # use a comma for the last key-value pair as well.
}
language = languages.get('Tom', 'person not found')
#The first argument is the key to be searched
#The second argument is the value to be returned if the key doesn't exist.
#The second argument defaults to the value None
for person,language in languages.items():
print(f"\nPerson: {person}")
print(f"Language: {language}")
#the method items() returns a list of key-value pairs.
for person in languages.keys():
print(person)
#The following has the same result.
for person in languages:
print(person)
'erin' not in languages.keys() # True. The keys() method returns a list of keys
for language in languages.values():
print(language)
#The values() method returns a list of values without any keys.
#It doesn't check repetition.
for language in set(languages.values()):
print(language)
#A set is a collection in which each item must be unique.
languages = {'python', 'ruby', 'python', 'c'}
# You can build a set directly using braces and separating the elements
# with commas.
print(languages) # {'ruby', 'c', 'python'}
aliens = []
#Make 30 green aliens.
for alien_number in range(30):
new_alien = {
'color': 'green',
'points': 5,
'speed': 'slow',
}
aliens.append(new_alien)
| true |
a4bf7e7a86f2b2fe1456b4e4f112145f2021e3f7 | apalat12/Chandler-s-State-Game | /revision_pandas_well_commented.py | 1,447 | 4.15625 | 4 | import pandas
data = pandas.read_csv("weather_data.csv")
# Just read the CSV, output_type <class 'pandas.core.frame.DataFrame'>
# data is the object created to DataFrame
# print(type(data["temp"]))#<class 'pandas.core.series.Series'>
##for row in data["temp"]: #temp could be any coloumn ,returns Series or list
## print(row)
##print(data.to_dict()) #it will convert data to dictionary
##print(data["temp"].to_list()) # it will convert Series to python list
##print(data["temp"].mean()) # ==data.temp.mean()
##print(data.temp.mean())
##print(data["temp"].max())
##print(data["day"]) # any coloumn can be used and it will give a list
##print(data["condition"]) # == data.condition
#pandas take each of the heading and converts it into attributes
#To Get data in row
##print(data[data['day']=='Monday'])
###OR
##print(data[data.day=='Monday'])
##print(data[data.temp==data.temp.max()])
#OR
##print(data[data.temp==data["temp"].max()])
monday = data[data.day=="Monday"] # ROW for Monday
##print(monday.temp*1.8+32)
#OR
##print(data[data.day=="Monday"].temp*1.8 +32)
my_dict = {
"students":["Amy","James","Angela"],
"Score": [45,57,83]
}
##new_data = pandas.DataFrame(my_dict)
##print(new_data)
##new_data.to_csv("sample.csv")
states = pd.read_csv("50_states.csv")
# print(states)
for (idx,row) in states.iterrows():
print(row.state)
states_list = states.state.to_list()
remaining_states = states_list.copy()
| true |
2a0d8d81ee6dbbb32f1e22381cf286d686bc02e5 | JeongMin-98/algorithm | /.vscode/stack1/factroial.py | 243 | 4.15625 | 4 | def factorial(x):
if x>0:
if x > 1:
return x*factorial(x-1)
else:
return 1
else:
return "팩토리얼 함수를 실행시킬수 없습니다."
x = 0
result = factorial(x)
print(result) | false |
21230c540b9b65ef240e31a2624d9b56f06991cb | Amudha2019/INeuron-Assignment-1 | /Asstask2.3.py | 224 | 4.4375 | 4 | #Write a Python program that accepts a word from the user and reverse it.
s = input("Enter your name")
print ("The original string is : ",end="")
print (s)
b=s[::-1]
print("The reversed string is " +b)
| true |
7fd04bfe2f73822bf225b2e438333da7e2e93eba | Henrico454/MyLearning | /Exercicio09.py | 370 | 4.1875 | 4 | # Escreva um programa que leia em metros
# e mostre convertido em centimetros e milimetros
metro = float(input('Digite a quantidade de metros: '))
cm = metro / 0.010000
mm = metro / 0.00100000
print('a quantidade de metros convertida em centimetros corresponde a {}'.format(cm))
print('A quantidade de metros convertida em milímetros corresponde a {}'.format(mm)) | false |
d43b9cfdf01fb1940ef6642175179f3483338597 | dmshirochenko/check_logs_python | /check_log_with_python.py | 1,194 | 4.15625 | 4 | #!/usr/bin/env python3
import sys
import os
import re
def error_search(log_file):
"""
Function will check log file in attempt to find line with inoutted value
"""
error = input("What is the error? ")
returned_errors = []
with open(log_file, mode='r',encoding='UTF-8') as file:
for log in file.readlines():
error_patterns = []
for i in range(len(error.split(' '))):
error_patterns.append(r"{}".format(error.split(' ')[i].lower()))
if all(re.search(error_pattern, log.lower()) for error_pattern in error_patterns):
returned_errors.append(log)
return returned_errors
def file_output(returned_errors):
"""
Function will write found inoutted lines to the new file
"""
if not returned_errors:
print('Nothing was found.')
else:
print('Something were found in logs. Please check the file.')
with open('found_error_ in_logs.log', 'w+') as file:
for error in returned_errors:
file.write(error)
if __name__ == "__main__":
log_file = sys.argv[1]
print('Log file name = ', log_file)
returned_errors = error_search(log_file)
file_output(returned_errors)
sys.exit(0)
| true |
3168d598dcf2abd90df6e24311eb90237a6ffe95 | pdvelez/miscellaneous_exercises | /recursion/a_to_power_b.py | 438 | 4.3125 | 4 | """
This exercise can be found at
http://www.w3resource.com/python-exercises/data-structures-and-algorithms/python-recursion.php
"""
def a_to_power_b(a, b):
"""
Return a to the power of b. i.e. pow(3, 4) = 81
"""
if b == 0:
return 1
elif a == 0:
return 0
elif b == 1:
return a
else:
return a * a_to_power_b(a, b - 1)
if __name__ == '__main__':
print(a_to_power_b(3, 4)) | false |
e5d300a7d73090e9b9d169034e2d777934d91cf3 | Shamitbh/ITP-115 | /Labs/ITP115_l2_Bhatia_Shamit.py | 1,571 | 4.1875 | 4 | # Shamit Bhatia
# ITP 115, Fall 2016
# Lab L2
# Shamitbh@usc.edu
# import random
sizeCoffee = input("What size coffee do you want(S, M, L): ")
if (sizeCoffee.lower() == "s"):
sizeCoffee = "small"
elif (sizeCoffee.lower() == "m"):
sizeCoffee = "medium"
elif (sizeCoffee.lower() == "l"):
sizeCoffee = "large"
else: #user enters a letter that is not s, m, or l
print("Please follow the directions.")
wordTempCoffee = "" #if user enters temp > 150, "hot", if temp < 150, "cold" -> variable stores the user's temp (int) as a string (hot or cold)
tempCoffee = int(input("What temperature would you like(in degrees Fahrenheit)?: "))
if (tempCoffee > 150):
wordTempCoffee = "hot"
elif (tempCoffee > 0):
wordTempCoffee = "cold"
else: #user enters a negative temp.
print("Please follow the directions.")
beansType = input("What type of beans / blend would you like?: ")
if beansType == "":
print ("Please follow directions")
roomCream = input("Would you like room for cream (y/n)?: ")
if (roomCream.lower() == "y"):
roomCream = "Cream"
elif (roomCream.lower() == "n"):
roomCream = "No Cream"
else: #user enters a letter that's not y or n
print("Please follow the directions.")
print("\n")
print("You ordered a",sizeCoffee, wordTempCoffee, beansType,"with",roomCream)
# randomDrink = input("Would u also like me to generate a random temp bro? (y/n)")
# if (randomDrink.lower() == "y"):
# print("Sweet. ", end="")
# tempRand = random.randrange(100, 180)
# print("Your temp. is:",tempRand)
# else:
# print("Aight bro no worries.")
| true |
c3bb568a4ccd81bfd42e09f6b9f81c14de32aff1 | Shamitbh/ITP-115 | /Lecture Notes/Lecture Notes 9-13-16.py | 384 | 4.375 | 4 | # Lists and tuples
genres = ["crunk", "alternative", "jazz", "rap"]
for genre in genres:
print(genre, end=" ")
genres.append("hip hop")
for item in genres: # iterate through each genre
for letter in item: # iterate through each letter in given genre
if letter not in "aeiou":
# Print all non-vowel letters
print(letter, end="")
print()
| true |
fa9f4ed0637d6057a2c25dcb3cb8f1f8b0ce2bea | anupjungkarki/IWAcademy-Assignment | /Assignment 1/DataTypes/answer37.py | 212 | 4.25 | 4 | # Write a Python program to multiply all the items in a dictionary.
dict_data = {'1': 2, '2': 4, '3': 3, '4': 9, '5': 6}
mul = 1
for values in dict_data:
mul = values * dict_data[values]
print('Total:', mul)
| true |
83cf70778d713c91fe053e2076269a6ccadc6ee1 | anupjungkarki/IWAcademy-Assignment | /Assignment 1/Function/answer20.py | 274 | 4.25 | 4 | # Write a Python program to find intersection of two given arrays using Lambda.
array1 = [1, 2, 3, 5, 7, 8, 9, 10]
array2 = [1, 2, 4, 8, 9]
print(array1)
print(array2)
result = list(filter(lambda x: x in array1, array2))
print("\nIntersection of the said arrays: ", result)
| true |
d91c76998c60841a40178be9b956820c98f67b06 | anupjungkarki/IWAcademy-Assignment | /Assignment 2/answer14.py | 634 | 4.25 | 4 | # Write a function that reads a CSV file. It should return a list of dictionaries, using the first row as key names,
# and each subsequent row as values for those keys.
import csv
def read_csv(filename):
result = []
with open(filename) as file:
first = True
for line in file:
if first:
keys = "".join(line.split()).split(',')
first = False
else:
values = "".join(line.split()).split(',')
result.append({keys[n]: values[n] for n in range(0, len(keys))})
print(result)
read_csv('my_csv.csv')
| true |
17ae035e60481a3e0b999849fc14347ba44a8042 | anupjungkarki/IWAcademy-Assignment | /Assignment 1/DataTypes/answer2.py | 390 | 4.4375 | 4 | # Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string.
# If the string length is less than 2, return instead of the empty string.
def get_two_string(str):
if len(str) < 2:
return 'Empty String'
else:
return str[0:2] + str[-2:]
print(get_two_string('Python'))
print(get_two_string('Py'))
print(get_two_string('W'))
| true |
efea3da14774da087da06f183b556f44fd3d8a7e | anupjungkarki/IWAcademy-Assignment | /Assignment 1/DataTypes/answer18.py | 537 | 4.40625 | 4 | # Write a Python program to get the largest number from a list.
def my_max_number(list_data_next):
max_number = list_data_next[0]
for data in list_data_next:
if data > max_number:
max_number = data
return max_number
result = my_max_number([1, 3, 5, 20, 45, 2, 4, 7, 13])
print('The largest number is:', result)
# or we can also
list_data = [1, 4, 5, 18, 2, 3, 7, 9, 13, 12, 11]
list_data.sort()
if list_data:
print('The Largest number is:', list_data[-1])
else:
print('No data found in list') | true |
338de5262db09bddc708ece23426dd3eb19bcff1 | anupjungkarki/IWAcademy-Assignment | /Assignment 2/answer16.py | 991 | 4.15625 | 4 | # Imagine you are creating a Super Mario game. You need to define a class to represent Mario. What would it look like?
# If you aren't familiar with SuperMario, use your own favorite video or board game to model a player.
class Mario:
def __init__(self):
self._lives = 3
self._speed = 10
self._jumpHeight = 5
self._width = 32
self._height = 64
self._sprite = "/path/for Image"
def draw(self, screen):
# To draw Sprite to the screen
return
def update(self, delta_time):
# To use jump method if jump button is pressed
# To run if left or right is pressed
return
def move(self, direction):
# To use for speed and move in the specified direction
return
def jump(self):
# To determine the jump height
return
def collides(self):
# To determine the width and height if mario collide with object
return
| true |
e43f10a816528c63cd72ceaf6bf4c8c472a7d62b | VishwasKashyap/hello-world | /dailypogrammer/make_bricks.py | 742 | 4.15625 | 4 | def makebricks(small,big,goal):
small_size = 1
big_size = 5
if goal == small*small_size + big*big_size: #goal = small + big
print("True!, You can add up the bricks to match your goal!")
elif goal < small*small_size + big*big_size:
if goal <= small*small_size:
print("True!, you can add up the bricks to match your goal!")
elif goal > small*small_size and goal < small*small_size+big*big_size:
if goal % 5 <= small*small_size:
print("True!, you can add up the bricks to match your goal!")
else:
print("Sorry, your goal can't be reached!")
else:
print("Sorry, your goal can't be reached!")
makebricks(1,1,7)
| true |
b2558c76a2d4c08f701f8e8e380a74e6013fcc91 | Evil-Elvis/Coding-Challenges-EMEAR | /coding-challenge-0001.py | 2,153 | 4.25 | 4 | """
Open your PyCharm Or IDLE any Editor of your preference
Declare three variables named random_number and sum_of_digits and product_of_digits.
Initialize these variables with 0 since they will contain integers [numbers].
Then instruct the Python Interpreter to randomly choose a value of two digit between 10 & 99.
Save that random value into the appropriate variable (random_number).
Compute the sum of digits inside this random number and save it into sum_of_digits.
Compute the product of all digits inside this number and save into product_of_digits.
Display the two result to the user and prompt the user to imagine/guess and type this random number.
Compare this number with the random value and inform the user either it is higher or lower or equal.
In event the user number matches with the random number then congrats the user :)
"""
# defining variable
random_number = 0
sum_of_digits = 0
product_of_digits = 0
# import random module
from random import randint
random_number = randint(10,99)
# convert integer into str in order to select first and second digit and convert each digit back to integer
random_number_str = str(random_number)
digit_1 = int(random_number_str[0])
digit_2 = int(random_number_str[1])
# counter for number of trials
number_of_guesses = 1
# calculations
sum_of_digits = digit_1 + digit_2
product_of_digits = digit_1 * digit_2
# Player interaction
print('Your task is to guess a number between 10 and 99 based on the sum and product of the two digits.', '\n', 'Enter "0" to exit.')
print('Sum of digits: ', sum_of_digits)
print('Product of digits: ', product_of_digits)
# while loop repeats until it breaks due to correct user entry or entering "0".
while True:
guess = int(input('Guess the random_number: '))
if guess == random_number:
print('Congratulations! {} is the correct number! You needed {} attempts.'.format(random_number, number_of_guesses))
break
elif guess == 0:
break
elif guess < random_number:
print('random_number is larger')
number_of_guesses += 1
else:
print('random_number is smaller')
number_of_guesses += 1
| true |
8a068df097f93268d543ebc02c2b25ebde8203ea | Rocia/Project_Eulers_Solutions_in_Python | /10.py | 455 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 01:05:20 2018
@author: rocia
"""
def isPrime(x):
if x >= 2:
for y in range(2,x):
if not ( x % y ):
return False
else:
return False
return True
def compute(limit):
sumOprimes = 0
for x in range(2,limit+1):
if isPrime(x):
sumOprimes += x
return sumOprimes
print(compute(2000000)) | false |
95ee83323c99f57375ff73fe165fdae9a50f330b | ehsanul18/Datacamp-Courses | /Data_Manipulation_with_pandas/1_Transforming_Data/subsettingRows.py | 1,829 | 4.5625 | 5 | # Subsetting rows
# A large part of data science is about finding which bits of your dataset are interesting. One of the simplest techniques for this is to find a subset of rows that match some criteria. This is sometimes known as filtering rows or selecting rows.
# There are many ways to subset a DataFrame, perhaps the most common is to use relational operators to return True or False for each row, then pass that inside square brackets.
# dogs[dogs["height_cm"] > 60]
# dogs[dogs["color"] == "tan"]
# You can filter for multiple conditions at once by using the "bitwise and" operator, &.
# dogs[(dogs["height_cm"] > 60) & (dogs["color"] == "tan")]
# homelessness is available and pandas is loaded as pd.
# Instructions 1/3
# 35 XP
# Filter homelessness for cases where the number of individuals is greater than ten thousand, assigning to ind_gt_10k. View the printed result.
# Instructions 2/3
# Filter homelessness for cases where the USA Census region is "Mountain", assigning to mountain_reg. View the printed result.
# Instructions 3/3
# Filter homelessness for cases where the number of family_members is less than one thousand and the region is "Pacific", assigning to fam_lt_1k_pac. View the printed result.
# # Filter for rows where individuals is greater than 10000 (Instruction 1)
# ind_gt_10k = homelessness[homelessness['individuals']>10000]
# # See the result
# print(ind_gt_10k)
# # Filter for rows where region is Mountain (Instruction 2)
# mountain_reg = homelessness[homelessness['region'] == 'Mountain']
# # See the result
# print(mountain_reg)
# Filter for rows where family_members is less than 1000 (Instruction 3)
# and region is Pacific
fam_lt_1k_pac = homelessness[(homelessness['family_members'] < 1000) & (homelessness['region'] == 'Pacific')]
# See the result
print(fam_lt_1k_pac)
| true |
f9728728e2c8988e2acef424e205a519cfa784aa | nnelluri928/DailyByte | /valid_characters.py | 727 | 4.1875 | 4 | '''
This question is asked by Google.
Given a string only containing the
following characters (, ), {, }, [, and ] return
whether or not the opening and closing characters are in a valid order.
Ex: Given the following strings...
"(){}[]", return true
"(({[]}))", return true
"{(})", return false
'''
def isValid(s):
stack = []
lib = {")":"(","}":"{","]":"["}
for char in s:
if char in lib:
if stack and stack[-1] == lib[char]:
stack.pop()
else:
return False
else:
stack.append(char)
return True if not stack else False
s = "(){}[]"
print(isValid(s))
s = "(({[]}))"
print(isValid(s))
s = "{(})"
print(isValid(s)) | true |
aceb49f949f7a6f53e14cdd38028661d711c753b | nnelluri928/DailyByte | /next_greater_element.py | 1,196 | 4.28125 | 4 | '''
This question is asked by Amazon. Given two arrays of numbers,
where the first array is a subset of the second array,
return an array containing all the next greater elements for each element in the first array,
in the second array. If there is no greater element for any element, output -1 for that number.
Ex: Given the following arrays…
nums1 = [4,1,2], nums2 = [1,3,4,2], return [-1, 3, -1]
because no element in nums2 is greater than 4, 3 is the first number in nums2 greater than 1, and no element in nums2 is greater than 2.
nums1 = [2,4], nums2 = [1,2,3,4], return [3, -1]
because 3 is the first greater element that occurs in nums2 after 2 and no element is greater than 4.
'''
def greater_element(nums1,nums2):
stack = []
lib = {}
for num in nums2:
while stack and stack[-1] < num:
top = stack.pop()
lib[top] = num
stack.append(num)
res = []
for num in nums1:
if num in lib:
res.append(lib[num])
else:
res.append(-1)
return res
nums1 = [4,1,2]; nums2 = [1,3,4,2]
print(greater_element(nums1,nums2))
nums1 = [2,4]; nums2 = [1,2,3,4]
print(greater_element(nums1,nums2)) | true |
7531b51753efef691820b0220969311892f66335 | CYalda/PG_CY | /personality_CY.py | 494 | 4.21875 | 4 | name = "Christian"
state = "Connecticut"
city = "Greenwich"
tvshow = "How I Met Your Mother"
print (name + " likes to visit " + state + " and " + city)
print ("What is your favorite subject?")
subject = input()
if subject == "History":
print ("That's my favorite too")
else:
print (subject + " is Ok too.")
print ("What's your favorite sport?")
sport = input()
is sport == "Mini Golf" or sport == "mini gold":
print ("Im probably better then you")
| true |
b4a3c86a0a83383c56b6dcc8c5eff7e8e91742e6 | surendra477/100daysPythonchallenge | /day1.py | 284 | 4.34375 | 4 |
# reverse a number
a = input("a: ")
b = input("b: ")
c = a
a = b
b = c
print("a: "+ a)
print("b: "+b)
# find a band name using user input
cityname =input("enter cityname where you grew up?")
petname = input("enter pen name ?")
print("so your band name is "+cityname+petname)
| false |
4e2acd3d0fb53482b3d4566cbc7807dc47cbe7df | PM-CS10/Intro-Python | /src/lists.py | 888 | 4.375 | 4 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
# The available functions are the following on lists: 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# [command here]
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# [command here]
x.extend(y)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
# [command here]
x.remove(8)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
# [command here]
x.insert(5,99)
print(x)
# Print the length of list x
# [command here]
print(len(x))
# Using a for loop, print all the element values multiplied by 1000
for num in x:
print(num * 1000) | true |
c6bef9ac15ed74814d731847c3a311dc23e7a771 | AmberHsia94/Scary_Leetcode | /visualizing.py | 1,285 | 4.15625 | 4 | import turtle
def drawSpiral(myTurtle, lineLen):
# given a length
if lineLen > 0:
myTurtle.forward(lineLen)
myTurtle.right(90)
drawSpiral(myTurtle, lineLen - 5)
# draw a fractal tree
# a fractal is something that looks the same at all different levels of magnification.
def fractal_tree(branchLen, t):
if branchLen > 5:
t.forward(branchLen)
t.right(20)
fractal_tree(branchLen - 15, t)
t.left(40)
fractal_tree(branchLen - 15, t)
t.right(20)
t.backward(branchLen)
# def sierpinski_triangle(, t)
if __name__ == '__main__':
myTurtle = turtle.Turtle() # create a turtle
myWin = turtle.Screen() # creates a window for itself to draw in
# drawSpiral(myTurtle, 100)
# myWin.exitonclick()
# myTurtle.left(90)
# myTurtle.up()
# myTurtle.backward(100)
# myTurtle.down()
# myTurtle.color("green")
# fractal_tree(75, myTurtle)
# myWin.exitonclick()
# method of the window that puts the turtle into a wait mode
# until you click inside the window, after which the program cleans up and exits.
myTurtle.right(60)
myTurtle.forward(200)
myTurtle.right(120)
myTurtle.forward(200)
myTurtle.right(120)
myTurtle.forward(200)
| false |
9e9e553c9b507df80c4d616b408236ccc46c1aea | sethips/udacity | /cs101-Introduction-to-Computer-Science/hw3.8.py | 1,809 | 4.28125 | 4 | #!/usr/bin/python2.6
#THREE GOLD STARS
#Sudoku [http://en.wikipedia.org/wiki/Sudoku]
#is a logic puzzle where a game
#is defined by a partially filled
#9 x 9 square of digits where each square
#contains one of the digits 1,2,3,4,5,6,7,8,9.
#For this question we will generalize
#and simplify the game.
#Define a procedure, check_sudoku,
#that takes as input a square list
#of lists representing an n x n
#sudoku puzzle solution and returns
#True if the input is a valid
#sudoku square and returns False
#otherwise.
#A valid sudoku square satisfies these
#two properties:
# 1. Each column of the square contains
# each of the numbers from 1 to n exactly once.
# 2. Each row of the square contains each
# of the numbers from 1 to n exactly once.
correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
def check_sudoku(s):
N=len(s)
M=len(s[0])
if not N==M:
return False
validrows=[]
validcols=[]
for i in range(N):
validrows.append(range(1,N+1))
validcols.append(range(1,N+1))
for i,row in enumerate(s):
for j,el in enumerate(row):
if el in validrows[i]:
validrows[i].remove(el)
else:
return False
if el in validcols[j]:
validcols[j].remove(el)
else:
return False
#print validrows
#print validcols
for v in validrows:
if not (len(v)==0):
return False
for v in validcols:
if not (len(v)==0):
return False
return ((len(validrows)==N) and (len(validcols)==N))
#print check_sudoku(correct) == True
#print check_sudoku(incorrect) == False
| true |
22f6965c923f09ad557efef590dd5fda19b7be93 | sethips/udacity | /cs101-Introduction-to-Computer-Science/hw2.6.py | 483 | 4.1875 | 4 | def print_multiplication_table(N):
"""
Example:
>>> print_multiplication_table(2)
1*1=1
1*2=2
2*1=2
2*2=4
>>> print_multiplication_table(3)
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9
"""
for i in range(1,N+1):
for j in range(1,N+1):
print '{0}*{1}={2}'.format(i,j,i*j)
def _test():
import doctest
doctest.testmod(verbose=True)
if __name__ == "__main__":
_test()
| false |
0283bea14c2ebef73475fc6a5f9e31f88185d2e2 | PhilHuangSW/Leetcode | /rotate_list.py | 1,851 | 4.25 | 4 | #################### ROTATE LIST ####################
# Given a linked list, rotate the list to the right by k places, where k is non-negative.
# **Example 1:**
# ```
# Input: 1->2->3->4->5->NULL, k = 2
# Output: 4->5->1->2->3->NULL
# Explanation:
# rotate 1 steps to the right: 5->1->2->3->4->NULL
# rotate 2 steps to the right: 4->5->1->2->3->NULL
# ```
# **Example 2:**
# ```
# Input: 0->1->2->NULL, k = 4
# Output: 2->0->1->NULL
# Explanation:
# rotate 1 steps to the right: 2->0->1->NULL
# rotate 2 steps to the right: 1->2->0->NULL
# rotate 3 steps to the right: 0->1->2->NULL
# rotate 4 steps to the right: 2->0->1->NULL
# ```
#################### SOLUTION ####################
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# TIME: O(n) -- SPACE: O(1)
# Uses two pointers: a current and previous pointer
# First find the size of the linked list and mod (%) it with k (skips doing cycles)
# Modify the linked list in place by setting the previous node's next to be the end (nil)
# then set the current node's next to head, then set head to the current node
# i.e. 1->2->3->4->5->nil becomes 5->1->2->3->4->nil
# continue doing these shifts until k becomes 0
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head == None:
return head
size = self.size_ll(head)
k = k % size
if k == 0:
return head
current = head
previous = None
while k > 0:
while current.next != None:
previous = current
current = current.next
previous.next = None
current.next = head
head = current
k -= 1
return head
def size_ll(self, node):
size = 1
while node.next != None:
node = node.next
size += 1
return size
| true |
b1f4282c5de6da3f9a8bed1ed3b1b219c9b875d4 | rowbot1/learnpython | /practicepython/Rock_Paper_Scissors.py | 839 | 4.34375 | 4 | """
https://www.practicepython.org/exercise/2014/03/26/08-rock-paper-scissors.html
R P
R S
P R
P S
S R
S P
"""
rock = "r"
paper = "p"
scissors = "s"
# ensures the game contines to play after win event has completed
while True:
p1 = input("Player 1 r p or s: ").lower()
p2 = input("Player 2 r p or s: ").lower()
if p1 == p2:
print("Draw")
elif p1 == rock and p2 == paper:
print("Paper wins")
elif p1 == rock and p2 == scissors:
print("rock wins")
elif p1 == paper and p2 == rock:
print("scissors wins")
elif p1 == paper and p2 == scissors:
print("scissors win")
elif p1 == scissors and p2 == rock:
print("rock wins")
elif p1 == scissors and p2 == paper:
print("scissors wins")
"""idea to make this a network game and randomise who goes first"""
| false |
3d29f6bfdcc709d80e318a0c4f484ab5a431be1b | Deipied/coding_puzzles | /practice.py | 555 | 4.15625 | 4 | def find_outlier(integers):
even_list = []
odd_list = []
for int in integers:
if int%2 == 0:
even_list.append(int)
else:
odd_list.append(int)
if len(even_list) > len(odd_list):
return odd_list[0]
else:
return even_list[0]
# easier and cleaner solution
# def find_outlier(int):
# odds = [x for x in int if x%2!=0]
# evens= [x for x in int if x%2==0]
# return odds[0] if len(odds)<len(evens) else evens[0]
print(find_outlier([2, 4, 6, 8, 10, 3])) | false |
1627158b2f3b1a5fac1e300335d76f517151d842 | GrissomGilbert/Project-Euler-solve | /problem_19.py | 1,266 | 4.25 | 4 | '''
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
'''
import time
month_dict={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
if __name__ == '__main__':
days_count=366
monday_count=0
cal_time=time.time()
for year in range(1901,2001):
for month in range(1,13):
if days_count%7==1:
monday_count+=1
days_count+=month_dict[month]
if month==2 and year%4==0:
if year%400!=0:
pass
else:
days_count+=1
print("calculate time %f"%(time.time()-cal_time))
print("%d days fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)"%monday_count) | true |
c9c4b4958b364c0c493c1bd4b8906e72a08b25e7 | sadok-f/google-foo.bar | /problems/2.1_bunny_prisoner_locating.py | 1,927 | 4.21875 | 4 | """
Bunny Prisoner Locating
=======================
Keeping track of Commander Lambda's many bunny prisoners is starting to get tricky. You've been tasked with writing a program to match bunny prisoner IDs to cell locations.
The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda's space station, and as a result the prison blocks have an unusual layout. They are stacked in a triangular shape, and the bunny prisoners are given numerical IDs starting from the corner, as follows:
| 7
| 4 8
| 2 5 9
| 1 3 6 10
Each cell can be represented as points (x, y), with x being the distance from the vertical wall, and y being the height from the ground.
For example, the bunny prisoner at (1, 1) has ID 1, the bunny prisoner at (3, 2) has ID 9, and the bunny prisoner at (2,3) has ID 8. This pattern of numbering continues indefinitely (Commander Lambda has been taking a LOT of prisoners).
Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y). Each value of x and y will be at least 1 and no greater than 100,000. Since the prisoner ID can be very large, return your answer as a string representation of the number.
Languages
=========
To provide a Python solution, edit solution.py
To provide a Java solution, edit solution.java
Test cases
==========
Inputs:
(int) x = 3
(int) y = 2
Output:
(string) "9"
Inputs:
(int) x = 5
(int) y = 10
Output:
(string) "96"
Time to solve: 72 hours.
"""
def answer(x, y):
base = sum(xx + 1 for xx in range(x))
tail = sum(yy for yy in range(x, x + y - 1))
return base + tail
T = int(raw_input())
for t in range(T):
x, y = map(int, raw_input().split())
answer_in = int(raw_input())
answer_my = answer(x, y)
print("x, y: {}, {}".format(x, y))
print("answer_in: {}".format(answer_in))
print("answer_my: {}".format(answer_my))
print(answer_in == answer_my)
| true |
581e47197efdb38d5bfbf361c657e7bf902b3eb3 | NASA-AMMOS/MMGIS | /private/api/great_circle_calculator/__error_checking.py | 687 | 4.4375 | 4 | # -*- coding: utf-8 -*-
def _error_check_point(point, correct_point=True):
if len(point) != 2:
print("Point", str(point), "is incorrect length!")
return False
lon, lat = float(point[0]), float(point[1])
if -90 <= lat <= 90 and -180 <= lon <= 180: # Point makes sense
return (lon, lat)
# The point is (probably!) reversed
elif -90 <= lon <= 90 and -180 <= lat <= 180:
print("Point", str(point), "is probably reversed!")
if correct_point:
point_corrected = (lat, lon)
return point_corrected
return False
else:
print("Point", str(point), "Cannot be interpreted!")
return False
| true |
5e7278306948569e7d09484324936d1321cc119b | Nockternal/Burger | /intro to programming/Completed Tasks/Task 8/password.py | 1,103 | 4.1875 | 4 |
print ('the Criteria for a strong password is more than 6 characters with uppercase, lowercase and numbers in it')
password = input ('type your password ....')
upcase = False
lowcase = False
passlenth = False
havenum = False
if len(password) >= 6 :
passlenth = True
else:
pass
for char in password:
if char == (char.upper()):
upcase = True
break
else:
pass
for charx in password:
if charx == (charx.lower()):
lowcase = True
break
else:
pass
for chary in password:
if chary.isdigit():
havenum = True
break
else:
pass
if upcase and lowcase and passlenth == True:
print("You have a strong enough password")
elif upcase and passlenth and havenum == True:
print("You have a strong enough password")
elif upcase and lowcase and havenum == True:
print("You have a strong enough password")
elif lowcase and passlenth and havenum == True:
print("You have a strong enough password")
else:
print("You have a weak password...")
| true |
4740d74e75a72871304f8e35cd564e63ac93a3ee | klanghamer/prg105 | /FrequentCharacter.py | 1,338 | 4.3125 | 4 | """
Write a program that lets the user enter a string and displays the letter that
appears most frequently in the string. Ignore spaces, punctuation, and uppercase vs lowercase.
Hints:
Create a list to hold letters based on the length of the user input
Convert all letters to the same case
Use a loop to check for each letter in the alphabet (create an alphabet list and step through it)
Have a variable to hold the largest number of times a letter appears, and replace the value
when a higher number is found
"""
def main():
alpha = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z"]
user_string = input("Enter a phrase: ")
common_letters = ""
maximum = 0
count = 0
for char in alpha:
for letter in user_string:
if char == letter.upper():
count += 1
if count > maximum:
maximum = count
common_letters = char
count = 0
elif count == maximum:
common_letters = common_letters + " " + char
count = 0
else:
count = 0
print("The most common letter is ")
print(common_letters + " appeared " + str(maximum) + " times.")
main()
| true |
25b5596f7295dfb60f14c75982d1956ed4609054 | klanghamer/prg105 | /chapter11.2/employee.py | 1,605 | 4.34375 | 4 | """
Write an Employee class that keeps data attributes for the following pieces of information:
Employee name
Employee number
Next, Write a class named ProductionWorker that is a subclass of the Employee class.
The ProductionWorker class should keep data attributes for the following information
Shift numbered (an integer, such as 1, 2, or 3)
Hourly pay rate
The workday is divided into two shifts: day and night.
The shift attribute will hold an integer value representing the shift that the employee works.
The day shift is shift 1 and the night shift is shift 2.
Write the appropriate accessor and mutator methods (get and set) for each class.
"""
class Employee:
def __init__(self, em_name, em_num):
self.__em_name = em_name
self.__em_num = em_num
def set_em_name(self, em_name):
self.__em_name = em_name
def set_em_num(self, em_num):
self.__em_num = em_num
def get_em_name(self):
return self.__em_name
def get_em_num(self):
return self.__em_num
class ProductionWorker(Employee):
def __init__(self, em_name, em_num, shift_num, hourly_rate):
Employee.__init__(self, em_name, em_num)
self.__shift_num = shift_num
self.__hourly_rate = hourly_rate
def set_shift_num(self, shift_num):
self.__shift_num = shift_num
def set_hourly_rate(self, hourly_rate):
self.__hourly_rate = hourly_rate
def get_shift_num(self):
return self.__shift_num
def get_hourly_rate(self):
return self.__hourly_rate
| true |
b7044a580efc23363d215142ef2cedb2f6c73a24 | klanghamer/prg105 | /ChapterNinePractice.py | 2,995 | 4.46875 | 4 | """
Complete all of the TODO directions
The number next to the TODO represents the chapter
and section that explain the required code
Your file should compile error free
Submit your completed file
"""
import pickle
# TODO 9.1 Dictionaries
# Finish creating the following dictionary by adding three more people and birthdays
birthdays = {'Meri': 'May 16', 'Kathy': 'July 14', 'Trent': 'September 10', 'Kelly': 'April 26', 'Nika': 'May 28'}
# 1.Print Meri's Birthday
print(birthdays['Meri'])
# 2.Create an empty dictionary named registration
registration = {}
# 3.You will use the following dictionary for many of the remaining exercises
miles_ridden = {'June 1': 25, 'June 2': 20, 'June 3': 38, 'June 4': 12, 'June 5': 30, 'June 7': 25}
# print the keys and the values of miles_ridden using a for loop
for key in miles_ridden:
print(key, miles_ridden[key])
# get the value for June 3 and print it, if not found display 'Entry not found', replace the ""
value = "June 3"
print(value)
if value in miles_ridden:
print("The miles ridden for: " + value + " " + str(miles_ridden[value]))
else:
print(value + " was not found.")
# get the value for June 6 and print it, if not found display 'Entry not found' replace the ""
value2 = "June 6"
print(value2)
if value2 in miles_ridden:
print("The miles ridden for: " + value2 + " " + str(miles_ridden[value2]))
else:
print(value2 + " was not found.")
# Use the items method to print the miles_ridden dictionary
for items in miles_ridden.items():
print(items)
# Use the keys method to print all of the keys in miles_ridden
for key in miles_ridden.keys():
print(key)
# Use the pop method to remove june 4 then print the contents of the dictionary
miles_ridden.pop('June 4')
print(miles_ridden.items())
# Use the values method to print the contents of the miles_ridden dictionary
for val in miles_ridden.values():
print(val)
# TODO 9.2 Sets
# Create an empty set named my_set
my_set = set()
# Create a set named days that contains the days of the week
days = {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'}
# get the number of elements from the days set and print it
print("There were: " + str(len(days)) + " elements in the set.")
# Remove Saturday and Sunday from the days set
days.remove('Saturday')
days.remove('Sunday')
print(days)
# Determine if 'Mon' is in the days set
if 'Mon' in days:
print("Mon is in this dictionary")
if 'Mon' not in days:
print("Mon is not in this dictionary")
# TODO 9.3 Serializing Objects (Pickling)
# import the pickle library
# create the output file log and open it for binary writing
output_file = open('miles_ridden.dat', 'wb')
# pickle the miles_ridden dictionary and output it to the log file
pickle.dump(miles_ridden, output_file)
# close the log file
output_file.close()
| true |
7df32feb7dd868525d96d5b11a00b26f5a692db9 | yiamabhishek/Complete-Python-3-Bootcamp | /03-Methods and Functions/Function HomeWork/FHome-3.py | 449 | 4.25 | 4 | #Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.
sample = 'Hello Mr. Rogers, how are you this fine Tuesday?'
def up_low(s):
HCase = 0
LCase = 0
for x in s:
if x.isupper():
HCase += 1
elif x.islower():
LCase += 1
print(f'No. of Upper case characters :{HCase}')
print(f'No. of Lower case characters :{LCase}')
up_low(sample) | true |
94d2f11f82ffe9b016a05f0532a4cc0b8267b15e | mohit5335/python-programs | /classvar.py | 807 | 4.21875 | 4 | #in this program we will see types of class variables in python
"""that is the concept of instance variable and static/class variable"""
class car:
wheels = 4 #static/class variable
def __init__(self):
self.milage = 20 #instance varaible
self.company = 'BMW' #instance variable
c1 = car()
c2 = car()
c1.milage = 10 #instance variable changes within the particular instance
c2.company = 'Audi' #instance variable changes within the particular instance
car.wheels = 2 #static variable changes within the class
print("c1 Milage = :",c1.milage,"\tc1 Company = :",c1.company,"\tc1 Wheels = :",c1.wheels)
print("c2 Milage = :",c2.milage,"\tc2 Company = :",c2.company,"\tc2 Wheels = :",c2.wheels)
| true |
f397e62e51543f973a34dd2289c9bc124fdb1f2b | mohit5335/python-programs | /cal.py | 1,133 | 4.34375 | 4 | # Program make a simple calculator that can add, subtract, multiply and divide using functions#
#this function adds two numbers
def add(x,y):
return (x+y)
#this function subtracts two numbers
def subtract(x,y):
return(x-y)
#this function multiplies two numbers
def multiply(x,y):
return(x*y)
#this function divides two numbers
def divide(x,y):
return(x/y)
#this function gives x to the power y
def power(x,y):
return(x**y)
print("Select Operation")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Power")
#take input from user
n1 = int(input("Enter first number : "))
n2 = int(input("Enter Second number : "))
#enter choice from user
choice=input("Enter Choice 1/2/3/4/5 : ")
if choice == '1':
print( n1, "+", n2, "=",add(n1,n2) )
elif choice == '2':
print( n1, "-", n2, "=",subtract(n1,n2) )
elif choice == '3':
print( n1, "*", n2, "=",multiply(n1,n2) )
elif choice == '4':
print( n1, "/", n2, "=",divide(n1,n2) )
elif choice == '5':
print( n1, "^", n2, "=",power(n1,n2) )
else:
print("Invalid Choice")
print("Please choose from 1 to 5") | true |
033b74f52d971f023ae88c656a68e670cc0e68fc | mohit5335/python-programs | /bubblesort.py | 899 | 4.53125 | 5 | #program to sort list using bubble sort
def sort(list1):
for i in range(len(list1)-1,0,-1): #outer loop from length of list to first index
for j in range(i): #inner loop for checking each element
if list1[j] > list1[j+1]:
temp = list1[j] #temporary variable for holding first value
list1[j] = list1[j+1]
list1[j+1] = temp
print("List after Sorting",list1) #list after sorting
list1 = list() #empty list
num = int(input("Enter the no of elements : ")) #entering elements of list
for i in range(int(num)):
n = input("num : ")
list1.append(int(n))
#list1 = [23,56,84,32,65,45,75,12,34,66] (if list is predefined)
print("List before Sorting",list1) #list after sorting
sort(list1) #calls sort function
| true |
4eab8815ed0761a39a2202c4e3dbdd34b5d65c2e | fselvino/guppe | /pep8.py | 1,693 | 4.125 | 4 | """
PEP8 - Python Enhancement Proposal
São propostas de melhorias para a liguagem Python
The Zen of Python
import this
A ideia da PEP8 é que possamos escrever código python de forma Pythônica.
[1] - Utilize camel case para nomes de classes;
class Calculadora:
pass
class CalculadoraCientifica:
pass
[2] - Utilize nomes em minusculos, separados por underline para funções ou variáveis
def soma():
pass
def soma_dois():
pass
numero = 5
numer_impar = 7
[3] - Utilize 4 espaços para indentação
if 'a' in 'banana':
print('tem')
[4] - Linhas em branco
- Separar funçoes e definiçoes de classe com duas linhas em braco
-Metodos dentro de uma classe devem se separados com uma úunica linha em branco
[5] - Imports
- Imports devem ser sempre feitos em linhas separadas
# Import Errado
import sys, os
# import Correto
import sys
import os
# Não há problemas em utlizar
from types import StringTypes, ListTypes
# Caso tenha muitos imports de um mesmo pacote, recomenda-se fazer
from types import (
StringType,
ListType,
SetType,
OutroType
)
# Imports devem ser colocados no topo do arquivo, logo depois de quaisquer comentários ou docstring e
# antes de constantes ou variáveis globais.
[6] - Espaços em expressões e instruções
# não faça:
funcao( algo[ 1 ], { outro: 2 } )
# Faça:
funcao(algo[1], {outro: 2})
# Não faça:
algo (1)
# Faça:
algo(1)
# Não faça:
dict ['chave'] = lista [indice]
# Faça:
dict['chave'] = lista[indice]
# Não faça:
x = 1
y = 3
variavel_loga = 5
# Faça:
x = 1
y = 5
variavel_loga = 7
[7] - Termine sempre um instrução com uma nova linha
"""
import this
| false |
a066b6aa02c01a0722aff5cb2a28b1ba7f3e126f | Darkwolf007/Programming_with_python_2122 | /submissions/c_dictionaries/dictionaries_diegopajarito.py | 508 | 4.15625 | 4 | cities = {'last_1': 'Bogota', 'last_2': 'Duitama', 'last_3': 'Medellin', 'last_4': 'Barcelona', 'last_5': 'Lisbon'}
print(cities)
cities = { 'Barcelona': {'population': 5474482, 'unemployment_rate': 17.24},
'lisbon': {'population': 2827514, 'unemployment_rate': 7.4},
'Amsterdam': {'population': 2431000, 'unemployment_rate': 3.3} }
cities['Bogota'] = {'population': 7450987, 'unemployment_rate': 11.3}
print(cities)
keys = cities.keys()
for city in keys:
print(cities[city])
| false |
5391a90b0acbf82fd0576f4205373b2369d86831 | roycephillipsjr/LPTHW | /ex40a.py | 1,032 | 4.1875 | 4 | # This is an example of a dictionary
# a dictionary is a way to map one thing to another
# this example is a dictionary with a KEY "apple"
mystuff = {'apple': "I AM APPLES!"}
print(mystuff['apple'])
# This is an example of a module that has been created named mystuff
# That module is "called" by using import to bring the fuctions and variables it has
# you access the fuctions or variables with the . (dot) operator
import mystuffex
mystuffex.apple()
print(mystuffex.tangerine)
################################################################################
print(mystuff['apple']) # get apple from dict
mystuffex.apple() # get apple from module
print(mystuffex.tangerine) # same thing, it's just a variable
################################################################################
class MyStuff_class(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print("I AM CLASSY APPLES!")
thing = MyStuff_class()
thing.apple()
print(thing.tangerine)
| false |
38e98c7ce83b4a1c1823d90d87833b95e6ffe6eb | roycephillipsjr/LPTHW | /ex33_a.py | 733 | 4.1875 | 4 | def less_than(high, increase):
i = 0
numbers = []
while i < high:
# print(f"At the top is {i}")
numbers.append(i)
i = i + increase
print("Numbers now: ", numbers)
# print(f"At the bottom i is {i}")
print("The numbers: ")
return numbers
numbers = less_than(20, 2)
for num in numbers:
print(num)
print()
print('*'*20)
print()
def for_less_than(high, increase):
i = 0
numbers = []
for num in range(i,high,increase):
numbers.append(num)
i = i + increase
print("Numbers now: ", numbers)
print(">>>i=",i)
print("The numbers: ")
return numbers
number_2 = for_less_than(20, 2)
for num in number_2:
print(num)
| false |
37a83139da803c13c53ea6d6cfe6914266047170 | alexshenyuefei/python- | /python/property设置存储器属性.py | 824 | 4.1875 | 4 | # 通过point属性设置点坐标,并返回距离
class Point(object):
def __init__(self):
self.x = 1
self.y = 1
@property #使用装饰器对point进行装饰,那么会自动添加一个叫point的属性,当调用获取point的值时,调用此下一行的方法
def point(self): #设置存储器类型属性的getter
distance = (self.x**2 + self.y**2)**0.5
return distance
@point.setter #使用装饰器对point进行装饰,当对point设置值时,调用下一行的方法
def point(self,value:tuple): #设置存储器类型属性的setter
self.x,self.y = value
pointone = Point()
print(pointone.point) #对象属性point,获取值时调用get_distance
pointone.point = (10, 10) #对象属性point,设置坐标值
print(pointone.point)
| false |
84389cf6306ee0e34348a1c9e73b2df7604bf09e | alexshenyuefei/python- | /python/继承,多继承/多继承.py | 1,689 | 4.375 | 4 | """
多重继承
Python 允许子类继承多个基类
方法解释顺序(MRO)
遵循以下三条原则:
子类永远在父类前面(优先调用子类)
如果有多个父类,会根据它们在列表中的顺序被检查
如果对下一个类存在两个合法的选择,选择第一个父类
"""
"""
属性查找示例,现在的查询方法是采用广度优先
简单属性查找示例
关系详情查看子类父类孙类关系图
它首先查找同胞兄弟,采用一种广度优先的方式。
当查找foo(),它检查GC,然后是C1 和C2,然后在P1 中找到。如果P1 中没有,查找将会到达P2。
查找bar(),它搜索GC 和C1,紧接着在C2 中找到了。这样,就不会再继续搜索到祖父P1 和P2。
新式类也有一个__mro__属性,告诉你查找顺序是怎样的
"""
class P1(object): #(object): # parent class 1 父类1
def foo(self):
print("调用的是P1类的foo方法")
class P2(object):
def foo(self):
print("调用的是P2类的foo方法")
def bar(self):
print("调用的是P2类的bar方法")
class C1(P1,P2):#子类1,从P1,P2 派生
pass
class C2(P1,P2):# 子类2,从P2,P1派生
def bar(self):
print("调用是c2的bar方法")
class GC(C1,C2): # 孙类从C1,C2派生
pass
print(GC.__mro__)
gc = GC()
gc.foo() # GC ==> C1 ==> C2 ==> P1
gc.bar() # GC ==> C1 ==> C2
"""
首先查找同胞兄弟,一个父亲代表同胞兄弟,没有同胞兄弟就找父亲
比如GC继承自C1,C2,先找C1,C1没有,就找C1的兄弟(继承自相同父类,顺序也要一样),C
C1没有兄弟,就找C1的父类.C1的父类没有,再找C2.
C2如果没有就找C2的父类
""" | false |
882f9ed879b74931ca997c7cffb1eebbbc38977d | BramTech/Second-attempt | /Lotto Generator.py | 730 | 4.40625 | 4 | # Lottery Number Generator
# Design a program that generates a seven-digit lottery number. The program should generate seven random numbers, each in the range of 0 through 9,
# and assign each number to a list element. (Random numbers were discussed in Chapter 5 .) Then write another loop that displays the contents of the list.
#Import module
import random
# Create a list with space for 7 random lottery numbers
number_list = [0,0,0,0,0,0,0]
ct = 0
# Create a loop that stores and generates 7 random numbers, discarding duplicates
while ct < 7:
n = random.randint(0,9)
if n not in number_list:
number_list[ct] = n
ct += 1
# Show lottery numbers
print(("Your winning numbers are: ", number_list))
| true |
4f935c89909d5f4c8705383aeced0d9697a2e92a | physics91si/devangiviv-lab13 | /calc.py | 1,669 | 4.25 | 4 | #!/usr/bin/python
# Lab 13
# Physics 91SI
# Spring 2016
import sys
import re
def main():
"""Join command-line arguments and pass them to unitcalc(), then print."""
calculation = ''.join(sys.argv[1:])
print calc(calculation)
#given two numbers and a calculation, returns the appropriate output
def intermediate_result(num1, num2, operation):
if operation=='+':
return float(num1)+float(num2)
elif operation=='-':
return float(num1)-float(num2)
elif operation=='*':
return float(num1)*float(num2)
elif operation=='/':
return float(num1)/float(num2)
def calc(s):
"""Parse a string describing an operation on quantities with units."""
nums = []
operations = []
curr_index = 0
while curr_index < len(s):
if (not s[curr_index].isdigit()):
nums.append(float(s[0:curr_index]))
operations.append(s[curr_index])
s = s[curr_index+1:len(s)]
curr_index = 0
curr_index += 1
nums.append(float(s))
#at this point the lists nums and operations are populated with all the numbers and operations entered
#checks for syntax
assert(len(nums) >= 2)
assert(len(operations) >= 1)
#This does not take into account order of operations but instead just does the computations in the order they are written
result = intermediate_result(nums[0], nums[1], operations[0])
for i in range(2, len(nums)):
result = intermediate_result(result, nums[i], operations[i-1])
print(result)
if __name__ == "__main__": main()
| true |
e20151ca34bb369c851b714e8665ade3bd5ecb77 | mparedes003/Data-Structures | /binary_search_tree/binary_search_tree.py | 1,907 | 4.125 | 4 | class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
new_subtree = BinarySearchTree(value)
# if value is less than root go to left side
if (value < self.value):
# if left side is empty
if not self.left:
# value becomes root of new_subtree
self.left = new_subtree
else:
# else, insert the value
self.left.insert(value)
# if value is greater than or equal to root go to right side
elif value >= self.value:
# if right side is empty
if not self.right:
# value becomes root on new_subtree
self.right = new_subtree
else:
# else, insert the value
self.right.insert(value)
def contains(self, target):
# if root equals target
if self.value == target:
# return True
return True
# Look at the left side
if self.left:
# if left side contains target
if self.left.contains(target):
# return True
return True
# Look at the right side
if self.right:
# if right side conatins target
if self.right.contains(target):
# return True
return True
# otherwise, return False
return False
def get_max(self):
# if no root
if not self:
# return None
return None
# declare that the max value equals the main root
max_value = self.value
# declare that current becomes the root node in question
current = self
while current:
# if the current value in question is greater than the max value
if current.value > max_value:
# current.value becomes the max value
max_value = current.value
# current becomes the child node on the right, because it’s greater
current = current.right
# return max value
return max_value
| true |
892f696a0fb4fdbbfbc314936ab4bc369369b7c7 | Ignis17/CS140 | /Labs/Assignment_28.py | 412 | 4.25 | 4 | # Author: Joel Turbi
# Assignment: Lab Assignment 28
# Course: CS140
def watch(age):
if age < 13:
print("You can not watch the movie! It's PG13. Sorry.")
elif (age == 13) or (age <= 17):
print("You can watch the movie only if accompanied by an adult.")
elif (age == 18) or (age > 18):
print("Enjoy the movie!")
ages = int(input("What is your age? "))
watch(ages)
| true |
d82f4af8f4a062c0b16e281ce4d4fb8d8ce1cead | jusadi/ProjectEuler | /P1.py | 270 | 4.15625 | 4 | # Problem 1
# sum35(max value) -> sum of values under max which are multiples of 3 or 5
def sum35(max):
sum = 0
for i in range(max):
if (i % 3 == 0) or (i % 5 == 0):
sum += i
return sum
if __name__ == "__main__":
print(sum35(1000))
| true |
a1dc1a16c8269b5acffe66b71a5b3f5e29f2cd41 | lierfengmei/pyworks | /ex5_11.py | 1,192 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: 0.1
@author: MM
@license: MM's Licence
@contact: balabala@gmail.com
@site: AllitWell
@software: PyCharm
@file: ex5_11.py
@time: 2016/11/23 9:02
"""
#1)使用循环和算术运算,求出0~20之间所有的偶数
def calEven():
print()
print("Even numbers between 0~20 are:")
for eachNum in range(20):
if eachNum%2==0:
print(eachNum," ",end = "")
def calOdd():
print()
print("Odd numbers between 0~20 are:")
for eachNum in range(20):
if eachNum%2==1:
print(eachNum," ",end = "")
def calDivide():
print()
num1 = int(input("Please input one number:"))
num2 = int(input("Please input another number:"))
if (not num1) and (not num2):
print("two numbers are all zeros!")
return False
elif (not num1) or (not num2):
print("是的,它们有整除关系")
return True
elif (not num1%num2) or (not num2%num1):
print("是的,它们有整除关系")
return True
else:
print("不,它们没有整除关系")
return False
if __name__ == '__main__':
calEven()
calOdd()
calDivide()
| false |
ca8ccea100fdd2c4005b14189c854a125ac84b39 | njerigathigi/learn-python | /if_else.py | 567 | 4.25 | 4 | # Short Hand If
# If you have only one statement to execute, you can put it on the same
# line as the if statement.
a = 5
b = 2
if a > b: print('a is greater than b')
# Short Hand If ... Else
# If you have only one statement to execute, one for if, and one for else
# , you can put it all on the same line:
a = 330
b = 330
print('A') if a > b else print('B')
# This technique is known as Ternary Operators, or Conditional Expressions.
# You can also have multiple else statements on the same line:
print('A') if a > b else print('=') if a == b else print('B')
| true |
1e480e334d914be156402ad5f12b834a51e38f35 | njerigathigi/learn-python | /challenge9.py | 628 | 4.46875 | 4 | #create a function, format_input , that accepts any string and returns all
#numerics in it. Example :
#calling
#format_input('abc123')
#returns '123' as a string
#if input is empty, then return an empty string.
def Format_input(String):
num = ''
if String.isnumeric() == True:
print(String)
elif String == '':
print('')
elif String.isalnum() == True:
for char in String:
if char.isnumeric() == True:
num +=char
print(num)
Format_input('12adsn934')
| true |
e52536e18be7b3f9653e17a25fb3c430ffa201dd | njerigathigi/learn-python | /strip.py | 1,203 | 4.4375 | 4 | # The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end)
# characters (space is the default leading character to remove)
# Syntax
# string.strip(characters)
# Parameter Description
# characters Optional. A set of characters to remove as leading/trailing characters
txt = ",,,,,rrttgg.....banana....rrr"
x = txt.strip(",.grt")
print(x)
print()
#rstrip
# The rstrip() method removes any trailing characters
# (characters at the end a string) ie on the right side of the string.
# space is the default trailing character to remove.
#syntax
# string.rstrip(characters)
# Parameter Description
# characters Optional. A set of characters to remove as trailing characters
# y = txt.rstrip('rrr')
# print(y)
sentence = "banana,,,,,ssqqqww....."
fruit = sentence.rstrip(',sqw.')
print(fruit)
# lstrip
# The lstrip() method removes any leading characters ie to the left of the string
# space is the default leading character to remove
# Syntax
# string.lstrip(characters)
# Parameter Description
# characters Optional. A set of characters to remove as leading characters
txt1 = ",,,,,ssaaww.....banana"
new_txt1 = txt1.lstrip(',saw.')
print(new_txt1)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.