blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
4a8c2ad2eafe2cefe78c0ccd5750f097671c7075
|
GermanSumus/Algorithms
|
/unique_lists.py
| 651
| 4.3125
| 4
|
"""
Write a function that takes two or more arrays and returns a new array of
unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included in their
original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the final
array should not be sorted in numerical order.
"""
def unique_list(a_list, b_list):
for num in a_list:
if num in b_list:
b_list.remove(num)
concat = a_list + b_list
print(concat)
unique_list([1,2,3], [1,2,3,4,5])
unique_list([1,1,7,5], [3,9,4,5])
| true
|
b7ac1cfbb9087510ade29a2d2605b8cc01345d1f
|
GermanSumus/Algorithms
|
/factorialize.py
| 268
| 4.21875
| 4
|
# Return the factorial of the provided integer
# Example: 5 returns 1 * 2 * 3 * 4 * 5 = 120
def factorialize(num):
factor = 1
for x in range(1, num + 1):
factor = factor * x
print(factor)
factorialize(5)
factorialize(10)
factorialize(25)
| true
|
c2790a23c2030775a1ed612e3ee55c594ad30802
|
iamzaidsoomro/Python-Practice
|
/Calculator.py
| 706
| 4.15625
| 4
|
def calc():
choice = "y"
while(choice == "y" or choice == "Y"):
numb1 = input("Enter first number: ")
numb2 = input("Enter second number: ")
op = input("Enter operation: ")
numb1 = int(numb1)
numb2 = int(numb2)
if op == '+': print("Sum = " + str(numb1 + numb2))
elif op == '-': print("Difference = " + str(numb1 - numb2))
elif op == '*': print("Product = " + str(numb1 * numb2))
elif op == '/':
if numb2 != 0: print("division = " + str(numb1 / numb2))
else: print("Undefined")
else: print("Invalid Data")
choice = input("Would you like to perform again? Y/N: ")
calc()
| false
|
8f076f012de7d9e71daff7736fc562eff99078aa
|
kartikay89/Python-Coding_challenges
|
/countLetter.py
| 1,042
| 4.5
| 4
|
"""
Write a function called count_letters(text, letter), which receives as arguments a text (string) and
a letter (string), and returns the number of occurrences of the given letter (count both capital and
small letters!) in the given string. For example, count_letters('trAvelingprogrammer', 'a') should return 2
and count_letters('trAvelingprogrammer', 'A') should return also 2. If you are quite advanced,
use Regular Expressions or Lambda function here :)
"""
def count_letters(text, letter):
newText = text.lower()
result = 0
for letts in newText:
if letter in letts:
result +=1
return result
print(count_letters("Kartikay", "k"))
"""
import testyourcode
# one possibility
def count_letters(text, letter):
return text.lower().count(letter.lower())
# another possibility
import re
def count_letters2(text, letter):
return len(re.findall(letter.lower(), text.lower()))
# another possibility
def count_letters3(text, letter):
return sum(map(lambda x : 1 if letter.lower() in x else 0, text.lower()))
"""
| true
|
7c54349a4f78cefb44bff8616fc370b865849d48
|
kartikay89/Python-Coding_challenges
|
/phoneNum.py
| 1,223
| 4.53125
| 5
|
"""
Imagine you met a very good looking guy/girl and managed to get his/her phone number. The phone number has 9 digits but, unfortunately, one of the digits is missing since you were very nervous while writing it down.
The only thing you remember is that the SUM of all 9 digits was divisible by 10 - your crush was nerdy and that's one of the things you talked about.. :) Write a function called find_missing_digit(pseudo_number) that
takes as input a phone number made out of 8 digits and one 'x' (it is a string, for example '0123x1234') and returns the missing digit (as int).
"""
pseudoNumber = '0123x1234'
probNumbers = []
def divisibleFunction(sumlist):
if sumlist % 10 == 0:
print('True')
return probNumbers.append(sumlist)
def find_missing_digit(pseudo_number):
replacementNum = list(pseudo_number.replace('x', '4'))
# print(replacementNum)
intNums = list(map(int, replacementNum))
# print(intNums)
sums = sum(intNums)
# print(sums)
divisibleFunction(sums)
find_missing_digit(pseudoNumber)
print(probNumbers)
"""
def find_missing_digit(pseudo_number):
digits_sum = sum([int(i) for i in pseudo_number if i!='x'])
for i in range(10):
if (digits_sum+i)%10==0:
return i
"""
| true
|
c3bd11215bb589aa0940cf92e249d2dd8815b8e8
|
ravenawk/pcc_exercises
|
/chapter_07/deli.py
| 413
| 4.28125
| 4
|
#!/usr/bin/env python3
'''
Making sandwiches with while loops and for loops
'''
sandwich_orders = ['turkey', 'tuna', 'ham']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
finished_sandwiches.append(current_sandwich)
print(f"I made your {current_sandwich} sandwich.")
for sandwich in finished_sandwiches:
print(f"A {sandwich} sandwich was made today.")
| true
|
b0ee2dc3c3865353f42b2b18c45e0a8b77c7c7bc
|
ravenawk/pcc_exercises
|
/chapter_04/slices.py
| 326
| 4.25
| 4
|
#!/usr/bin/env python3
list_of_cubes = [ value**3 for value in range(1,11)]
for cube in list_of_cubes:
print(cube)
print(f"The first 3 items in the list are {list_of_cubes[:3]}.")
print(f"Three items in the middle of the list are {list_of_cubes[3:6]}.")
print(f"The last 3 items in the list are {list_of_cubes[-3:]}.")
| true
|
f87fbc9f1ad08e89dd1fd5e561bf0956f01b2a6e
|
ravenawk/pcc_exercises
|
/chapter_07/dream_vacation.py
| 381
| 4.21875
| 4
|
#!/usr/bin/env python3
'''
Polling for a dream vacation
'''
places_to_visit = []
poll = input("Where would you like to visit some day? ")
while poll != 'quit':
places_to_visit.append(poll)
poll = input("Where would you like to visit one day? (Enter quit to end) ")
for place in places_to_visit:
print(f"{place.title()} is one of the places people wanted to visit.")
| true
|
b102953b0aaef366c4056dfb9b94210c416b7512
|
ravenawk/pcc_exercises
|
/chapter_08/user_albums.py
| 514
| 4.34375
| 4
|
#!/usr/bin/env python3
'''
Function example of record album
'''
def make_album(artist_name, album_title, song_count=None):
''' Create album information '''
album = {'artist': artist_name, 'album name': album_title,}
if song_count:
album['number of songs'] = song_count
return album
while True:
ARTIST = input("What is the artis's name? (enter quit to exit) ")
if ARTIST == 'quit':
break
ALBUM = input("What is the album's name? ")
print(make_album(ARTIST, ALBUM))
| true
|
0d1604f91d1634f8d3d55d54edc6ed1bc0ce44ca
|
Tananiko/python-training-2020-12-14
|
/lists.py
| 709
| 4.15625
| 4
|
names = [] # ures lista
names = ["John Doe", "Jane Doe", "Jack Doe"]
john = ["John Doe", 28, "johndoe@example.com"]
print(names[0])
print(names[1])
# print(names[4]) # list index out of range
print(names[::-1])
print(names)
numbers = [1, 2, 3, 4, 5]
print(numbers)
print(len(numbers))
employees = [['John Doe', 1970], ['Jack Doe', 1980]]
print(employees[1][1])
for name in names:
print(name)
print(3 in numbers)
print('Jack Smith' in names)
odd_numbers = [1, 3, 5, 7]
even_numbers = [2, 4, 6, 8]
print(odd_numbers + even_numbers)
print(odd_numbers * 3)
# s = "John Doe" nem modosithato = immutable
# s[3] = "X"
even_numbers[0] = 22 # modosithato - mutable
print(even_numbers)
even_numbers.clear()
print(even_numbers)
| false
|
12c1a2d3672a7f0c7d391e958e8a047ff3893106
|
joesprogramming/School-and-Practice
|
/Calculate Factorial of a Number CH 4 pgm 10.py
| 281
| 4.25
| 4
|
# Joe Joseph
# intro to programming
# Ask user for a number
fact = int(input('Enter a number and this program will calculates its Factorial: ',))
# define formula
num = 1
t = 1
#run loop
while t <= fact:
num = num * t
t = t + 1
print(num)
| true
|
b931256e821d0b59a907d580734f21c455c22eb4
|
joesprogramming/School-and-Practice
|
/person customer/person.py
| 1,175
| 4.125
| 4
|
#Joe Joseph
# Intro to Programming
#Primary Class
class Person:
def __init__(self, name_p, address_1, phone_1):
self.__name_p = name_p
self.__address_1 = address_1
self.__phone_1 = phone_1
def set_name_p(self, name_p):
self.__name_p = name_p
def set_address_1(self, address_1):
self.__address_1 = address_1
def set_phone_1(self, phone_1):
self.__phone_1 = phone_1
# Methods
def get_name_p(self):
return self.__name_p
def get_address_1(self):
return self.__address_1
def get_phone_1(self):
return self.__phone_1
#Subclass
class Customer(Person):
def __init__(self, name, mail):
self.__name = name
self.__mail = mail
#Boolean Function
def list_mail(self):
#Loop for mailing list
if self.__mail == 'Y':
print('Welcome to the mailing list')
else:
print('You have been removed')
def get_name(self):
return self.__name
def get_mail(self):
return self.__mail
| false
|
6a159a65ea848c61eb4b35980b2bd524a5487b56
|
BzhangURU/LeetCode-Python-Solutions
|
/T522_Longest_Uncommon_Subsequence_II.py
| 2,209
| 4.125
| 4
|
##Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
##
##A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
##
##The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
##
##Example 1:
##Input: "aba", "cdc", "eae"
##Output: 3
##Note:
##
##All the given strings' lengths will not exceed 10.
##The length of the given list will be in the range of [2, 50].
##My comments: if subsequence of string a is LUS, then a must be LUS. So we
## sort strings, and find the longest LUS. ##def findLUSlength(strs: List[str]) -> int:
import functools
class Solution:
def cmpStr(self, a, b):
if len(a)!=len(b):
return len(b)-len(a)
else:
for i in range(len(a)):
if a[i]!=b[i]:
return ord(a[i])-ord(b[i])
return 0
def isSubsequence(self, a, b):
if len(a)>len(b):
return False
else:
j=0
for i in range(len(a)):
while a[i]!=b[j]:
j=j+1
if j>=len(b) or len(a)-i>len(b)-j:
return False
j=j+1
return True
#Check if string a is subsequence of b
def findLUSlength(self, strs: List[str]) -> int:
strs2=sorted(strs, key=functools.cmp_to_key(self.cmpStr))
for i in range(len(strs2)):
isLUS=True
if i<len(strs2)-1:
if strs2[i]==strs2[i+1]:
continue
for j in range(i):
if self.isSubsequence(strs2[i], strs2[j]):
isLUS=False
break
if isLUS:
return len(strs2[i])
return -1
| true
|
b339e1b0f40936bbb6974725c525364fa0667a49
|
Andrejs85/izdruka
|
/for_cikls.py
| 1,706
| 4.1875
| 4
|
#iteracija - kadas darbibas atkartota izpildišana
mainigais=[1,2,3]
for elements in mainigais:
print(elements) #darbibas kas javeic
#izdruka list elementus
myList=[1,2,3,4,5,6,7,8,9,10,11,12]
for sk in myList:
print(sk)
for _ in myList:
print("Sveiki!") #var nerakstit cikla mainiga nosaukumu
#izdruka tikai parra skaitļus
for sk in myList:
if sk%2==0:
print(sk)
else:
print(f"{sk} ir nepara skaitlis")
#summas apreķinašana
myList=[1,2,3,4,5,6,7,8,9,10,11]
summa=0
for sk in myList:
summa=summa+sk
print(f"Pēc {sk} skaitļu saskaitišanas summa ir {summa}")
print(summa)
#drukā tekstu
myString="Sveika, pasaue!"
for burts in myString:
print(burts)
for burts in "programma":
print(burts, end=" ")
#druka tuple
tup=(1,2,3,4)
for elements in tup:
print(elements)
myList=[(1,2), (3,4), (5,6), (7,8)] #packed tuple
print(len(myList))
for elements in myList:
print(elements)
for viens,otrs in myList: #var nelikt iekavas
print(viens)
print(otrs)
myList=[(1,2,3), (4,5,6), (7,8,9)]
for a,b,c in myList:
print(b)
#vardnicas
d={"k1":11, "k2":12, "k3":13}
for elements in d:
print(elements) #izdruka tikai atslegas
for elements in d.items():
print(elements) #drukā pārus
for atslega, vertiba in d.items():
print(vertiba)
print(atslega)
#Given an Integer N, print all the numbers from1 to N.
#ar skaitļiem izmanto funkciju range()
for skaitlis in range(15): #izdruka visus skaitļus no [0;15)
print(skaitlis)
for skaitlis in range(5, 15): #izdruka visus skaitļus no [5;15)
print(skaitlis)
for skaitlis in range(5,15,2): #izdruka visus skaitļus no [0;15) ar soli 2
print(skaitlis)
| false
|
79d8085cb879c116c4092396ecc83fa1b7f2b5d2
|
SanaaShah/Python-Mini-Assignments
|
/6__VolumeOfSphere.py
| 290
| 4.5625
| 5
|
# 6. Write a Python program to get the volume of a sphere, please take the radius as input from user. V=4 / 3 πr3
from math import pi
radius = input('Please enter the radius: ')
volume = 4 / (4 * pi * 3 * radius**3)
print('Volume of the sphere is found to be: '+str(round(volume, 2)))
| true
|
4ac590cb424a5d27fc41ccfe671b7c42db027139
|
SanaaShah/Python-Mini-Assignments
|
/30__OccurenceOfLetter.py
| 331
| 4.21875
| 4
|
# 30. Write a Python program to count the number occurrence of a specific character in a string
string = input('Enter any word: ')
word = input('Enter the character that you want to count in that word: ')
lenght = len(string)
count = 0
for i in range(lenght):
if string[i] == word:
count = count + 1
print(count)
| true
|
53577eb885ed53f2ba4c0d09fa7a0262ff6fdb2f
|
SanaaShah/Python-Mini-Assignments
|
/2__checkPositive_negative.py
| 350
| 4.4375
| 4
|
# 2. Write a Python program to check if a number is positive, negative or zero
user_input = float(input('Please enter any number: '))
if user_input < 0:
print('Entered number is negative.')
elif user_input > 0:
print('Entered number is positive')
elif user_input == 0:
print('You have entered zero, its neither negative nor positive')
| true
|
f81383ec7b0b8be08c8c40ec057866c6b4383879
|
SanaaShah/Python-Mini-Assignments
|
/1__RadiusOfCircle.py
| 299
| 4.53125
| 5
|
# 1. Write a Python program which accepts the radius of a circle from the user and compute the area
from math import pi
radius = float((input('Please enter the radius of the cricle: ')))
print('Area of the circle of radius: '+str(radius) + ' is found to be: '+str(round((pi * radius**2), 2)))
| true
|
06827bf14302ec76a9b9d64a66273db96e3746fa
|
duplys/duplys.github.io
|
/_src/recursion/is_even.py
| 557
| 4.59375
| 5
|
"""Example for recursion."""
def is_even(n, even):
"""Uses recursion to compute whether the given number n is even.
To determine whether a positive whole number is even or odd,
the following can be used:
* Zero is even
* One is odd
* For any other number n, its evenness is the same as n-2
"""
if n == 0:
even = True
elif n == 1:
even = False
else:
even = is_even(n-2, even)
return even
for i in range(1,20):
val = None
print("[*] Is {0} even? {1}".format(i, is_even(i, val)))
| true
|
c3a181aea806b68ce09197560eeb485ca6d8419d
|
jamesb97/CS4720FinalProject
|
/FinalProject/open_weather.py
| 1,535
| 4.25
| 4
|
'''
Python script which gets the current weather data for a particular zip code
and prints out some data in the table.
REST API get weather data which returns the Name, Current Temperature,
Atmospheric Pressure, Wind Speed, Wind Direction, Time of Report.
'''
import requests
#Enter the corresponding api key from openweather
API_key = ""
base_url = "http://api.openweathermap.org/data/2.5/weather?"
#User is prompted to enter the city name or zip code
city_name = input('Enter City Name: ')
#Instantiate corresponding url from openweather_api
Final_url = base_url + "appid=" + API_key + "&q=" + city_name
weather_data = requests.get(Final_url).json()
#Get input for current temperature
temp = weather_data['main']['temp']
#Get input for the current pressure
pressure = weather_data['main']['pressure']
#Get input for wind speed
wind_speed = weather_data['wind']['speed']
#Get input for wind direction
wind_direction = weather_data['wind']['deg']
#Get input for the current weather description
description = weather_data['weather'][0]['description']
#Print the data to the console
print('\nCurrent Temperature: ', temp, "K")
print('\nAtmospheric Pressure: ', pressure, "hpa")
print('\nWind Speed: ', wind_speed, "m/h")
print('\nWind Direction: ', wind_direction)
print('\nDescription: ', description)
#Import Date and Time module for displaying the current time report.
import datetime
now=datetime.datetime.now()
print("\nTime of Report: ")
print(now.strftime('%Y-%m-%d %H:%M:%S'))
| true
|
18200cb8e9e584fe454d57f3436a9184159388b8
|
ayoubabounakif/edX-Python
|
/ifelifelse_test1_celsius_to_fahrenheit.py
| 811
| 4.40625
| 4
|
#Write a program to:
#Get an input temperature in Celsius
#Convert it to Fahrenheit
#Print the temperature in Fahrenheit
#If it is below 32 degrees print "It is freezing"
#If it is between 32 and 50 degrees print "It is chilly"
#If it is between 50 and 90 degrees print " It is OK"
#If it is above 90 degrees print "It is hot"
# Code Starts Here
user_input = input("Please input a temperature in Celsius:")
celsius = float(user_input)
fahrenheit = ((celsius * 9) / 5 ) +32
print ("The temperature is ",fahrenheit, "degrees Fahrenheit")
if fahrenheit < 32:
print ("It is freezing")
elif 32 <= fahrenheit <= 50:
print ("It is chilly")
elif 50 < fahrenheit < 90:
print ("It is OK")
elif fahrenheit >= 90:
print ("It is hot")
| true
|
b9804e7911242e9c4eae1074e8ef2949155d60e0
|
ayoubabounakif/edX-Python
|
/sorting.py
| 515
| 4.125
| 4
|
# Lets sort the following list by the first item in each sub-list.
my_list = [[2, 4], [0, 13], [11, 14], [-14, 12], [100, 3]]
# First, we need to define a function that specifies what we would like our items sorted by
def my_key(item):
return item[0] # Make the first item in each sub-list our key
new_sorted_list = sorted(my_list, key=my_key) # Return a sorted list as specified by our key
print("The sorted list looks like:", new_sorted_list)
| true
|
f3019b4227dfd2a758d0585fb1c2f9e27df1b8e9
|
ayoubabounakif/edX-Python
|
/quizz_1.py
| 275
| 4.28125
| 4
|
#a program that asks the user for an integer 'x'
#and prints the value of y after evaluating the following expression:
#y = x^2 - 12x + 11
import math
ask_user = input("Please enter an integer x:")
x = int(ask_user)
y = math.pow(x,2) - 12*x + 11
print(int(y))
| true
|
7013c99a792f116a7b79f4ad1a60bfb3f4b1a8a2
|
ayoubabounakif/edX-Python
|
/quizz_2_program4.py
| 1,141
| 4.34375
| 4
|
#Write a program that asks the user to enter a positive integer n.
#Assuming that this integer is in seconds,
#your program should convert the number of seconds into days, hours, minutes, and seconds
#and prints them exactly in the format specified below.
#Here are a few sample runs of what your program is supposed to do:
#when user enters : ---> 369121517
#your program should print:
# 4272 days 5 hours 45 minutes 17 seconds
#when user enters : ---> 24680
#your program should print:
# 0 days 6 hours 51 minutes 20 seconds
#when user enters : ---> 129600
#your program shoudl print:
# 1 days 12 hours 0 minutes 0 seconds
# CODE
#1 minute = 60 seconds
#1 hours = 60 * 60 = 3600 seconds
#1 day = 60 * 60 * 24 = 86400 seconds
sec = int(input("Enter the number of seconds:"))
time = int(sec)
days = time // 86400
hours = (time - (days * 86400)) // 3600
minuts = (time - ((days * 86400) + (hours * 3600)) ) // 60
seconds = (time - ((days * 86400) + (hours * 3600) + (minuts * 60)))
print (days, 'days' ,hours,'hours',minuts, 'minutes',seconds,'seconds')
| true
|
940e284ec16e99a3349d00e0611e487cdce976f1
|
ayoubabounakif/edX-Python
|
/quizz_3_part3.py
| 397
| 4.1875
| 4
|
# Function that returns the sum of all the odd numbers in a list given.
# If there are no odd numbers in the list, your function should return 0 as the sum.
# CODE
def sumOfOddNumbers(numbers_list):
total = 0
count = 0
for number in numbers_list:
if (number % 2 == 1):
total += number
if (number == count):
return (0)
return total
| true
|
9774dac844cb3985d733af0c87e697b85f93be88
|
ayoubabounakif/edX-Python
|
/for_loop_ex2.py
| 296
| 4.3125
| 4
|
#program which asks the user to type an integer n
#and then prints the sum of all numbers from 1 to n (including both 1 and n).
# CODE
ask_user = input("Type an integer n:")
n = int(ask_user)
i = 1
sum = 0
for i in range(1, n+1):
sum = sum + i
print (sum)
| true
|
69b29ccaa611a0e92df5f8cd9b3c59c231847b72
|
fingerman/python_fundamentals
|
/python-fundamentals/4.1_dict_key_value.py
| 1,032
| 4.25
| 4
|
'''
01. Key-Key Value-Value
Write a program, which searches for a key and value inside of several key-value pairs.
Input
• On the first line, you will receive a key.
• On the second line, you will receive a value.
• On the third line, you will receive N.
• On the next N lines, you will receive strings in the following format:
“key => {value 1};{value 2};…{value X}”
After you receive N key -> values pairs, your task is to go through them
and print only the keys, which contain the key and the values, which contain the value.
Print them in the following format:
{key}:
-{value1}
-{value2}
…
-{valueN}
Examples
Input:
bug
X
3
invalidkey => testval;x;y
debug => XUL;ccx;XC
buggy => testX;testY;XtestZ debug:
Output:
-XUL
-XC
buggy:
-testX
-XtestZ
---------------------------
Input:
key
valu
2
xkeyc => value;value;valio
keyhole => valuable;x;values
Output:
xkeyc:
-value
-value
keyhole:
-valuable
-values
'''
key = input()
value = input()
n = int(input())
for _ in range(0, n):
line = input()
print(i)
| true
|
41b3d14d2ff362836aaf33ab6d7af0382b240d22
|
fingerman/python_fundamentals
|
/python_bbq/1tuple/tup_test.py
| 580
| 4.40625
| 4
|
"""
tuples may be stored inside tuples and lists
"""
myTuple = ("Banane", "Orange", "Apfel")
myTuple2 = ("Banane1", "Orange1", "Apfel1")
print(myTuple + myTuple2)
print(myTuple2[2])
tuple_nested = ("Banane", ("Orange", "Strawberry"), "Apfel")
print(tuple_nested)
print(tuple_nested[1])
print(type(tuple_nested[1]))
tuple_list = ("Banane", ["Orange", "Strawberry"], "Apfel")
print(tuple_list)
print(type(tuple_list))
print(tuple_list[1])
print(type(tuple_list[1]))
list_tuple = ["Banane", ("Orange", "Strawberry"), "Apfel"]
print(type(list_tuple))
print(type(list_tuple[1]))
| false
|
b0936ba1bc7bc61bec45b91ebb9467b0da6cd47e
|
fingerman/python_fundamentals
|
/python_bbq/OOP/008 settergetter.py
| 1,220
| 4.46875
| 4
|
class SampleClass:
def __init__(self, a):
## private varibale or property in Python
self.__a = a
## getter method to get the properties using an object
def get_a(self):
return self.__a
## setter method to change the value 'a' using an object
def set_a(self, a):
self.__a = a
## creating an object
obj = SampleClass(10)
## getting the value of 'a' using get_a() method
print(obj.get_a())
## setting a new value to the 'a' using set_a() method
obj.set_a(45)
print(obj.get_a())
print(obj.__dict__)
#SampleClass hides the private attributes and methods.
#It implements the encapsulation feature of OOPS.
#This is how you implement private attributes, getters, and setters in Python.
#The same process was followed in Java.
#Let's write the same implementation in a Pythonic way.
class PythonicWay:
def __init__(self, a):
self.a = a
#You don't need any getters, setters methods to access or change the attributes.
#You can access it directly using the name of the attributes.
## Creating an object for the 'PythonicWay' class
obj = PythonicWay(100)
print(obj.a)
#PythonicWay doesn't hide the data.
#It doesn't implement any encapsulation feature.
| true
|
45b01f271a65e346353cc5fcd18383ff480b8c9d
|
fingerman/python_fundamentals
|
/python-fundamentals/exam_Python_09.2018/1.DateEstimation.py
| 1,251
| 4.4375
| 4
|
'''
Problem 1. Date estimation
Input / Constraints
Today is your exam. It’s 26th of August 2018. you will be given a single date in format year-month-day. You should estimate if the date has passed regarding to the date mention above (2018-08-26), if it is not or if it is today. If it is not you should print how many days are left till that date. Note that the current day stills count!
Date Format:
yyyy-mm-dd
Output
The output should be printed on the console.
If the date has passed you should print the following output:
• "Passed"
If the day is today:
"Today date"
If the date is future:
• "{number of days} days"
INPUT
2018-08-20
Output
Passed
--------------------------
Input
2021-08-26
1097 days left
--------------------------
Input - today
2018-08-26
Today date
'''
import datetime
list_nums = [int(item) for item in input().split('-')]
date_input = datetime.date(list_nums[0], list_nums[1], list_nums[2])
date_today = datetime.datetime.now().date()
if date_today == date_input:
print("Today date")
if date_input < date_today:
print("Passed")
if date_input > date_today:
days_left = date_input - date_today
days_left = days_left + datetime.timedelta(days=1)
print(f'{days_left.days} days left')
| true
|
d1d7f48647893caeefd979258abd684763d507ba
|
rgbbatista/devaria-python
|
/exercícios 2.py
| 1,859
| 4.25
| 4
|
'''Escrever um prog que recebe dois num e um operador
matemático e com isso executa um calculo corretamente'''
def soma(num1 , num2): # criando função
print('Somando', num1 + num2)
resultado = num1 + num2
return resultado
def subtracao(num1 , num2): # criando função
print('Subtraindo', num1 - num2)
resultado = num1 - num2
return resultado
def multiplicacao(num1 , num2): # criando função
print('mutiplicando', num1 * num2)
resultado = num1 * num2
return resultado
def divisao(num1 , num2): # criando função
print('dividindo', num1 / num2)
resultado = num1 / num2
return resultado
if __name__ == '__main__':
num1 = int(input('Informe o primeiro número: '))
num2 = int(input('Informe o segundo número: '))
operador = input('Informe um operador matemático: ')
if operador == '+':
resultado = soma(num1 , num2)
elif operador == '-':
resultado = subtracao(num1,num2)
elif operador == '*':
resultado = multiplicacao(num1,num2)
elif operador == '/':
resultado = divisao(num1, num2)
else:
print('Operador incorreto')
print( f'O resultado da operação é: {resultado}')
''' minha forma de fazer
if __name__ == '__main__':
num1 = int(input('Informe o primeiro número: '))
num2 = int(input('Informe o segundo número: '))
operador = input('Informe um operador matemático: ')
if operador =='+':
print('a soma dos números digitados é: ',num1 + num2)
elif operador == '-':
print('a subtração dos números digitados é: ', num1 - num2)
elif operador == '/':
print ('a adivisão dos números digitados é: ', num1 / num2)
elif operador == '*':
print('A multiplicação dos números é: ', num1 * num2)
else:
print('operador inválido' )'''
| false
|
ec67e60dc31824809ecf5024ce76c1708a46b295
|
rmalarc/is602
|
/hw1_alarcon.py
| 1,967
| 4.28125
| 4
|
#!/usr/bin/python
# Author: Mauricio Alarcon <rmalarc@msn.com>
#1. fill in this function
# it takes a list for input and return a sorted version
# do this with a loop, don't use the built in list functions
def sortwithloops(input):
sorted_input = input[:]
is_sorted = False
while not is_sorted:
changes = False
for i in range(len(sorted_input)-1):
if (sorted_input[i] > sorted_input[i+1]):
changes = True
tmp = sorted_input[i]
sorted_input[i] = sorted_input[i+1]
sorted_input[i+1] = tmp
is_sorted = not(changes)
return sorted_input
#2. fill in this function
# it takes a list for input and return a sorted version
# do this with the built in list functions, don't us a loop
def sortwithoutloops(input):
sorted_input = input[:]
sorted_input.sort()
return sorted_input#return a value
#3. fill in this function
# it takes a list for input and a value to search for
# it returns true if the value is in the list, otherwise false
# do this with a loop, don't use the built in list functions
def searchwithloops(input, value):
found=False
for i in range(len(input)):
found = input[i] == value
if (found):
break
return found #return a value
#4. fill in this function
# it takes a list for input and a value to search for
# it returns true if the value is in the list, otherwise false
# do this with the built in list functions, don't use a loop
def searchwithoutloops(input, value):
return value in input #return a value
if __name__ == "__main__":
L = [6,3,6,3,13,5,5]
print sortwithloops(L) # [3, 3, 5, 5, 6, 6, 13]
print sortwithoutloops(L) # [3, 3, 5, 5, 6, 6, 13]
print searchwithloops(L, 5) #true
print searchwithloops(L, 11) #false
print searchwithoutloops(L, 5) #true
print searchwithoutloops(L, 11) #false
| true
|
1ead53f839aedb80b3d3360ad1d1c972710a2d69
|
Austinkrobison/CLASSPROJECTS
|
/CIS210PROJECTS/PROJECT3/DRAW_BARCODE/draw_barcode.py
| 2,588
| 4.15625
| 4
|
"""
draw_barcode.py: Draw barcode representing a ZIP code using Turtle graphics
Authors: Austin Robison
CIS 210 assignment 3, part 2, Fall 2016.
"""
import argparse # Used in main program to obtain 5-digit ZIP code from command
# line
import time # Used in main program to pause program before exit
import turtle # Used in your function to print the bar code
## Constants used by this program
SLEEP_TIME = 30 # number of seconds to sleep after drawing the barcode
ENCODINGS = [[1, 1, 0, 0, 0], # encoding for '0'
[0, 0, 0, 1, 1], # encoding for '1'
[0, 0, 1, 0, 1], # encoding for '2'
[0, 0, 1, 1, 0], # encoding for '3'
[0, 1, 0, 0, 1], # encoding for '4'
[0, 1, 0, 1, 0], # encoding for '5'
[0, 1, 1, 0, 0], # encoding for '6'
[1, 0, 0, 0, 1], # encoding for '7'
[1, 0, 0, 1, 0], # encoding for '8'
[1, 0, 1, 0, 0] # encoding for '9'
]
SINGLE_LENGTH = 25 # length of a short bar, long bar is twice as long
def compute_check_digit(digits):
"""
Compute the check digit for use in ZIP barcodes
args:
digits: list of 5 integers that make up zip code
returns:
check digit as an integer
"""
sum = 0
for i in range(len(digits)):
sum = sum + digits[i]
check_digit = 10 - (sum % 10)
if (check_digit == 10):
check_digit = 0
return check_digit
"""
Draws a single bar
args:
digit: either 1 or 0
output:
a bar of length 25 if digit is 0, or length 50 if digit is 1
"""
def draw_bar(my_turtle, digit):
my_turtle.left(90)
if digit == 0:
length = SINGLE_LENGTH
else:
length = 2 * SINGLE_LENGTH
my_turtle.forward(length)
my_turtle.up()
my_turtle.backward(length)
my_turtle.right(90)
my_turtle.forward(10)
my_turtle.down()
"""
Draws a chuck of a barcode
args:
the zip code to be translated
output:
a chunck of a barcode in turtle graphics
"""
def draw_zip(my_turtle, zip):
for digit_spot in str(zip):
digit = int(digit_spot)
for barcode_chunk in ENCODINGS[digit]:
draw_bar(my_turtle, barcode_chunk)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("ZIP", type=int)
args = parser.parse_args()
zip = args.ZIP
if zip <= 0 or zip > 99999:
print("zip must be > 0 and < 100000; you provided", zip)
else:
my_turtle = turtle.Turtle()
draw_zip(my_turtle, zip)
time.sleep(SLEEP_TIME)
if __name__ == "__main__":
main()
| true
|
8dd8056d42f4b32c463bc559c4ee173c2339e067
|
tlarson07/dataStructures
|
/tuples.py
| 1,378
| 4.3125
| 4
|
#NOTES 12/31/2016
#Python Data Structures: Tuples
#Similar to lists BUT
#Can't be changed after creation (NO: appending, sorting, reversing, etc.
#Therefore they are more efficient
friends = ("Annalise", "Gigi", "Kepler") #
numbers = (13,6,1,23,7)
print friends[1]
print max(numbers)
(age,name) = (15,"Lauren") #assigning two variables at once
print name
print age
age,name = (15,"Lauren") #assigning two variables at once WITHOUT parathesis
print name
print age
print (18,33,75) > (8,32,2) #tuples are compariable, runs through each element until False, or prints True
#DICTIONARY ----> LIST of TUPLES ----> SORTED LIST
family = {"Lauren":15, "Paige":10, "Tanner":18, "Jennifer":43, "Bruce": 50}
t = family.items() #turns dict (family) into a list of tuples (t)
print t
t.sort() #sorts the list of tuples by keys
print t
#DICTIONARY ----> LIST of SORTED TUPLES
family = {"Lauren":15, "Paige":10, "Tanner":18, "Jennifer":43, "Bruce": 50}
t = sorted(family.items()) #creates sorted list of tuples (key, value pair) from a dictionary
print t
for person, age in sorted(family.items()):
print person,age
tAge = list() #creates an empty list (tAge)
for person, age in family.items(): #for key/value (person,age) in list of tuples(family)
tAge.append((age,person)) #append tuple (age,person)
tAge.sort() #sorts list (tAge), where the key is currenty age
print tAge
| true
|
211273d69389aee16e11ffc9cf9275c0f509029e
|
sudhapotla/untitled
|
/Enthusiastic python group Day-2.py
| 2,426
| 4.28125
| 4
|
# Output Variables
# python uses + character to combine both text and Variable
x = ("hard ")
print("we need to work " + x)
x = ("hardwork is the ")
y = (" key to success")
z = (x + y)
print(z)
#Create a variable outside of a function, and use it inside the function
x = "not stressfull"
def myfunc():
print("Python is " + x)
myfunc()
# Create a variable inside a function, with the same name as the global variable
x = "not stressfull"
def myfunc():
x = "may be sometimes hard"
print("python " + x)
myfunc()
print("python is " + x)
# To create a global variable inside a function, you can use the global keyword
def myfunc():
global x
x = "easy"
myfunc()
print ("python is "+ x)
#To change the value of a global variable inside a function, refer to the variable by using the global keyword:
x = "easy"
def myfunc():
global x
x = "hard"
myfunc()
print("python is " + x)
# Learning DataTypes
x = 9
print(type(x))
x = " is everybody's lucky number" # str
print(type(x))
x = 20.5
print(type(x))
x = 1j
print(type(x))
x = ["sarees", "blouses", "dresses"]
print(type(x))
x = ("gavvalu", "chekkalu", "kova")
print(type(x))
x = range(7)
print(type(x))
x = {"name": "Pluto", "age": 12}
print(type(x))
x = {"apple", "banana", "cherry"}
print(type(x))
x = frozenset({"apple", "banana", "cherry"})
print(type(x))
x = True
print(x)
print(type(x))
x = b"Hello"
print(type(x))
x = bytearray(5)
print(x)
print(type(x))
x = memoryview(bytes(5))
print(type(x))
# Learning Python numbers
# Integers
x = 7
y = 35656222554887711
z = -67890
print(type(x))
print(type(y))
print(type(z))
#Float
x = 2.10
y = 7.0
z = -36.59
print(type(x))
print(type(y))
print(type(z))
#Complex
x= 1j
y= 7+5j
z= -5j
print(type(x))
print(type(x))
print(type(x))
# converting from one type to another with the int(), float(), and complex() methods:
x = 1 #int
y = 2.5 #float
z = 1+5j #complex
# convert from int to float
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x) #cannot convert complex numbers into another number type.
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
# Random numbers
#Python does not have a random() function to make a random number, but Python has a built-in module
#called random that can be used to make random numbers:
import random
import random
print(random.randrange(2, 100))
| true
|
deaa241ca580c969b2704ae2eb830487b247c766
|
sudhapotla/untitled
|
/Python variables,Datatypes,Numbers,Casting.py
| 1,192
| 4.25
| 4
|
#Python Variables
#Variables are containers for storing data values.
#Rules for Variable names
#A variable name must start with a letter or the underscore character
#A variable name cannot start with a number
#A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
#Variable names are case-sensitive (age, Age and AGE are three different variables)
my_name="sudha"
address="westchester"
print(my_name)
print(address)
#python uses + character to combine the text and variable
print(my_name + " lives in "+ address )
#If you try to combine a string and a number, Python will give you an error:
"""my_name="sudha"
address= 114
print(my_name + " lives in "+ address )"""
#Global variables
#Variables that are created outside of a function
#Global variables can be used by everyone, both inside of functions and outside.
x= "python"
y= " is awesome"
z= (x+y)
print(z)
#Global variables created outside a fnction
x= "awesome"
def myfunc():
print("python is" + x)
#creating a variable inside the function with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
| true
|
a070d7391d0b798ed5d4b143c113b58d2134b6c4
|
Allegheny-Computer-Science-102-F2018/classDocs
|
/labs/04_lab/sandbox/myTruthCalculatorDemo.py
| 1,176
| 4.3125
| 4
|
#!/usr/bin/env python3
# Note: In terminal, type in "chmod +x program.py" to make file executable
"""calcTruth.py A demo to show how lists can be used with functions to make boolean calculations"""
__author__ = "Oliver Bonham-Carter"
__date__ = "3 October 2018"
def myAND(in1_bool, in2_bool):
# function to determine the boolean AND calculation.
return in1_bool and in2_bool
#end of myAND()
def myOR(in1_bool, in2_bool):
# function to determine the boolean OR calculation.
return in1_bool or in2_bool
#end of myOR()
def main(): # lead function
#define the list of true and false values
A_list = [True, True, False, False]
B_list = [True, False, True, False]
print(" Welcome to the CalcTruth program!")
truth_dic = {}
for a in A_list:
for b in B_list:
# print(" Current values, a = ",a,"b = ",b)
myOR_bool = myOR(a,b)
myAND_bool = myAND(a,b)
truth_dic[str(a)+" OR "+str(b)] = myOR_bool
truth_dic[str(a)+" AND "+str(b)] = myAND_bool
for i in truth_dic:
print(" ",i, ":", truth_dic[i])
print(" All finished!")
#end of main()
main() # driver function
| true
|
cbe189e695f9b2a21c1f708c3a724fb5ab8e23af
|
mehulchopradev/curtly-python
|
/more_more_functions.py
| 853
| 4.15625
| 4
|
def abc():
a = 5 # scope will abc
b = 4
def pqr(): # scope will abc
print('PQR')
print(a) # pqr() can access the enclosing function variables
b = 10 # scope will pqr
print(b) # 10
pqr()
print(b) # 4
abc()
# pqr() # will not work
# fun -> function object
# scope -> module
def fun():
print('Fun')
# xyz -> function object
# scope -> module
def xyz(f):
# f -> fun function object
# scope f -> xyz
f()
xyz(fun) # to pass a function as an argument to another function
def mno():
print('Mno called')
y = 3 # y -> scope -> mno -> and always accessible in ytd() even when mno() has returned
z = 2
def ytd(x): # ytd -> scope -> mno
# closures
print((x ** 2) + y)
return ytd # to return a function from another function
func = mno()
func(5) # actually calling the ytd function defined inside mno
| false
|
d80dcff9be08846685f9f553817a16daf91a2d77
|
JeanneBM/PyCalculator
|
/src/classy_calc.py
| 1,271
| 4.15625
| 4
|
class PyCalculator():
def __init__(self,x,y):
self.x=x
self.y=y
def addition(self):
return self.x+self.y
def subtraction(self):
return self.x - self.y
def multiplication(self):
return self.x*self.y
def division(self):
if self.y == 0:
print("Division by zero. We cannot perform this operation.")
else:
return self.x/self.y
def main():
print("Select please one of the following operations: ")
print("1 - Addition")
print("2 - Subtraction")
print("3 - Multiplication")
print("4 - Division")
choice = input("What kind of operation should be performed? [Insert one of the options(1 2 3 4)]: ")
if choice in ('1', '2', '3', '4'):
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
calculator = PyCalculator(x,y)
if choice == '1':
print(calculator.addition())
elif choice == '2':
print(calculator.subtraction())
elif choice == '3':
print(calculator.multiplication())
else:
print(calculator.division())
if __name__ == '__main__':
main()
| true
|
3f6ff625caa4763758eab2acd908db3abb976e1c
|
taizilinger123/apple
|
/day2/高阶函数.py
| 938
| 4.125
| 4
|
var result = subtract(multiply(add(1,2),3),4); #函数式编程
def add(a,b,f): #高阶函数
return f(a)+f(b)
res = add(3,-6,abs)
print(res)
{
'backend':'www.oldboy.org',
'record':{
'server':'100.1.7.9',
'weight':20,
'maxconn':30
}
}
>>> b = '''
... {
... 'backend':'www.oldboy.org',
... 'record':{
... 'server':'100.1.7.9',
... 'weight':20,
... 'maxconn':30
... }
... }'''
>>> b
" \n{\n 'backend':'www.oldboy.org',\n 'record':{\n 'server':'100.1.
7.9',\n 'weight':20,\n 'maxconn':30\n }\n}"
>>> b[1]
'\n'
>>> eval(b)
{'record': {'server': '100.1.7.9', 'weight': 20, 'maxconn': 30}, 'backend': 'www
.oldboy.org'}
>>> b=eval(b)
>>> b
{'record': {'server': '100.1.7.9', 'weight': 20, 'maxconn': 30}, 'backend': 'www
.oldboy.org'}
>>> b['record']
{'server': '100.1.7.9', 'weight': 20, 'maxconn': 30}
| false
|
ee136845779de40a10d2deb1362f98d3700455dc
|
markorodic/python_data_structures
|
/algorithms/bubble_sort/bubble_sort.py
| 238
| 4.15625
| 4
|
def bubblesort(array):
for j in range(len(array)-1):
for i in range(len(array)-1):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
return array
# list = [7,4,2,3,1,6]
# print list
# print bubblesort(list)
| false
|
ff7dbb03f9a296067fbd7e9cfff1ff58d2a00a63
|
jocogum10/learning_python_crash_course
|
/numbers.py
| 1,487
| 4.40625
| 4
|
for value in range(1,5):
print(value)
for value in range(1,6):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
#square values
squares = [] #create empty list
for value in range(1,11): #loop from 1 to 10 using range function
square = value**2 #store in square variable the current loop value raised to the 2nd power
squares.append(square) #add to the list the value of square
print(squares)
#better square values
squaresb = []
for value in range(1,11):
squaresb.append(value**2)
print("\n\n")
print(squaresb)
#list comprehensions
print("\n\n")
print("\n\n")
squares = [value**2 for value in range(1,11)]
print(squares)
add_one = [integer+1 for integer in range(1,6)]
print(add_one)
#try it yourself
print("#########################")
#counting to twenty
for number_to_twenty in range(1,21):
print(number_to_twenty)
#one million pero up to hundred lang kay dugay
hundred = []
for count_to_hundred in range(1,101):
hundred.append(count_to_hundred)
print(hundred)
#summing a million pero hundred lang kay dugay
print(min(hundred))
print(max(hundred))
print(sum(hundred))
#odd numbers
odd_numbers = []
for odd in range(1,20,2):
odd_numbers.append(odd)
print(odd_numbers)
#cubes
cubes = []
for first_10_cubes in range(1,11):
cubes.append(first_10_cubes**3)
print(cubes)
#cube comprehension
cubes_comprehension = [first_10_cubes_b**3 for first_10_cubes_b in range(1,11)]
print(cubes_comprehension)
| true
|
f38a0a567da80562246900f4d8986106e6f99509
|
CrownCrafter/School
|
/great3.py
| 423
| 4.15625
| 4
|
#!/usr/bin/env python3
a = int(input("Enter Number "))
b = int(input("Enter Number "))
c = int(input("Enter Number "))
if(a>=b and a>=c):
print("Largest is " + str(a))
elif(b>=a and b>=c):
print("Largest is " + str(b))
else:
print("Largest is " + str(c))
if(a<=b and a<=c):
print("Smallest is " + str(a))
elif(b<=a and b<=c):
print("Smallest is " + str(b))
else:
print("Smallest is " + str(c))
| false
|
17d50543233400d554d9c838e64ec0c6f5506ce6
|
ArashDai/SchoolProjects
|
/Python/Transpose_Matrix.py
| 1,452
| 4.3125
| 4
|
# Write a function called diagonal that accepts one argument, a 2D matrix, and returns the diagonal of
# the matrix.
def diagonal(m):
# this function takes a matrix m ad returns an array containing the diagonal values
final = []
start = 0
for row in m:
final.append(row[start])
start += 1
return final
# Problem 2
# Write a function called symmetric that will accept one argument, a matrix m, and returns true if the
# matrix is symmetric or false otherwise.
def symmetric(m):
# this function takes a matrix m and returns true if the matrix is symetric or false if it is not
solution = True
for row in range(0, len(m)):
for item in range(0, len(m[row])):
if row == item:
continue # nothing to check against
elif m[row][item] == m[item][row]:
continue # yes it is symmetric
else:
solution = False
break
return solution
# Problem 3
# Write a function called transpose that will return a new matrix with the transpose matrix. The original
# matrix must not be modified. See the usage for examples of how transpose works.
def transpose(A):
# this function takes a matrix A and returns a new transposed matrix
At = []
for row in range(0, len(A)):
if row == 0:
for item in range(0,len(A[row])):
At.append([A[row][item]])
else:
for item in range(0,len(A[row])):
At[item].append(A[row][item])
return At
| true
|
15380c51a8f569f66e9ecf0f34000dfe32db85c0
|
DoolPool/Python
|
/Calculadora Basica/Calculadora-Vs1.py
| 1,147
| 4.1875
| 4
|
print("=== CALCULADORA BASICA ===")
print("Elige una opción : ")
print("1.-Suma")
print("2.-Resta")
print("3.-Multiplicación")
print("4.-División")
x= input("Escribe tu elección : ")
y= float(x)
if(y==1):
a=input("Introduce el primer numero \n")
b=input("Introduce el segundo numero \n")
a2=float(a)
b2=float(b)
resultado= a2+b2
print("El resultado de la suma es : ",resultado)
elif(y==2):
a=input("Introduce el primer numero \n")
b=input("Introduce el segundo numero \n")
a2=float(a)
b2=float(b)
resultado= a2-b2
print("El resultado de la resta es : ",resultado)
elif(y==3):
a=input("Introduce el primer numero \n")
b=input("Introduce el segundo numero \n")
a2=float(a)
b2=float(b)
resultado= a2*b2
print("El resultado de la multiplicación es : ",resultado)
elif(y==4):
a=input("Introduce el primer numero \n")
b=input("Introduce el segundo numero \n")
a2=float(a)
b2=float(b)
resultado= a2/b2
print("El resultado de la división es : ",resultado)
else:
print("NUMERO INVALIDO")
#The End
#DoolPool
| false
|
3f2328a01dd09470f4421e4958f607c3b97a5e1f
|
Remyaaadwik171017/mypythonprograms
|
/flow controls/flowcontrol.py
| 244
| 4.15625
| 4
|
#flow controls
#decision making(if, if.... else, if... elif... if)
#if
#syntax
#if(condition):
# statement
#else:
#statement
age= int(input("Enter your age:"))
if age>=18:
print("you can vote")
else:
print("you can't vote")
| true
|
8fd6028336cac45579980611e661c84e892bbf12
|
danksalot/AdventOfCode
|
/2016/Day03/Part2.py
| 601
| 4.125
| 4
|
def IsValidTriangle(sides):
sides.sort()
return sides[0] + sides[1] > sides [2]
count = 0
with open("Input") as inputFile:
lines = inputFile.readlines()
for step in range(0, len(lines), 3):
group = lines[step:step+3]
group[0] = map(int, group[0].split())
group[1] = map(int, group[1].split())
group[2] = map(int, group[2].split())
if IsValidTriangle([group[0][0], group[1][0], group[2][0]]):
count += 1
if IsValidTriangle([group[0][1], group[1][1], group[2][1]]):
count += 1
if IsValidTriangle([group[0][2], group[1][2], group[2][2]]):
count += 1
print "Valid triangles:", count
| true
|
005807a3b2a9d1c4d9d1c7c556ac27b7c526c39f
|
sumnous/Leetcode_python
|
/reverseLinkedList2.py
| 1,585
| 4.25
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2014-03-02
@author: Ting Wang
'''
#Reverse a linked list from position m to n. Do it in-place and in one-pass.
#For example:
#Given 1->2->3->4->5->NULL, m = 2 and n = 4,
#return 1->4->3->2->5->NULL.
#Note:
#Given m, n satisfy the following condition:
#1 ≤ m ≤ n ≤ length of list.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @param m, an integer
# @param n, an integer
# @return a ListNode
def reverseBetween(self, head, m, n):
dummy = ListNode(-1)
dummy.next = head
prev = dummy
for i in range(1,n+1):
if i == m:
prev_m = prev
if i > m and i <= n:
prev.next = head.next
head.next = prev_m.next
prev_m.next = head
head = prev
prev = head
head = head.next
return dummy.next
def generateLinkedList(array):
if len(array) == 0:
return None
head = ListNode(array[0])
curr = head
for i in range(1, len(array)):
node = ListNode(array[i])
curr.next = node
curr = node
return head
def printLinkedList(curr):
result = []
while curr != None:
result.append(curr.val)
curr = curr.next
print(result)
if __name__ == '__main__':
s = Solution()
linked = s.reverseBetween(generateLinkedList([3,5]),1,2)
printLinkedList(linked)
| false
|
f78c5a609bc06e6f4e623960f93838db21432089
|
valerienierenberg/holbertonschool-higher_level_programming
|
/0x05-python-exceptions/0-safe_print_list.py
| 744
| 4.125
| 4
|
#!/usr/bin/python3
def safe_print_list(my_list=[], x=0):
a = 0
for y in range(x):
try:
print("{}".format(my_list[y]), end="")
a += 1
except IndexError:
break
print("")
return(a)
# --gives correct output--
# def safe_print_list(my_list=[], x=0):
# try:
# for x in my_list[:x]:
# print("{}".format(my_list[x - 1]), end="")
# print()
# except IndexError:
# print()
# finally:
# return x
#
# Function that prints x elements of a list
# a = counter variable to keep count correct, will be returned
# for loop iterates through list to index x
# print value of each element
# add to count only if index doesn't exceed length of list
| true
|
bc9d2fe1398ef572e5f23841976978c19a6e21a6
|
YusefQuinlan/PythonTutorial
|
/Intermediate/2.5 pandas/2.5.5 pandas_Column_Edit_Make_DataFrame.py
| 2,440
| 4.5
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 19 17:11:39 2021
@author: Yusef Quinlan
"""
import pandas as pd
"""
Making a dictionary to be used to make a pandas DataFrame with.
The keys are the columns, and the values for the keys (which must be lists)
are what are used to make the DataFrame.
"""
dictionary1 = {
'Column1':['val','val','val'],
'Column2':['Jack','Dentist','lllll'],
'AColumnName':[1,2,3]
}
# The dataframe is used with pd.DataFrame(dictionary1).
df = pd.DataFrame(dictionary1)
df
"""
Here a list of tuples is created and a DataFrame will be created from these
tuples. Each tuple represents a value of the rows and there are no column
names, so column names must be specified later.
"""
Tuples1 = [('val','val2','hello'),
(4,5,3),
(99,88,77)]
"""
Here the pd.DataFrame() function is used with the tuples list as an
argument, and also with the column names as an argument and a DataFrame is
created.
"""
df = pd.DataFrame(Tuples1, columns=['Col1','Tr','MOP'])
df
"""
Here the columns attribute of our DataFrame is accessed, so that we can see
all the different columns in our DataFrame. The columns are then edited by
directly editing the .columns attribute with a list of new column names for
the existing columns. This will permanently change the column names.
"""
df.columns
df.columns = ['Col1','Mr','Mop']
df
"""
A list comprehension is used here in order to change the columns attribute
of our DataFrame, it changes our column names to uppercase versions of
themselves.
"""
df.columns = [colname.upper() for colname in df.columns]
df
# Same as the above but lower case instead.
df.columns = [colname.lower() for colname in df.columns]
df
"""
Below, the df.rename() function is used with the columns argument,
this returns a DataFrame that is a modified version of the original
DataFrame. The modifications being that the new column names specified in
the argument will be the names of the returned columns names. Note that
not all column names must be changed and that the column names that are to
be changed must be put as keys in a dictionary and the value to be changed
to should be their values.
"""
df.rename(columns={'col1':'T-rex','mop':'POM'})
df
# Same as above, but with the inplace=True argument, the DataFrame is changed.
df.rename(columns={'col1':'T-rex','mop':'POM'}, inplace=True)
df
| true
|
881419c45d178dec904578bbe59fac4ce828b4b7
|
YusefQuinlan/PythonTutorial
|
/Basics/1.16.3_Basic_NestedLoops_Practice.py
| 2,147
| 4.40625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 15:10:45 2019
@author: Yusef Quinlan
"""
# A nested loop is a loop within a loop
# there may be more than one loop within a loop, and there may be loops within loops
# within loops etc etc
# Any type of loop can be put into any other type of loop
#as in the example below, several loops can be put into one loop without being put into another
# i.e. in the below example the two loops with range(0,3) are both with the loop with range(0,5)
# and so are nested in that loop, but they are both independant of eachother and are not nested within
# eachother.
for i in range(0,5):
print(i+1)
for i2 in range(0,3):
print(i + 1 + (i2 + 1))
for i3 in range(0,3):
print(i + 1 + (i3 + 1))
#The below shows that you can use any type of loop within another type of loop
whilenum = 1
for i in range(0,10):
while whilenum < ((i+1) * 3):
print("Whilenum is equal to: " + str(whilenum))
whilenum = whilenum + 1
#The below demonstrates how quickly nested loops can multiply/add to the amount
# of overall lines of code actually run by your program, for those who want to do more homework
# there is something called 'Big O notation' that goes into this concept in more detail than I.
#for those of you who are curious to see the multiplicative effects of nested loops
# you may want to mess about with the value of 'Amount_Times' and experiment to see what happens
# you could change the value to a rediculous number such as 1000 or 10,000 , be warned though
# your computer may not be able to handle it and I bear no responsibility for any damages you might
# incur by experimenting with the variable value.
num1 = 1
num2 = 1
Amount_Times = 10
for i in range(0,Amount_Times):
print("iteration number: " + str(i+1) + " of the first loop")
for i in range(0,Amount_Times):
print("execution number: " + str(num1) + " of the code in the second loop")
num1 = num1 + 1
for i in range(0,Amount_Times):
print("execution number: " + str(num2) + " of the code in the third loop")
num2 = num2 + 1
| true
|
05111398ed789569ad5d10cfbf537cb53a069ed5
|
YusefQuinlan/PythonTutorial
|
/Intermediate/2.1 Some Useful-Inbuilt/2.1.8_Intermediate_Generators.py
| 1,879
| 4.21875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 15:38:07 2020
@author: Yusef Quinlan
"""
# What is a generator?
# A generator is an iterable object, that can be iterated over
# but it is not an object that contains all the iterable instances of whatever
# it iterates, at once.
# return will return the first valid value and exit the function
# so the following function wont return the whole range.
def iterablereturn():
for i in range(9):
return i
# Returns 0, the first value in range(9) -- 0,1,2,3,4,5,6,7,8
iterablereturn()
"""
A generator essentially makes an iteration formula and produces a generator object
based on that formula, however the generator does not contain every iteration
rather it has to be iterated over and each item generated must be used at
each iteration in order to have value, as a generator can only be iterated
over once
"""
# generators use the keyword yield and must be iterated over to be useful.
def yielder():
for i in range(9):
yield i
# using the following function will just output a generator object not the
# iterable items that the object can produce, as it does not contain them, rather
# it generates them one by one.
yielder()
# The following is the correct use of a generator
for i in yielder():
print(i)
aList1 = [x for x in range(9)]
aList2 = [x for x in range(9)]
# The following functions have the same outputs, but differ in their
# manner of execution, their use of RAM and their efficiency.
def five_list(alist):
for i in range(len(alist)):
alist[i] = alist[i] * 5
return alist
def five_list_yield(alist):
for i in range(len(alist)):
yield i * 5
# Checking original list value
for i in aList1:
print(i)
# Proof of outputs
for i in five_list(aList1):
print(i)
for i in five_list_yield(aList2):
print(i)
| true
|
b51c8430b39bdf7dce428ccaaed9ddf5ef1c9505
|
mahfoos/Learning-Python
|
/Variable/variableName.py
| 1,180
| 4.28125
| 4
|
# Variable Names
# A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
# Rules for Python variables:
# A variable name must start with a letter or the underscore character
# A variable name cannot start with a number
# A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
# Variable names are case-sensitive (age, Age and AGE are three different variables)
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
# 2myvar = "John"
# my-var = "John"
# my var = "John"
# This example will produce an error in the result
# Multi Words Variable Names
# Variable names with more than one word can be difficult to read.
# There are several techniques you can use to make them more readable:
# Camel Case
# Each word, except the first, starts with a capital letter:
myVariableName = "John"
# Pascal Case
# Each word starts with a capital letter:
MyVariableName = "John"
# Snake Case
# Each word is separated by an underscore character:
my_variable_name = "John"
| true
|
ae3689da43f974bd1948f7336e10162aea14cae6
|
CharlesBasham132/com404
|
/second-attempt-at-tasks/1-basics/2-input/2-ascii-robot/bot.py
| 523
| 4.125
| 4
|
#ask the user what text character they would wish to be the robots eyes
print("enter character symbol for eyes")
eyes = input()
print("#########")
print("# #")
print("# ",eyes,eyes, " #")
print("# ----- #")
print("#########")
#bellow is another way of formatting a face with the use of + instead of ,
#plusses + do not add spaces automatically and so are manually addes within the print statement speach marks " "
print("##########")
print("# " + eyes + " " + eyes + " #")
print("# ---- #")
print("##########")
| true
|
e2e0488734dab283f61b4114adf692f8d041209e
|
abhisheklomsh/Sabudh
|
/prime_checker.py
| 700
| 4.25
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 9 10:51:47 2019
@author: abhisheklomsh
Here we ask user to enter a number and we return whether the number is prime or not
"""
def prime_check(input_num):
flag=1
if input_num ==1: print(str(input_num)+" is not a prime number")
else:
for i in range(2,input_num+1):
if (input_num==i and flag ==1):
print(str(input_num)+" is a prime number!")
pass
elif(input_num%i==0 and flag==1):
print("This is not a prime number")
flag=0
prime_check(int(input('Enter number to be cheked if it\'s prime or not')))
| true
|
17c67730fe1f49ff945cdd21cf9b814073341e32
|
ThienBNguyen/simple-python-game
|
/main.py
| 1,447
| 4.21875
| 4
|
import random
def string_combine(aug):
intro_text = 'subscribe to '
return intro_text + aug
# def random_number_game():
# random_number = random.randint(1, 100)
# user_number = int(input('please guess a number that match with the computer'))
# while user_number == random_number:
# if random_number == user_number:
# print('your are correct')
# elif random_number < user_number:
# print('your number is greater than computer number')
# elif random_number > user_number:
# print('your number is less than computer number')
# return random_number
def user_guess(x):
random_number = random.randint(1,x)
guess = 0
while guess != random_number:
guess = int(input(f'guess a number between 1 and {x}: '))
if guess < random_number:
print('sorry, guess again.too low.')
elif guess > random_number:
print('sorry, guess again. too hight.')
print(f'correct. {random_number}')
def computer_guess(x):
low = 1
high = x
feedback = ''
while feedback != 'c':
guess = random.randint(low, high)
feedback = input(f'is {guess} too high(H) , too low(L) or correct(C)').lower()
if feedback == 'h':
high = guess - 1
elif feedback == 'l':
low = guess + 1
print(f'yay the computer guessed your, {guess}, correctly!!')
computer_guess(10)
| true
|
c8492b2fc31a4301356bdfd95ead7a6a97fcc010
|
am93596/IntroToPython
|
/functions/calculator.py
| 1,180
| 4.21875
| 4
|
def add(num1, num2):
print("calculating addition:")
return num1 + num2
def subtract(num1, num2):
print("calculating subtraction:")
return num1 - num2
def multiply(num1, num2):
print("calculating multiplication:")
return num1 * num2
def divide(num1, num2):
print("calculating division:")
if num2 == 0:
return "Invalid - cannot divide by 0"
else:
return num1 / num2
# print("Please input the numbers to be used:")
# number1 = input("Number 1: ")
# number2 = input("Number 2: ")
# if not (num1.isdigit() and num2.isdigit()):
# return "Please enter your numbers in digits"
# num1 = int(num1)
# num2 = int(num2)
#
# add_two_nums(number1, number2)
# subtract_two_nums(number1, number2)
# multiply_two_nums(number1, number2)
# divide_two_nums(number1, number2)
def calculator(instruction, int1, int2):
if instruction == "add":
return add(int1, int2)
elif instruction == "subtract":
return subtract(int1, int2)
elif instruction == "multiply":
return multiply(int1, int2)
elif instruction == "divide":
return divide(int1, int2)
else:
return "invalid instruction"
| true
|
a60f3c97b90c57d099e0aa1ade1650163cf8dd8d
|
adam-m-mcelhinney/MCS507HW
|
/MCS 507 Homework 2/09_L7_E2_path_length.py
| 1,656
| 4.46875
| 4
|
"""
MCS H2, L7 E2
Compute the length of a path in the plane given by a list of
coordinates (as tuples), see Exercise 3.4.
Exercise 3.4. Compute the length of a path.
Some object is moving along a path in the plane. At n points of
time we have recorded the corresponding (x, y) positions of the object:
(x0, y0), (x1, y2), . . ., (xn−1, yn−1). The total length L of the path from
(x0, y0) to (xn−1, yn−1) is the sum of all the individual line segments
((xi−1, yi−1) to (xi, yi), i = 1, . . . , n − 1):
L =
nX−1
i=1
p
(xi − xi−1)2 + (yi − yi−1)2 . (3.9)
Make a function pathlength(x, y) for computing L according to
the formula. The arguments x and y hold all the x0, . . . , xn−1 and
y0, . . . , yn−1 coordinates, respectively. Test the function on a triangular
triangular
path with the four points (1, 1), (2, 1), (1, 2), and (1, 1). Name of
program file: pathlength.py.
"""
def path_length(c):
"""Compute the length of a path in the plane given by a list of
coordinates (as tuples)
"""
from math import sqrt
# Break problem into the sum of the x coordinates
# and the sum of the y coordinates
# Extract list of all the x and y coordinates
x_coord=[c[i][0] for i in range(0,len(c))]
y_coord=[c[i][1] for i in range(0,len(c))]
# Compute x length and y length
x=0;y=0
for i in range(1,len(c)):
x=x+(x_coord[i]-x_coord[i-1])**2
y=y+(y_coord[i]-y_coord[i-1])**2
total_len=sqrt(x+y)
return total_len
#c=[(1,1),(2,1),(1,2),(1,1)]
#c=[(4,1),(20,1),(1,23),(1,11)]
#c=[(1,4),(4,6)]
print path_length(c)
| true
|
bf8675caa23965c36945c51056f3f34ec76ce1bc
|
anthonyharrison/Coderdojo
|
/Python/Virtual Dojo 3/bullsandcows.py
| 2,390
| 4.15625
| 4
|
# A version of the classic Bulls and Cows game
#
import random
# Key constants
MAX_GUESS = 10
SIZE = 4
MIN_NUM = 0
MAX_NUM = 5
def generate_code():
secret = []
for i in range(SIZE):
# Generate a random digit
code = random.randint(MIN_NUM,MAX_NUM)
secret.append(str(code))
return secret
def check_guess (code, guess):
result = ""
bull = 0
cow = 0
win = False
# Validate length of guess
if len(guess) > SIZE:
# Too many digits
result = "Pig"
else:
for i in range (len(guess)):
if guess[i] == code [i]:
# A valid digit in correct position
bull = bull + 1
result = result + "Bull "
elif guess[i] in code:
# A valid digit, but not in correct position
cow = cow + 1
result = result + "Cow "
# Now check result
if bull == SIZE:
# All digits found
result = "Farmer"
win = True
elif bull == 0 and cow == 0:
# No digits found
result = "Chicken"
print ("[RESULT]",result)
return win
def introduce_game():
print ("Welcome to Bulls and Cows")
print ("Try and guess my secret", SIZE,"digit code containing the digits",MIN_NUM,"to",MAX_NUM)
print ("I know it is hard, but I will try and give you some help.")
print ("If I say:")
print ("BULL You have a valid digit in the correct position")
print ("COW You have a valid digit but in the wrong position")
print ("CHICKEN You have no valid digits")
print ("FARMER You have all valid digits in the correct position")
print ("")
print ("Good luck!")
# Game
game_end = False
while not game_end:
introduce_game()
code = generate_code()
count = 0
win = False
while count < MAX_GUESS and not win:
count = count + 1
print ("Guess #",count)
guess = input("Enter your guess ")
win = check_guess(code,guess)
# Game over...
if win:
print ("Well done")
else:
print ("Never mind, try again")
print ("My secret code was",code)
# Play again?
again = input("Do you want to play again (Y/N)? ")
if again.upper() == "N":
game_end = True
print ("Thanks for playing. Have a nice day")
| true
|
044c1fcd7f2bec2a0b74d90e2dcf4583a2ed876c
|
mayaugusto7/learn-python
|
/basic/functions_anonymous.py
| 391
| 4.21875
| 4
|
# funcoes anonimas no python não tem o def
# Para criar funções anonimas devemos usar a expressão lambda
sum = lambda arg1, arg2: arg1 + arg2
print("Value of total: ", sum(10, 20))
print("Value of total: ", sum(20, 20))
def sum(arg1, arg2):
total = arg1 + arg2
print ("Inside the function : ", total)
return total;
total = sum(10, 20)
print("Outside the function : ", total)
| false
|
6bc2dbc19391e9ef4e37a9ce96a4f5a7cdb93654
|
skfreego/Python-Data-Types
|
/list.py
| 1,755
| 4.53125
| 5
|
"""
Task:-Consider a list (list = []). You can perform the following commands:
. insert i e: Insert integer e at position i
. print: Print the list.
. remove e: Delete the first occurrence of integer e
. append e: Insert integer e at the end of the list.
. sort: Sort the list.
. pop: Pop the last element from the list.
. reverse: Reverse the list.
Initialize your list and read in the value of n followed by n lines of commands where each command will be of the
7 types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format:- The first line contains an integer,n , denoting the number of commands.
Each line i of the n subsequent lines contains one of the commands described above.
Output Format:- For each command of type print, print the list on a new line.
"""
"""
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
"""
if __name__ == '__main__':
N = int(input())
command = []
for i in range(N):
command.append(input().split())
result = []
for i in range(N):
if command[i][0] == 'insert':
result.insert(int(command[i][1]), int(command[i][2]))
elif command[i][0] == 'print':
print(result)
elif command[i][0] == 'remove':
result.remove(int(command[i][1]))
elif command[i][0] == 'append':
result.append(int(command[i][1]))
elif command[i][0] == 'pop':
result.pop()
elif command[i][0] == 'sort':
result.sort()
elif command[i][0] == 'reverse':
result.reverse()
| true
|
80612a7405e7f0609f457a2263715a5077eaa327
|
buy/leetcode
|
/python/94.binary_tree_inorder_traversal.py
| 1,313
| 4.21875
| 4
|
# Given a binary tree, return the inorder traversal of its nodes' values.
# For example:
# Given binary tree {1,#,2,3},
# 1
# \
# 2
# /
# 3
# return [1,3,2].
# Note: Recursive solution is trivial, could you do it iteratively?
# confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
# OJ's Binary Tree Serialization:
# The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
# Here's an example:
# 1
# / \
# 2 3
# /
# 4
# \
# 5
# The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def inorderTraversal(self, root):
result, stack = [], [(root, False)]
while stack:
cur, visited = stack.pop()
if cur:
if visited:
result.append(cur.val)
else:
stack.append((cur.right, False))
stack.append((cur, True))
stack.append((cur.left, False))
return result
| true
|
e8689f10872987e7c74263e68b95788dce732f56
|
buy/leetcode
|
/python/145.binary_tree_postorder_traversal.py
| 983
| 4.125
| 4
|
# Given a binary tree, return the postorder traversal of its nodes' values.
# For example:
# Given binary tree {1,#,2,3},
# 1
# \
# 2
# /
# 3
# return [3,2,1].
# Note: Recursive solution is trivial, could you do it iteratively?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def postorderTraversal(self, root):
if not root:
return []
result, queue = [], [(root, False)]
while queue:
curNode, visited = queue.pop()
if curNode:
if visited:
result.append(curNode.val)
else:
queue.append((curNode, True))
queue.append((curNode.right, False))
queue.append((curNode.left, False))
return result
| true
|
06dc7790c9206822c66d72f4185f16c0127e377d
|
AlexandrKnyaz/Python_lessons_basic
|
/lesson02/home_work/hw02_easy.py
| 1,716
| 4.125
| 4
|
# Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
fruits_list = ['Абрикос', 'Персик', "Слива", "Груша", "Арбуз", "Дыня"]
for fruit_index, fruit_name in enumerate(fruits_list, start=1):
print(fruit_index, "{:>7}".format(fruit_name))
# Задача-2:
# Даны два произвольные списка.
# Удалите из первого списка элементы, присутствующие во втором списке.
list1 = ['dog', 7, 'apple', 444, 3.45]
list2 = ['dog', 444, 3.45]
print(list1)
print(list2)
for val in list2:
if val in list1:
list1.remove(val)
print(list1)
print(list2)
# Задача-3:
# Дан произвольный список из целых чисел.
# Получите НОВЫЙ список из элементов исходного, выполнив следующие условия:
# если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два.
first_list = [2, 12, 3, 15, 44, 73]
new_list = []
val = len(first_list)
for i in range(val):
if first_list[i] % 2 == 0:
new_list.append(first_list[i] / 4)
else:
new_list.append(first_list[i] * 2)
print(new_list)
| false
|
8f5d33183271397e07fd1b45717bc15dc24ba80f
|
nayanika2304/DataStructuresPractice
|
/Practise_graphs_trees/random_node.py
| 2,420
| 4.21875
| 4
|
'''
You are implementing a binary tree class from scratch which, in addition to
insert, find, and delete, has a method getRandomNode() which returns a random node
from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm
for getRandomNode, and explain how you would implement the rest of the methods.
Random number calls can be expensive. If we'd like, we can reduce the number of random number calls
substantially.
Another way to think about what we're doing is that the initial random number call indicates which node (i) to return,
and then we're locating the ith node in an in-order traversal.
Subtracting LEFT_SIZE + 1 from i reflects that, when we go right,
we skip over LEFT_SIZE + 1 nodes in the in-order traversal.
https://www.youtube.com/watch?v=nj5jFhglw8U
depth of tree is log n so time complexity is O(logn)
'''
from random import randint
class Node:
def __init__(self, data):
self.data = data
self.children = 0
self.left = None
self.right = None
# This is used to fill children counts.
def getElements(root):
if root == None:
return 0
return (getElements(root.left) +
getElements(root.right) + 1)
# Inserts Children count for each node
def insertChildrenCount(root):
if root == None:
return
root.children = getElements(root) - 1
insertChildrenCount(root.left)
insertChildrenCount(root.right)
# Returns number of children for root
def children(root):
if root == None:
return 0
return root.children + 1
# Helper Function to return a random node
def randomNodeUtil(root, count):
if root == None:
return 0
if count == children(root.left):
return root.data
if count < children(root.left):
return randomNodeUtil(root.left, count)
return randomNodeUtil(root.right,
count - children(root.left) - 1)
# Returns Random node
def randomNode(root):
count = randint(0, root.children)
return randomNodeUtil(root, count)
# Driver Code
if __name__ == "__main__":
# Creating Above Tree
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.right = Node(40)
root.left.right = Node(50)
root.right.left = Node(60)
root.right.right = Node(70)
insertChildrenCount(root)
print("A Random Node From Tree :",
randomNode(root))
| true
|
4774e23e3a65b54ff0e96736d0d491a965c6a1b4
|
nayanika2304/DataStructuresPractice
|
/Practise_linked_list/remove_a_node_only pointer_ref.py
| 1,885
| 4.375
| 4
|
'''
Implement an algorithm to delete a node in the middle (i.e., any node but
the first and last node, not necessarily the exact middle) of a singly linked list, given only access to
that node.
iterating through it is a problem as head is unkniwn
faster approach is to copy the data of next node in current node
and delete next node
# to delete middle node
LinkedListNode next =n.next;
n.data = next.data;
n.next = next.next;
return true;
'''
# a class to define a node with
# data and next pointer
class Node():
# constructor to initialize a new node
def __init__(self, val=None):
self.data = val
self.next = None
# push a node to the front of the list
def push(head, val):
# allocate new node
newnode = Node(val)
# link the first node of the old list to the new node
newnode.next = head.next
# make the new node as head of the linked list
head.next = newnode
# function to print the list
def print_list(head):
temp = head.next
while (temp != None):
print(temp.data, end=' ')
temp = temp.next
print()
# function to delete the node
# the main logic is in this
def delete_node(node):
prev = Node()
if (node == None):
return
else:
while (node.next != None):
node.data = node.next.data
prev = node
node = node.next
prev.next = None
if __name__ == '__main__':
# allocate an empty header node
# this is a node that simply points to the
# first node in the list
head = Node()
# construct the below linked list
# 1->12->1->4->1
push(head, 1)
push(head, 4)
push(head, 1)
push(head, 12)
push(head, 1)
print('list before deleting:')
print_list(head)
# deleting the first node in the list
delete_node(head.next)
print('list after deleting: ')
print_list(head)
| true
|
c173928913363f978662919341813f5ae867bf95
|
fanyichen/assignment6
|
/lt911/assignment6.py
| 1,816
| 4.28125
| 4
|
# This program is to manage the user-input intervals. First have a list of intervals entered,
# then by taking new input interval to merge intervals.
# input of valid intervals must start with [,(, and end with ),] in order for correct output
import re
import sys
from interval import interval
from interval_functions import *
def prompt():
'''Start the program by prompting user input'''
start = True
print "Please enter a list of intervals, start with '[]()', and put ', ' in between intervals."
user_list = raw_input("List of intervals? \n")
if user_list in ["quit","Quit","q","Q"]:
start = False
return
interval_list = user_list.split(", ")
for element in interval_list:
if not validInput(element):
start = False
else:
start = True
while start:
user_interval = raw_input("Interval? (please enter only in the right format):\n")
if user_interval in ["quit","Quit","q","Q"]:
start = False
return
elif not validInput(user_interval):
print "Invalid interval"
pass
else:
insert_interval = interval(user_interval)
if len(insert_interval.list) == 0:
print "Invalid interval"
else:
interval_list = insert(interval_list, user_interval)
print interval_list
def validInput(input_interval):
'''check is input interval is valid'''
delimiters = ",", "[","]", "(",")"
regexPattern = '|'.join(map(re.escape, delimiters))
int_element = re.split(regexPattern, input_interval)
if input_interval[0] in ["[","]","(",")"] or input_interval[-1] in ["[","]","(",")"]:
try:
lower = int(int_element[1])
upper = int(int_element[-2])
return True
except:
return False
else:
return False
class InvalidIntervalError(Exception):
def __str__(self):
return 'Invalid interval'
if __name__ == "__main__":
try:
prompt()
except:
pass
| true
|
29816333038bf4bf14460d8436d1b75243849537
|
kevgleeson78/Emerging-Technonlgies
|
/2dPlot.py
| 867
| 4.15625
| 4
|
import matplotlib.pyplot as plt
# numpy is used fo scientific functionality
import numpy as np
# matplotlib plots points in a line by default
# the first list is the y axis add another list for the x axis
# To remove a connecting line from the plot the third arg is
# shorthand for create blue dots
# numpy range
x = np.arange(0.0, 10.0, 0.01)
y = 3.0 * x + 1.0
# generate noise for the plot
noise = np.random.normal(0.0, 1.0, len(x))
# plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'b.')
plt.plot(x, y + noise, 'r.', label="Actual")
plt.plot(x, y, 'b', label="Model")
# plt.ylabel("Some Value Label")
# to add a title
plt.title("SImple Title")
# To add a label to the x axis
plt.xlabel("Weight")
# To add a label to the y axis
plt.ylabel("Mass")
# To add a legend to the plot label has to be added to the plots above as an extra parameter.
plt.legend()
plt.show()
| true
|
f17209f360bf135a9d3a6da02159071828ca0087
|
hamishscott1/Number_Guessing
|
/HScott_DIT_v2.py
| 1,120
| 4.3125
| 4
|
# Title: Guess My Number v2
# Date: 01/04/2021
# Author: Hamish Scott
# Version: 2
""" The purpose of this code is to get the user to guess a preset number.
The code will tell them if the number is too high or too low and will
tell them if it is correct."""
# Setting up variables
import random
int_guess = 0
int_number = random.randint(1, 64)
int_num_of_guesses = 1
# Asks users name.
str_name = input('What is your name? ').title()
# User feedback loop, tells user if guess is too high or too low.
while int_guess != int_number:
int_guess = int(input("Hi {}. Please try and guess \
the number between 1 and 64 inclusive: ".format(str_name)))
if int_guess > int_number:
print("{}, your guess is too high. Try again. ".format(str_name))
int_num_of_guesses += 1
elif int_guess < int_number:
print("{}, your guess is too low. Try again. ".format(str_name))
int_num_of_guesses += 1
# Prints how mant guesses user took.
print("Congratulations {}, you have guessed my number, \
you took {} guesses. Goodbye.".format(str_name, int_num_of_guesses))
| true
|
fd4b084531d68577c6ba3c066575fba247aa6daa
|
summen201424/pyexercise-1
|
/venv/totalexercise/algorithm.py
| 618
| 4.28125
| 4
|
#sqrt_newton
# import math
# from math import sqrt
# num=float(input("请输入数字:"))
# def sqrt_newton(num):
# x=sqrt(num)
# y=num/2.0
# count=1
# while abs(y-x)>0.0000001:
# print(count,y)
# count+=1
# y=((y*1.0)+(1.0*num)/y)/2.000
# return y
# print(sqrt_newton(num))
# print(sqrt(num))
from math import sqrt
num=float(input("请输入数字:"))
def sqrt_num(num):
y=num/2
count=1
x=sqrt(num)
while abs(x-y)>\
0.000001:
print(count,y)
y=(y+num/y)/2
count+=1
return y
print(sqrt_num(num))
print(sqrt(num))
| false
|
e995bf856a613b5f1978bee619ad0aaab4be80ed
|
saibeach/asymptotic-notation-
|
/v1.py
| 1,529
| 4.21875
| 4
|
from linkedlist import LinkedList
def find_max(linked_list):
current = linked_list.get_head_node()
maximum = current.get_value()
while current.get_next_node():
current = current.get_next_node()
val = current.get_value()
if val > maximum:
maximum = val
return maximum
#Fill in Function
def sort_linked_list(linked_list):
print("\n---------------------------")
print("The original linked list is:\n{0}".format(linked_list.stringify_list()))
new_linked_list = LinkedList()
while linked_list.get_head_node():
current_max = find_max(linked_list)
linked_list.remove_node(current_max)
new_linked_list.insert_beginning(current_max)
return new_linked_list
#Test Cases
ll = LinkedList("Z")
ll.insert_beginning("C")
ll.insert_beginning("Q")
ll.insert_beginning("A")
print("The sorted linked list is:\n{0}".format(sort_linked_list(ll).stringify_list()))
ll_2 = LinkedList(1)
ll_2.insert_beginning(4)
ll_2.insert_beginning(18)
ll_2.insert_beginning(2)
ll_2.insert_beginning(3)
ll_2.insert_beginning(7)
print("The sorted linked list is:\n{0}".format(sort_linked_list(ll_2).stringify_list()))
ll_3 = LinkedList(-11)
ll_3.insert_beginning(44)
ll_3.insert_beginning(118)
ll_3.insert_beginning(1000)
ll_3.insert_beginning(23)
ll_3.insert_beginning(-92)
print("The sorted linked list is:\n{0}".format(sort_linked_list(ll_3).stringify_list()))
#Runtime
runtime = "N^2"
print("The runtime of sort_linked_list is O({0})\n\n".format(runtime))
| true
|
02a7ab067157be02467fd544a87a26fb7d792d7b
|
mayurimhetre/Python-Basics
|
/calculator.py
| 735
| 4.25
| 4
|
###### Python calculator Program ##############################
### taking two numbers as input from user and option
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choose = int(input("Enter your option : 1,2,3,4 : "))
a = int(input("Enter First Number :"))
b = int(input("Enter Second Number :"))
def add(a,b):
print("addition of two numbers is ", a+b)
def subtract(a,b):
print("Subtraction of two numbers is ", a-b)
def multiply(a,b):
print("Multiplication is",a*b)
def division(a,b):
print("Division is :", a/b)
if choose == 1:
add(a,b)
elif choose == 2:
subtract(a,b)
elif choose ==3:
multiply(a,b)
else:
division(a,b)
| true
|
523f44dfb04138b92c56d603b07f8e4c3a9f75b3
|
tanmaya191/Mini_Project_OOP_Python_99005739
|
/6_OOP_Python_Solutions/set 1/arithmetic_operations.py
| 561
| 4.1875
| 4
|
"""arithmetic operation"""
print("Enter operator")
print("1 for addition")
print("2 for subtraction")
print("3 for multiplication")
print("4 for division")
op = int(input())
print("Enter 1st number")
num1 = int(input())
print("Enter 2nd number")
num2 = int(input())
if op == 1:
print(num1, "+", num2, "=", num1 + num2)
elif op == 2:
print(num1, "-", num2, "=", num1 - num2)
elif op == 3:
print(num1, "*", num2, "=", num1 * num2)
elif op == 4:
print(num1, "/", num2, "=", num1 / num2)
else:
print("Enter valid inputs")
| false
|
ee6a4589b17ed32172b53dca9e9a054b71ebea60
|
tanmaya191/Mini_Project_OOP_Python_99005739
|
/6_OOP_Python_Solutions/set 1/vowel_check.py
| 488
| 4.21875
| 4
|
"""vowel or consonant"""
print("Enter a character")
char = input()
if len(char) == 1:
if char == "a" or char == "e" or char == "i" or char == "o" or char == "u":
print(char, "is a vowel")
elif char == "A" or char == "E" or char == "I" or char == "O" or char == "U":
print(char, "is a vowel")
elif "A" < char <= "z":
print(char, "is a consonant")
else:
print("Enter a valid input")
else:
print("Enter a valid input")
| false
|
2f563e53a9d4c0bbf719259df06fb0003ac205bc
|
sweetise/CondaProject
|
/weight_conversion.py
| 433
| 4.28125
| 4
|
weight = float(input(("Enter your Weight: ")))
unit = input(("Is this in 'lb' or 'kg'?"))
convert_kg_to_lb = round(weight * 2.2)
convert_lb_to_kg = round(weight / 2.2)
if unit == "kg":
print(f" Your weight in lbs is: {convert_kg_to_lb}")
elif unit == "lb":
print(f" Your weight in kg is: {convert_lb_to_kg}")
else:
print("Invalid input. Please enter weight in 'kg', 'kgs', 'kilograms' or 'lb', 'lbs', 'pounds'")
| true
|
978e2b9b55998133ab90b0868126f32367f29d60
|
samcheck/Tutorials
|
/ATBSWP/Chap3/collatz.py
| 348
| 4.125
| 4
|
def collatz(number):
if number == 1:
return
elif number % 2 == 0:
print(number // 2)
collatz(number // 2)
else:
print(3 * number + 1)
collatz(3 * number + 1)
print('Input an interger: ')
number = input()
try:
number = int(number)
collatz(number)
except ValueError:
print('Error: please enter an interger')
number = input()
| false
|
f6b8082233895e0a78275d13d2ec29c14bc088cf
|
Ethan2957/p03.1
|
/multiple_count.py
| 822
| 4.1875
| 4
|
"""
Problem:
The function mult_count takes an integer n.
It should count the number of multiples of 5, 7 and 11 between 1 and n (including n).
Numbers such as 35 (a multiple of 5 and 7) should only be counted once.
e.g.
mult_count(20) = 7 (5, 10, 15, 20; 7, 14; 11)
Tests:
>>> mult_count(20)
7
>>> mult_count(50)
20
>>> mult_count(250)
93
"""
# Use this to test your solution. Don't edit it!
import doctest
def run_tests():
doctest.testmod(verbose=True)
# Edit this code
def mult_count(n):
count = 0
for i in range(1, n+1, 5):
count = count + 1
for l in range(1, n+1, 7):
if l % 5 != 0:
count = count + 1
for j in range(1, n+1, 11):
if j % 7 != 0 and j % 5 != 0:
count = count + 1
print(count)
| true
|
f7f7a5f023f89594db74f69a1a2c3f5f34dfc881
|
gpallavi9790/PythonPrograms
|
/StringPrograms/5.SymmetricalString.py
| 241
| 4.25
| 4
|
#Prgram to check for symmetrical string
mystr=input("Enter a string:")
n=len(mystr)
mid=n//2
firsthalf=mystr[0:mid]
secondhalf=mystr[mid:n]
if(firsthalf==secondhalf):
print("Symmetrical String")
else:
print("Not a Symmetrical String")
| true
|
57740b0f61740553b9963170e2dddc57c7b9858b
|
gpallavi9790/PythonPrograms
|
/StringPrograms/7.RemoveithCharacterFromString.py
| 400
| 4.25
| 4
|
#Prgram to remove i'th character from a string
mystr="Pallavi Gupta"
# Removing char at pos 3
# using replace, removes all occurences
newstr = mystr.replace('l', '')
print ("The string after removal of i'th character (all occurences): " + newstr)
# Removing 1st occurrence of
# if we wish to remove it.
newstr = mystr.replace('l', '', 1)
print ("The string after removal of i'th character : " + newstr)
| true
|
a8bdf0c4d3abbd4582c4149436a2abed7d48369b
|
Jessicammelo/cursoPython
|
/default.py
| 951
| 4.15625
| 4
|
"""
Modulos colection - Default Dict
https://docs.python.org/3/library/collections.html#collections.defaultdict
# Recap Dicionarios
dicionario = {'curso': 'Programação em Python: essencial'
print(dicionario)
print(dicionario['curso'])
print(dicionario['outro']) #???KeyError
Default Dict -> Ao criar um dicionario utilizando-o, nós informamos um valor default,
podendo utilizar um lambda para isso. Esse valor será utilizado sempre que não houver
um valor definido. Caso tentemos acessar uma chave que não existe, essa chave será criada
e o valor default será atribuido.
OBs: Lambdas são funcoes sem nome, que podem ou não receber parametros de entrada e retornar
valores.
"""
#Fazendo import
from collections import defaultdict
dicionario = defaultdict(lambda: 0)
dicionario['curso'] = 'programação em python: essencial'
print(dicionario)
print(dicionario['outro']) # KeyError no dicionario comum, mais aqui não
print(dicionario)
| false
|
ac582b05af10382ea245887fae34f853cc48b3fe
|
Jessicammelo/cursoPython
|
/tipo_String.py
| 684
| 4.375
| 4
|
"""
Tipo String
Sempre que estiver entre aspas simples ou duplas ('4.2','2','jessica')
"""
"""
nome = 'Jessica'
print(nome)
print(type(nome))
nome = "Gina's bar"
print(nome)
print(type(nome))
nome = 'jessica'
print(nome.upper())#tudo maicusculo
print(nome.lower())# tudo minusculo
print(nome.split())#transfoma em uma lista de string
#['0','1','2']
#['j','e','s']
nome = 'jes'
print(nome[0:2]) #slice de string
print(nome[1:2])
print(nome.split()[0])s
"""
nome = 'jessica melo'
#[0,1]
#['jessica','melo']
print(nome.split()[1])
print(nome[::-1]) #Comece do primeiro elemento, va até o ultimo elemento e inverta # inversão da string pythônico
print(nome.replace('j', 'g'))
print(type(nome))
| false
|
84dbde9af21ff55e79e696e14d53754929cdf550
|
Jessicammelo/cursoPython
|
/lambdas.py
| 1,826
| 4.90625
| 5
|
"""
Utilizando Lambdas
Conhecidas por expressões Lambdas, ou simplesmente Lambdas, são funções sem nome,
ou seja, funções anonimas.
#Função em Paython:
def funcao(x):
return 3 * x + 1
print(funcao(4))
print(funcao(7))
#Expressão Lambda
lambda x: #Função em Paython:
def funcao(x):
return 3 * x + 1
print(funcao(4))
print(funcao(7))
#Expressão Lambda
lambda x: 3 * x + 1
#como utilizar a expressão lambda?
calc = lambda x: 3 * x + 1
print(calc(4))
print(calc(7))
#como utilizar a expressão lambda?
calc = lambda x: 3 * x + 1
print(calc(4))
print(calc(7))
#Podemos ter expressões lambdas com multiplos entradas
nome_completo = lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title()
# strip = remeve espaços
#title = aplica letra maiuscula
print(nome_completo('angelina ', 'Jolie'))
print(nome_completo(' Felicity ', 'jones '))
#Em funções Python podemos ter nenhuma ou varias entradas.Em lambdas tbm:
amar = lambda: ' Como não amar python'
uma = lambda x: 3 * x + 1
duas = lambda x, y: (x * y) ** 0.5
tres = lambda x, y, z: 3 / (1/ x + 1 / y + 1/z)
#n lambda x1, x1 ....xn: <expressão
print(amar())
print(uma(6))
print(duas(5, 7))
print(tres(3, 6, 9))
#Obs|:
# Se passamos mais argumentos do que parametros esperados teremos TypeError
#Outro exemplo
autores = ['Isacc Assimov', 'Ray Bradbury']
print(autores)
autores.sort(Key=lambda sobrenome: sobrenome.split(' ')[-1].lower())
print(autores)
"""
# Função quadratica
#f(x) = a * x ** 2 + b * x + c
#Definindo a função
def geradora_funcao_quadratica(a, b, c):
"""Retorna a função f(x) = a * x ** 2 + b * x + c"""
return lambda x: a * x ** 2 + b * x + c
teste = geradora_funcao_quadratica(2, 3, -5)
print(teste(0))
print(teste(1))
print(teste(2))
print(geradora_funcao_quadratica(3, 0, 1)(2))
| false
|
f47f69de9366760f05fda6dd697ce2301ad38e01
|
johnhjernestam/John_Hjernestam_TE19C
|
/introkod_syntax/Annat/exclusiveclub.py
| 453
| 4.125
| 4
|
age = int(input('How old are you? '))
if age < 18:
print('You are too young.')
if age > 30:
print('You are too old.')
if age >= 18:
answer = input('Have you had anything to drink today or taken something? Yes or no: ')
if answer == "no":
print('You got to be turned up')
else:
print('Please answer yes or no.')
if answer == "yes":
input('So you telling me you turned up or what?')
| true
|
396d8403fb82b6c4b6f698b5998d0b57f89071fb
|
felhix/cours-python
|
/semaine-1/07-boolean.py
| 2,963
| 4.1875
| 4
|
#! python3
# 07-boolean.py - quelques booléens, opérateurs, et comparateurs
# Voici quelques comparateurs
print(1 == 1) #=> True, car 1 est égal à 1
print(1 == "1") #=> False, car 1 est un integer, et "1" est un string
print("Hello" == "Bonjour") #=> False, car ces 2 strings sont différents
print("1" == "1") #=> True, car ces 2 strings sont identiques
print(1 != 2) #=> True, car 1 est différent de 2
print(1 != "1") #=> True, car 1 est un integer, et "1" est un string. Ils sont donc différents
print("Hello" != "Hello") #=> False, car ces deux strings sont identiques
print(0 < 1) #=> True, car 0 est strictement inférieur à 1
print(-10 < -9) #=> True, car -10 est sctrictement inférieur à -9
print(0 < 0) #=> False, car 0 n'est pas strictement inférieur à 0
print(1 > 0) #=> True, car 1 est strictement supérieur à 0
print(0 <= 1) #=> True, car 0 est inférieur ou égal à 1
print(1 <= 1) #=> True, car 1 est inférieur ou égal à 1
print(1 <= 0) #=> False, car 1 n'est pas inférieur ou égal à 0
print(1 >= 0) #=> True, car 1 est supérieur ou égal à 0
print(1 >= 1) #=> True, car 1 est supérieur ou égal à 1
print(0 >= 1) #=> False, car 0 n'est pas supérieur ou égal à 1
#ça marche aussi avec des variables
age = 26
age_dans_1_an = 27
print(age < age_dans_1_an) #=> True
print(age == age_dans_1_an) #=> False
print(age == age_dans_1_an - 1) #=> True, car 26 est égal à 27 - 1. Les opérations marchent sur les booléens
#et aussi avec les strings
first_name = "Félix"
last_name = "Gaudé"
print("Félix Gaudé" == first_name + " " + last_name) #=> True, car les deux renvoient à un string équivalent à "Félix Gaudé"
print(first_name == "félix") #=> False, car la casse compte
print(first_name == "Felix") #=> False, idem pour les accents
#on peut déclarer une variable en tant que booléen (c'est un data type après tout)
variable_1 = True
variable_2 = 1 > 0 #=> True
variable_3 = age < age_dans_1_an #=> True
#on peut faire des opérations de booléns avec les opérateurs
print(1 == 1 and 2 == 2) #=> True, car 1 et égal à 1 ET 2 est égal à 2
print(2 > 3 and 2 == 2) #=> False, car l'une des deux comparaisons est False
print(2 > 3 and 2 == 1) #=> False, car les deux comparaisons sont False
print(1 == 1 or 2 == 2) #=> True, car au moins une des deux comparaisons est True
print(2 > 3 or 2 == 2) #=> True, car au moins une des deux comparaisons est True
print(2 > 3 or 2 == 1) #=> False, car il n'y a pas au moins une des deux comparaisons qui est True
#plus tricky, on peut conjuguer les opérateurs
print(1 == 2 or 2 == 3 or 1 == 1) #=> True, car au moins un des éléments de comparaisons est True
print( (1 == 1 and 2 == 3) or 1 == 2) #=> False. On va résoudre en premier l'opération entre parenthèses (False, car l'un des deux est False) avant de la comparer avec le "or" restant. Les deux sont False, cela renvoie False.
| false
|
230e1d2846f4b608c3f541d5d089655ca97f9efe
|
kmrsimkhada/Python_Basics
|
/loop/while_with_endingCriteria.py
| 968
| 4.25
| 4
|
#While-structure with ending criteria
'''
The second exercise tries to elaborates on the first task.
The idea is to create an iteration where the user is able to define when the loop ends by testing the input which the user gave.
Create a program which, for every loop, prompts the user for input, and then prints it on the screen.
If the user inputs the string "quit", the program prints "Bye bye!" and shuts down.
When the program is working correctly it should print out something like this:
>>>
Write something: What?
What?
Write something: Fight the power.
Fight the power.
Write something: quit
Bye bye!
>>>
It is probably a good idea to implement the entire program within one "while True" code block, and define the ending criteria so that the program uses a selection criteria and break command.
'''
while True:
write = str(input("Write something: "))
if write == "quit":
print("Bye bye!")
break;
else:
print(write)
continue;
| true
|
e1dca0956dc0547a3090e508787df989034b0eaf
|
kmrsimkhada/Python_Basics
|
/type_conversion.py
| 702
| 4.5
| 4
|
#Type Conversions
'''
In this exercise the aim is to try out different datatypes.
Start by defining two variables, and assign the first variable the float value 10.6411.
The second variable gets a string "Stringline!" as a value.
Convert the first variable to an integer, and multiply the variable with the string by 2.
After this, finalize the program to print out the results in the following way:
Integer conversion cannot do roundings: 10
Multiplying strings also causes trouble: Stringline!Stringline!
'''
number1 = 10.6411
st1 = "Stringline!"
st2 = st1*2
num1 = int(number1)
print("Integer conversion cannot do roundings: "+str(num1))
print("Multiplying strings also causes trouble: "+st2)
| true
|
26a5ce912495c032939b4b912868374a6d8f83c7
|
kmrsimkhada/Python_Basics
|
/lists/using_the_list.py
| 2,397
| 4.84375
| 5
|
#Using the list
'''
n the second exercise the idea is to create a small grocery shopping list with the list datastructure.
In short, create a program that allows the user to (1) add products to the list, (2) remove items and (3) print the list and quit.
If the user adds something to the list, the program asks "What will be added?: " and saves it as the last item in the list.
If the user decides to remove something, the program informs the user about how many items there are on the list (There are [number] items in the list.")
and prompts the user for the removed item ("Which item is deleted?: "). If the user selects 0, the first item is removed. When the user quits,
the final list is printed for the user "The following items remain in the list:" followed by the remaining items one per line.
If the user selects anything outside the options, including when deleting items, the program responds "Incorrect selection.".
When the program works correctly it prints out the following:
>>>
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Apples
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Beer
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 1
What will be added?: Carrots
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 2
There are 3 items in the list.
Which item is deleted?: 3
Incorrect selection.
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 2
There are 3 items in the list.
Which item is deleted?: 2
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 2
There are 2 items in the list.
Which item is deleted?: 0
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 4
Incorrect selection.
Would you like to
(1)Add or
(2)Remove items or
(3)Quit?: 3
The following items remain in the list:
Beer
>>>
'''
mylist = []
while True :
user_input = int(input("""Would you like to
(1)Add or
(2)Remove items or
(3)Quit?:"""))
if user_input == 1:
add_input = input("What will be added?: ")
mylist.append(add_input)
elif user_input == 2:
print("There are ",len(mylist), " items in the list.")
try:
mylist.pop(int(input("Which item is deleted?: ")))
except Exception:
print("Incorrect selection.")
elif user_input == 3:
print("The following items remain in the list: ")
for i in mylist:
print(i)
break
else:
print("Incorrect selection. ")
| true
|
8a49bad35b7b1877abf081adc13ed6b9b63d0de8
|
suhanapradhan/IW-Python
|
/functions/6.py
| 319
| 4.28125
| 4
|
string = input("enter anything consisting of uppercase and lowercase")
def count_case(string):
x = 0
y = 0
for i in string:
if i.isupper():
x += 1
else:
y += 1
print('Upper case count: %s' % str(x))
print('Lower case count: %s' % str(y))
count_case(string)
| true
|
35a98e4bf5b1abcd7d6dd9c6ff64d53d07f8788e
|
BinyaminCohen/MoreCodeQuestions
|
/ex2.py
| 2,795
| 4.1875
| 4
|
def sum_list(items):
"""returns the sum of items in a list. Assumes the list contains numeric values.
An empty list returns 0"""
sum = 0
if not items: # this is one way to check if list is empty we have more like if items is None or if items is []
return 0
else:
for x in items:
sum += x
return sum
def remove_duplicates(items):
"""remove all the duplicates from a list, and return the list in the original order
a copy of the list (with the modifications) is returned
:type items: object
listNoDup = []
if len(items) < 2:
return items
else:
for x in items:
for y in listNoDup:
if x is not y:
listNoDup.append(x)
return listNoDup"""
exsist = set()
listNoDup = []
for x in items:
if x not in exsist:
exsist.add(x)
listNoDup.append(x)
return listNoDup
def remove_longer_than(words, n):
"""remove all the words from the words list whose length is greater than N"""
return [x for x in words if len(x) <= n]
def have_one_in_common(list1, list2):
"""return True if the lists have at least one element in common
for x in list1:
for y in list2:
if x is y:
return True
return False"""
return len(set(list1).intersection(set(list2))) > 0
def word_count(words):
"""takes a list of words and returns a dictionary that maps to each word how many times it appears in the list"""
d = {}
for x in words:
if x in d:
d[x] += 1
else:
d[x] = 1
return d
# start tests
def test_sum_list():
assert (sum_list([]) == 0)
assert (sum_list([1]) == 1)
assert (sum_list([1, 2, 3]) == 6)
def test_remove_duplicates():
assert (remove_duplicates([1, 3, 2, 1, 3, 1, 2]) == [1, 3, 2])
assert (remove_duplicates(["a", "b", "a"]) == ["a", "b"])
assert (remove_duplicates([]) == [])
def test_remove_longer_than():
l = ["", "a", "aa", "aaa", "aaaa"]
assert (remove_longer_than(l, -1) == [])
assert (remove_longer_than(l, 0) == [""])
assert (remove_longer_than(l, 2) == ["", "a", "aa"])
def test_have_one_in_common():
assert (have_one_in_common([1, 2, 3], [4, 5, 6]) == False)
assert (have_one_in_common([], []) == False)
assert (have_one_in_common([1, 2, 3], [1]) == True)
assert (have_one_in_common(["a", "b", "c"], ["a", "x", "c"]) == True)
def test_word_count():
assert (word_count([]) == {})
assert (word_count(["a", "b", "a"]) == {"a": 2, "b": 1})
if __name__ == "__main__":
test_sum_list()
test_remove_duplicates()
test_remove_longer_than()
test_have_one_in_common()
test_word_count()
print("Done")
| true
|
a9cb243ebc4a52d46e6d214a17e011c293cde3ff
|
s16323/MyPythonTutorial1
|
/EnumerateFormatBreak.py
| 1,464
| 4.34375
| 4
|
fruits = ["apple", "orange", "pear", "banana", "apple"]
for i, fruit in enumerate(fruits):
print(i, fruit)
print("--------------Enumerate---------------")
# Enumerate - adds counter to an iterable and returns it
# reach 3 fruit and omit the rest using 'enumerate' (iterator)
for i, fruit in enumerate(fruits): # 'For' loop receives 2 args now. For every index 'i' and a given 'fruit' element reported by 'enumerate()' function do:
if i == 3:
break
print(i, fruit)
print("---------------Format-----------------")
# Format
# C = "someOtherString".capitalize() # Check out other functions
# print(C.lower()) # itd...
print("someString {} {}".format("123", "ABC")) # format replaces whatever is in {}
x ="Hello {}"
y = x.format("World", "xxx", 777)
print(y)
print("--------------------------------------")
for i, fruit in enumerate(fruits):
print("I'm checking: {}".format(i))
if i == 3:
print("{} is the third fruit!!! No more checking.".format(fruit))
break
print(i,"is", fruit)
print("------Skipping some iterations--------")
# Skipping some iterations
fruits = ["apple", "orange", "pear", "banana", "apple"]
print("Start")
for fruit in fruits:
if fruit == "orange":
print("wracam do poczatku petli")
continue # after 'continue' the next if is skipped ! Code goes back to 'for' loop
if fruit == "banana": break
print(fruit)
print("End")
| true
|
d51b4e8230def2eac49d1505656a5f943d162efc
|
ricardofelixmont/Udacity-Fundamentos-IA-ML
|
/zip-function/zip.py
| 556
| 4.46875
| 4
|
# ZIP FUNCTION
# zip é um iterador built-in Python. Passamos iteraveis e ele os une em uma estrutura só
nomes = ['Lucas', 'Ewerton', 'Rafael']
idades = [25, 30, 24]
nomes_idades = zip(nomes, idades)
print(nomes_idades) # Mostra o objeto do tipo zip()
#como zip() é um iterador, precisamos iterar sobre ele para mostrar seus elementos
for nome in nomes: # Dessa forma ele nao fica guardado na memoria como uma variavel separada
print(nome)
# Tambem podemos atribuir esse zip a uma lista:
nomes_idades = list(zip(nomes, idades))
print(nomes_idades)
| false
|
4cb726601b5dda4443b8fe3b388cbd6f598013a8
|
varnagysz/Automate-the-Boring-Stuff-with-Python
|
/Chapter_05-Dictionaries_and_Structuring_Data/list_to_dictionary_function_for_fantasy_game_inventory.py
| 1,640
| 4.21875
| 4
|
'''Imagine that a vanquished dragon’s loot is represented as a list of strings
like this:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function named addToInventory(inventory, addedItems), where the
inventory parameter is a dictionary representing the player’s inventory
(like in the previous project) and the addedItems parameter is a list like
dragonLoot. The addToInventory() function should return a dictionary that
represents the updated inventory. Note that the addedItems list can contain
multiples of the same item. Your code could look something like this:
def addToInventory(inventory, addedItems):
# your code goes here
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
The previous program (with your displayInventory() function from the previous
project) would output the following:
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48'''
def display_inventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print('Total number of items: ' + str(item_total))
def add_to_inventory(inventory, added_items):
for i in added_items:
inventory.setdefault(i, 0)
inventory[i] += 1
return inventory
inv = {'gold coin': 42, 'rope': 1}
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = add_to_inventory(inv, dragon_loot)
display_inventory(inv)
| true
|
71db3ebdbd3bbcac09c385947f6b327f9d7c3d73
|
harshit-sh/python_games
|
/matq.py
| 743
| 4.25
| 4
|
# matq.py
# Multiplication Quiz program
# Created by : Harshit Sharma
from random import randint
print "Welcome to Maths Multiplication Quiz!"
print "--------------------------------"
ques = int(raw_input("How many questions do you wish to answer? "))
print "--------------------------------"
limit = int(raw_input("Till what positive range can you answer? (Enter a Positive number) "))
c1 = 0
for i in range(ques):
n1 = randint(1,limit)
n2 = randint(1,limit)
right_ans = n1*n2
ans = int(raw_input("What's %d times %d? : "%(n1,n2)))
if right_ans == ans:
print "Well done!"
c1 = c1 + 1
else:
print "Sorry, answer is ",right_ans
print
print "---------Summary------------"
print
print "You scored", c1, "points out of a possible", ques
| true
|
05c461070ef9f5a7cee7b53541d22be836b65450
|
crisjsg/Programacion-Estructurada
|
/Ejercicio10 version 2.py
| 1,169
| 4.125
| 4
|
#10. Modifica el programa anterior para que en vez de mostrar un mensaje genérico en el caso
#de que alguno o los dos números sean negativos, escriba una salida diferenciada para cada
#una de las situaciones que se puedan producir, utilizando los siguientes mensajes:
#a. No se calcula la suma porque el primer número es negativo.
#b. No se calcula la suma porque el segundo número es negativo.
#c. No se calcula la suma porque los dos números son negativos.
def cogerNumeros(numero):
numero = int(input("Introduce la cantidad de números que vayas a coger: "))
listaNumeros = []
listaNumeros.append(numero)
primerNumero = int(input("Introduce un número entero: "))
segundoNumero = int(input("Introduce un segundo numero entero: "))
if primerNumero < 0 and segundoNumero < 0:
print ("No se calcula la suma porque los dos números son negativos.")
if primerNumero < 0:
print ("No se calcula la suma porque el primer número es negativo.")
if segundoNumero < 0:
print ("No se calcula la suma porque el segundo número es negativo.")
if primerNumero >= 0 and segundoNumero >= 0:
print ("La suma de los números es:", primerNumero + segundoNumero)
| false
|
dc7761a6601b2d29f7ef50966814a7a4201f579f
|
josecaromuentes2019/CursoPython
|
/manehoExcepciones2.py
| 429
| 4.1875
| 4
|
import math
print('estre programa calcula la Raiz cuadrada de un numero')
def raiz(num):
if num<0:
raise ValueError('No es posible calcular Raices negativas')
else:
return math.sqrt(num)
while True:
try:
numero = int(input('Digita un numero: '))
print(raiz(numero))
except ValueError as miError:
print(miError)
else:
print('Progrma finalizado')
break
| false
|
cdaa647a527a20cf851f65ce4df554a3185b920a
|
annkon22/ex_book-chapter3
|
/linked_list_queue(ex20).py
| 1,835
| 4.1875
| 4
|
# Implement a stack using a linked list
class Node:
def __init__(self, init_data):
self.data = init_data
self.next = None
def get_data(self):
return self.data
def get_next(self):
return self.next
def set_data(self, new_data):
self.data = new_data
def set_next(self, new_next):
self.next = new_next
class UnorderedList:
def __init__(self):
self.head = None
self.num = 0
def is_empty(self):
return self.head == None
def add(self, item):
temp = Node(item)
temp.set_next(self.head)
self.head = temp
self.num += 1
def size(self):
return self.num
def list_print(self):
print_value = self.head
while print_value:
print(print_value.data, end = ' ')
print_value = print_value.next
def queue(self, newdata):
new_node = Node(newdata)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def stack(self, newdata):
new_node = Node(newdata)
if self.head is None:
self.head = new_node
return
def __str__(self):
current = self.head
string = ''
while current is not None:
string += str(current) + ", "
current = current.get_next()
return string
my_lst = UnorderedList()
my_lst.stack(1)
my_lst.stack(10)
my_lst.stack(100)
my_lst.stack(1000)
my_lst.stack(10000)
my_lst.stack(100000)
my_lst.stack(1000000)
my_lst.stack(10000000)
my_lst.list_print()
print()
| true
|
32662139be2cd03f427faaa5a1255fb8fd24b1cd
|
annkon22/ex_book-chapter3
|
/queue_reverse(ex5).py
| 457
| 4.25
| 4
|
#Implement the Queue ADT, using a list such that the rear of the queue
#is at he end of the list
class Queue():
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
return self.items.pop(0)
my_q = Queue()
my_q.enqueue('hi')
my_q.enqueue('ok')
my_q.enqueue('bye')
print(my_q.dequeue())
print(my_q.dequeue())
print(my_q.dequeue())
| true
|
061acf150e2bea1ec8acbc7ce8d2a4550c408e0e
|
ChristianDzul/ChristianDzul
|
/Exam_Evaluation/Question_06.py
| 506
| 4.15625
| 4
|
##Start##
print ("Welcome to the area calculator")
##Variables##
length = 0
width = 0
area_square = 0
area_rectangle = 0
##Getting the values##
length = int( input("Insert a value for the lenght \n"))
width = int( input("Insert a value for the width \n"))
##Process##
if (length == width):
area_square = length * width
print ("The figure is a square with an area of:", area_square)
else:
area_rectangle = length * width
print ("The figure is a rectangle with an area of:", area_rectangle)
| true
|
5aa2d245d628c79a70360f2c114a4cef537a65e4
|
dharm0us/prob_pro
|
/iterate_like_a_native.py
| 577
| 4.40625
| 4
|
#iterate like a native
# https://www.youtube.com/watch?v=EnSu9hHGq5o
myList = ["The", "earth", "revolves", "around", "sun"]
for v in myList: #Look ma, no integers
print(v)
#iterator is reponsible for producing the stream
#for string it's chars
for c in 'Hello':
print(c)
d = {'a' : 1, 'b' : 2}
for k in d: #by default iterating a dict produces keys
print(k)
#other dict iterations
for v in d.values():
print(v)
for k in d.keys():
print(k)
with open("README.md") as f: #file iteration
for line in f:
print(line)
| false
|
59890f09a10730dc76f570bd8d186c3cb9364f93
|
konovalovatanya26/prog_Konovalova
|
/turtle_new/упр 10.py
| 337
| 4.25
| 4
|
import turtle
t = turtle.Turtle()
t.shape('turtle')
Number = 100
Step = 5
def circle(Number, Step):
for step in range(Number):
t.forward(Step)
t.left(360/Number)
for step in range(Number):
t.forward(Step)
t.right(360/Number)
for _ in range(3):
circle(Number, Step)
t.left(60)
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.