blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c228669d8e3dd2bb25cb18e3221c2f78985e735a | wingedrasengan927/Python-tutorials | /Object Oriented Programming/6. Propert decorators, getters and setters.py | 2,581 | 4.4375 | 4 | # -------PROPERTY DECORATOR---------
# This allows to get our class attribute's getter, setter and deleter functionality
# The property decorator allows us to define a method but we can access the method like an attribute
# Let's go and pull this email attribute out into a method similar to our fullname method
# Setter's
# Let's add a property decorator to fullname method similar to the email method
# but, in this case, Let's say we want to change the fullname
# and doing so should also change the firstname, lastname and email
# so, if do emp_1.fullname = Corey Schafer
# Then the changes should be:
# firstname = Corey
# lastname = Schafer
# email = Corey.Schafer@company.com
# Deleter's
# Let's say I want to delete an employee
class employee:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
@property
def email(self):
return "{}.{}@company.com".format(self.firstname, self.lastname)
@property
def fullname(self):
return "{} {}".format(self.firstname, self.lastname)
# Let's define a setter
# The name of the setter should be name of the property
# 'fullname' in this case
@fullname.setter
def fullname(self, name):
# Name is the value we are trying to set. e.g., 'Corey Schafer'
first, last = name.split(' ')
self.firstname = first
self.lastname = last
@fullname.deleter
def fullname(self):
print("Delete Name!")
self.firstname = None
self.lastname = None
emp_1 = employee("Neeraj", "Krishna")
print(emp_1.firstname)
print(emp_1.lastname)
print(emp_1.fullname)
print(emp_1.email)
# Now, Let's change the first name
emp_1.firstname = "Jim"
print(emp_1.firstname) # Jim
print(emp_1.lastname) # Krishna
print(emp_1.fullname) # Jim Krishna
print(emp_1.email) # Neeraj.Krishna@company.com
# As we can see
# the fullname changes and the email doesn't change
# The reason is the fullname method grabs the CURRENT firstname and lastname
# we have to fix the email
# This is where getters and setters come in
# We can do this in python using property decorator
# Now we can see, adding property decorator solves the problem
# Now, the email method can be accessed as an attribute
print(emp_1.email)
# Now, let's try out our setter
emp_1.fullname = "Corey Schafer"
print(emp_1.firstname) # Corey
print(emp_1.lastname) # Schafer
print(emp_1.email) # Corey.Schafer@company.com
# What happened is, when we set emp_1.fullname = "Corey Schafer"
# It went directly to our setter method and carried out the process
# So the deleter runs when we delete an attribute
del emp_1.fullname
| true |
00657cd91ae7377197cc2244b487d34d94f07fc5 | mdhvkothari/Data_science | /data_in_pandas.py | 1,298 | 4.4375 | 4 | import pandas as pd
from pandas import DataFrame , read_csv
name = ['madhav','rahul','rishab','bikesh','nitin','vaibhav']
age = [18,16,18,22,10,25]
place=['jewar','mathura','bihar','bihar','noida','bharatpur']
#we can zip these arrya into one
datalist = list(zip(name,age,place))
print(datalist)
#now we can convert these data into DataFrame
df = pd.DataFrame(data = datalist,columns=['Names','Ages','Place'])
print(df)
#now we can convert this data into csv file
df.to_csv('datafile.csv',index=False)
#to read the above csv file
Location = r'/home/mdhv/data-science/datafile.csv'
df = pd.read_csv(Location)
print(df)
#we can delete this file for this we have to import os
#import os
#os.remove(Location)
#for find the datatype of data
print(df.dtypes)
#for specified column
print(df.Ages.dtypes )
#for shorted data
sorted = df.sort_values(['Ages'],ascending=False)
#.head will give the upper data of the table
print(sorted.head(1))
#another method for finding the max value
print(df['Ages'].max())
#we can change the index
df = df.set_index('Names')
print(df.head(2))
print(df['Place'][:2])
print(df.describe())
#how to select the row
print(df.iloc[0:2])
#we can use boolian values
print(df[df["Ages"]>18])
#it will give the number of the people present in the data
print((df["Ages"]>18).sum())
| true |
006bc87f712ba86c08245db7fc06a85e53fec19f | david-uni/python-help | /exercises/exercise-1.py | 1,122 | 4.3125 | 4 | # 27/10/2020 exercise 1
# helper
def end_exercise():
print('\n', '-' * 100, '\n')
# example 1
def hypotenuse(a, b):
return (a**2 + b**2) ** 0.5
def triangle_area(a, b):
""" Calculates the area of a right triangle.
Input:
1) a - First adjacent
2) b - Second adjacent
Output (float): Returns the area of the triangle
"""
return (a * b) / 2
def circumference(a, b, c):
return a + b + c
print('hypotenuse - ' + str(hypotenuse(3, 4)))
print('triangleArea - ' + str(triangle_area(3, 4)))
print('circumference - ' + str(circumference(3, 4, 5)))
end_exercise()
# example 2
def upper_middle(word):
middle = len(word) // 2
word = word.lower()
return word[:middle] + str.upper(word[middle]) + word[middle + 1:]
print('result of middle upper - ' + upper_middle('wikipedia'))
end_exercise()
# example 3
def count_donuts(donuts):
if donuts > 10:
print('Number of donuts: A lot!')
elif donuts > 5:
print('Number of donuts:', str(donuts) + '...')
else:
print('Number of donuts:', str(donuts) + '.')
count_donuts(11)
end_exercise()
| true |
6ae6d85deaeda13f3ec65e0e6cfb0bbb66b6a200 | david-uni/python-help | /homeworks/ex1/ex1_version_1.py | 2,368 | 4.21875 | 4 | ''' Exercise #1 - solution. Python.'''
#########################################
# Question 1 - do not delete this comment
#########################################
S = 220.0 # Replace ??? with a positive float of your choice.
AB = 20.0 # Replace ??? with a positive float of your choice.
BC = 10.0 # Replace ??? with a positive float of your choice.
AD = 15.0 # Replace ??? with a positive float of your choice.
DC = 35.0 # Replace ??? with a positive float of your choice.
# Write the rest of the code for question 1 below here.
circumference = AB + BC + AD + DC
midsegment = (AB + DC) / 2
height = S / midsegment
print('Diameter is:', circumference)
print('Midsegment is:', midsegment)
print('Height is:', height)
#########################################
# Question 2 - do not delete this comment
#########################################
my_name = 'oxana' # Replace ??? with a string of your choice.
# Write the rest of the code for question 2 below here.
formatted_name = my_name[0].upper() + my_name[1:].lower()
print('Hello', formatted_name + '!')
#########################################
# Question 3 - do not delete this comment
#########################################
number = '49' # Replace ??? with a string of your choice.
# Write the rest of the code for question 3 below here.
if(int(number) % 7 == 0):
print('I am', number, 'and I am divisible by 7')
else:
print('I am', number, 'and I am not divisible by 7')
#########################################
# Question 4 - do not delete this comment
#########################################
text = 'tom' # Replace ??? with a string of your choice.
copies = 3 # Replace ??? with a positive int of your choice.
# Write the rest of the code for question 4 below here.
str1 = text[1::2]
str2 = text[0::2]
new_str = str1 + str2
print(copies * new_str)
#########################################
# Question 5 - do not delete this comment
#########################################
name = 'droLtromedloV' # Replace ??? with a string of your choice.
q = 4 # Replace ??? with a int of your choice.
# Write the rest of the code for question 5 below here.
if type(name) != str or type(q) != int or q < 0 or q >= len(name) or len(name) == 0:
print('Error: illegal input!')
else:
sub1 = name[:q]
sub2 = name[q:]
sub1 = sub1[::-1]
sub2 = sub2[::-1]
print(sub1, sub2)
| true |
7280bf0bf3d1f5e3ba1f4048aded05dc1e8fca15 | david-uni/python-help | /lectures/lesson-4.py | 897 | 4.59375 | 5 | # 15/11/2020 Lesson 4
# tuples
def example():
return 1, 2, 3 # will return a tuple - e.g. (1, 2, 3)
my_tuple = (1, 2) # immutable
# dictionaries
my_dict = {'key': 'val'}
my_dict['key']
# default in case none existing - None
my_dict.get('key', 'value in case key doesn\'t exist')
my_dict.keys() # returns a dynamic list of all the key
my_dict.values() # returns a dynamic list of all the value
my_dict.items() # returns a dynamic list of all the key, value pair as tuples
my_dict_keys = my_dict.keys()
print(my_dict_keys)
my_dict['new_key'] = 'new val'
# you can see that the keys are dynamic and now contains the new_key
print(my_dict_keys)
# returns a boolean (True - if it is, False - if it isn't)
'new_key' in my_dict
my_dict.pop('new_key', 'return value if the key doesn\'t exist')
copy_dict = my_dict.copy()
{}.update(my_dict) # add all the keys and values of my_dict to {}
| true |
d8fe35d411f2414b46368447967b1184ce6c606a | DikshaRai1/FST-M1 | /Python/Activities/Activity9.py | 584 | 4.1875 | 4 | #Given a two list of numbers create a new list such that new list should contain only odd numbers from the first list and even numbers from the second list.
list1=[1,2,3,4]
list2=[6,7,8,9]
list3=[]
for number in list1: #Adding odd numbers from list1 to list3
if (number%2)!=0 :
list3.append(number)
for number in list2:
if (number%2)==0 : #Adding even numbers to list3 from list2
list3.append(number)
print(list3) #Printing list3 | true |
0ced6115d6c9b4877ce35039e85bbbdd5b3fbfed | DikshaRai1/FST-M1 | /Python/Activities/Activity18.py | 515 | 4.1875 | 4 | # Import pandas
import pandas as pd
#Read from csv file and store data in dataframe
dataframe=pd.read_csv('csvFile.csv')
#Print Usernames
print(dataframe["Usernames"])
#Print 2nd row of Usernames and Passwords
print(dataframe["Usernames"][1])
print(dataframe["Passwords"][1])
#Sort Usernames
#Print Usernames after sorting
print(dataframe.sort_values("Usernames"))
#Sort Passwords in descending order
#Print passwords after sorting
print(dataframe.sort_values("Passwords", ascending=False)) | true |
4643df42437ce2a1c5b436cbf3b2b62c6f128729 | raserma/AutomateTheBoringStuff | /Chapter 7/strong_password.py | 1,282 | 4.53125 | 5 | #!/usr/bin/env python3
# strong_password.py - it makes sure a password is strong
# Note: I divided the regex into 4 expressions to give concise feedback to user
# about why password is not strong enough.
import re
def is_password_strong(password):
"""Validates a strong password"""
# define the password requisites
min_characters_regex = re.compile(r'\w{8,}')
lowercase_regex = re.compile(r'[a-z]+')
uppercase_regex = re.compile(r'[A-Z]+')
digit_regex = re.compile(r'\d+')
if min_characters_regex.search(password) is None:
print('Your password needs at least 8 characters')
return False
if lowercase_regex.search(password) is None:
print('Your password needs at least 1 lowercase')
return False
if uppercase_regex.search(password) is None:
print('Your password needs at least 1 uppercase')
return False
if digit_regex.search(password) is None:
print('Your password needs at least 1 digit')
return False
print('Password strong enough!')
return True
def main():
password = input('Introduce your secure password:')
while not is_password_strong(password):
print('Try again please.')
password = input('Introduce your secure password:')
main()
| true |
a99178d46477891a99067c48d58466378d308aa5 | androshchyk11/lab10 | /5.py | 1,692 | 4.21875 | 4 | '''Сформувати функцію, що визначатиме чи є задане натуральне число простим.
Простим називається число, що більше за 1 та не має інших дільників, окрім 1 та самого
себе).
Виконав студент групи 122-А Андрощук Артем Олександрович
'''
'''У цій задачі більш доцільно буде використати ітераційний метод через простоту алгоритму та наявності
очевидного рвшення за допомогою циклу'''
import timeit
print("1 - recursion;\n"
"2 - iteration.")
flag = int(input("What do you want to use?"))
mysetup = '''
import math
'''
if flag == 2:
mycode = '''
n = int(input("Input your number: "))
if n < 2:
print("The number shoul be more than 1!")
quit()
elif n == 2:
print("This is simple number")
quit()
i = 2
limit = int(math.sqrt(n))
while i <= limit:
if n % i == 0:
print("False")
quit()
i += 1
print("True")
'''
elif flag == 1:
mycode = '''
def Isprime(n):
i = 2
j = 0
while(True):
if(i*i <= n and j != 1):
if(n % i == 0):
j=j+1
i=i+1
elif(j==1):
return False
else:
return True
n = int(input("Input your number: "))
print(Isprime(n))
'''
print("time of a program: ", timeit.timeit(setup=mysetup,
stmt=mycode,
number=1))
| false |
37416093d9a280510823338b050ff982d6a832d2 | Voidivi/Hacker-Rank-Solutions | /Sorting Anagrams - hackerrank solution.py | 992 | 4.28125 | 4 | #!/usr/bin/env python3
# Sorting anagrams
# Author: Lyssette Williams
# Write your code here
def funWithAnagrams(text):
sorted_text = [] #list/array
for word in text: #text is array provided
sorted_text.append(sorted(word))
#makes a copy of provided array, with each word sorted alphabetically
#sorting the individual letters within the word
#reason to keep a copy, if two words are anagrams they'll match exactly when sorted
#makes checking easier in the next loop
for i in range(len(text)-1,-1,-1): #walks backward end of the array to the start
for j in range(i): #starts at 0 works it's way to i, through the whole loop
if sorted_text[i] == sorted_text[j]: #if i and j have matching sorted versions
text.pop(i) #we delete it
break #we end the inner loop
text.sort()#anagram free array in text and sorts the whole array
return text
if __name__ == '__main__': | true |
b0140ba10709fa05fbfa15270795f389557b310a | alferesx/programmingbydoing | /dumbcalculator.py | 304 | 4.28125 | 4 | number1 = float(input("What is your first number?: "))
number2 = float(input("What is your second number?: "))
number3 = float(input("What is your third number?: "))
result = (number1 + number2 + number3) / 2
print((str(number1)+ " " + str(number2)+ " " + str(number3) + " / 2") + " is: " + str(result))
| false |
c5de53365f200e653a7ee7dff5bfd7c069b3eb86 | silverfox78/HackerRank | /Python - Language Proficiency/E008 - Find a string/ejercicio.py | 520 | 4.15625 | 4 | # >>> Find a string
# >>> https://www.hackerrank.com/challenges/find-a-string/problem
def count_substring(string, sub_string):
largoString = len(string)
largoSubString = len(sub_string)
contador = 0
for i in range(largoString):
contador += 1 if string[i:i + largoSubString] == sub_string else 0
return contador
if __name__ == '__main__':
string = 'ABCDCDC' #input().strip()
sub_string = 'CDC' #input().strip()
count = count_substring(string, sub_string)
print(count) | false |
5177076e167701fe5f82f5e23ee53b7cd64e22a0 | fullonic/govspy | /snippets/switch/switch.py | 429 | 4.125 | 4 | def input_():
return int(input())
number = input_()
if number == 8:
print("Oxygen")
elif number == 1:
print("Hydrogen")
elif number == 2:
print("Helium")
elif number == 11:
print("Sodium")
else:
print("I have no idea what %d is" % number)
# Alternative solution
number = input_()
db = {1: "Hydrogen", 2: "Helium", 8: "Oxygen", 11: "Sodium"}
print(db.get(number, "I have no idea what %d is" % number))
| false |
40ceab485558ac4afccb0db09f45658f9ca0f3b8 | mysticman2476/python_scripts | /try.py | 342 | 4.3125 | 4 | # Simple program
username = raw_input ('Please enter your name: ')
age=input('Please enter your age: ')
print 'your name is {} and your age is {}'.format(username, age)
if age > 18:
print (username, 'you are officially a teen')
elif age == 15:
print (username, 'you are 15!')
else:
print (username, 'you are a kid')
print ('goodbye')
| true |
b4fdd2ffb876b5a9b1a1b351428b39968ba9dade | akumar90/HW06 | /HW06_ex09_06.py | 1,084 | 4.375 | 4 | #!/usr/bin/env python
# HW06_ex09_05.py
# (1)
# Write a function called is_abecedarian that returns True if the letters in a
# word appear in alphabetical order (double letters are ok).
# - write is_abecedarian
# (2)
# How many abecedarian words are there?
# - write function(s) to assist you
# - number of abecedarian words:
##############################################################################
# Imports
# Body
def is_abecedarian(word):
for i in range(len(word)-1):
if ord(word[i]) > ord(word[i+1]):
return False
return True
def no_of_words(filename):
with open(filename, 'r') as f:
count = 0
for lines in f:
for words in lines.split():
if(is_abecedarian(words.strip())):
count += 1
return count
##############################################################################
def main():
print ("1st problem")
print (repr(is_abecedarian("abcdegjkz")))
print
print
print ("2nd Problem")
print ("Number of words which have letters in alphabetical order are : "+repr(no_of_words("words.txt")))
if __name__ == '__main__':
main()
| true |
e3e63c06298b85d3a1ea90f9ebef25ceaaf69c98 | agatajan/Python_training | /DAY_2/ex_day3.py | 1,102 | 4.21875 | 4 |
#1 wypisz co druga literę z napisu - uzyj petli for:
# text = "Python is a fantastic snake"
# # for x in text:
# # print(text[::2])
# # break
# 1.1 wypisz co druga literę
# text = "Python is a fantastic snake"
# print(text[::2])
# 1.2 wypisz teraz co trzecią literę
# text = "Python is a fantastic snake"
# print(text[::3])
# 2 wyszukaj w dokumentacji jak rozbić powyższy tekst na listę słów a nastepnie wydrukuj ta liste (for slowo in lista)
# text = "Python is a fantastic snake"
# words = text.split()
#
# for i in words:
# print(i)
# #cwiczenie
# text = "Python is a fantastic snake"
# how_many_chars = len(text)
#
# list_of_indexes = range(0,how_many_chars,2)
#
# for idx in list_of_indexes:
# print(text[idx], end="")
# #enumerate
# months = ["Jan", "Feb", "March"]
# for index, value in enumerate(months):
# print(f"Na indeksie {index} znajduje sie {value}")
# 3 zmien program z punktu drugiego tak, aby uzytkownik sam wpisal jakis tekst, ktory program mu rozbije na liste slow
text = input("Wpisz zdanie: ")
words = text.split()
for i in words:
print(i) | false |
fdce7e49678666671b6e7879a5a4900bada3d5b4 | lr154lrose/Project-Euler | /python solutions/Problems 1-10/problem_9.py | 545 | 4.34375 | 4 | from math import sqrt, floor
def pythagorean_triplet(
number,
): # finding a pythagorean triplet where the sum of it is equal to number
for n in range(1, floor(sqrt(number))):
for m in range(
n, floor(sqrt(number))
): # for loop for m starting at n since n < m
a = m * m - n * n # using the equations for finding pythagorean triple
b = 2 * m * n
c = m * m + n * n
if a + b + c == number:
return a * b * c
print(pythagorean_triplet(1000))
| false |
ec388e037c8e04383093d9507ee13e7fd468966e | maiali13/DS-Unit-3-Sprint-2-SQL-and-Databases | /SC/northwind.py | 2,279 | 4.4375 | 4 | # Unit 3 Sprint 2 Challenge
import sqlite3
# Load DB
connect = sqlite3.connect('northwind_small.sqlite3')
cursor = connect.cursor()
# Part 2
# What are the ten most expensive items (per unit price) in the database?
query = """
SELECT ProductName
FROM Product
ORDER BY UnitPrice DESC
LIMIT 10;
"""
q = cursor.execute(query).fetchall()
print("10 most expensive products: ", q)
# What is the average age of an employee at the time of their hiring?
# (Hint: a lot of arithmetic works with dates.)
query1 = """
SELECT ROUND(AVG(HireDate - BirthDate), 1)
FROM Employee;
"""
q1 = cursor.execute(query1).fetchall()
print("Average age of employees at hire: ", q1)
# (*Stretch*) How does the average age of employee at hire vary by city?
query2 = """
SELECT City, ROUND(AVG(HireDate - BirthDate), 1)
FROM Employee
GROUP BY City;
"""
q2 = cursor.execute(query2).fetchall()
print("Average age of employees at hire by city: ", q2)
# Part 3
# What are the ten most expensive items (per unit price) in the databse
# *and* their suppliers?
query3 = """
SELECT UnitPrice, ProductName, CompanyName
FROM (SELECT Product.UnitPrice, Product.ProductName, Supplier.CompanyName
FROM Product
JOIN Supplier
WHERE Product.SupplierId = Supplier.Id
ORDER BY UnitPrice DESC
LIMIT 10);
"""
q3 = cursor.execute(query3).fetchall()
print("10 most expensive products and suppliers: ", q3)
# What is the largest category (by number of unique products in it)?
query4 = """
SELECT Category.CategoryName, COUNT(DISTINCT ProductName) AS TotalProducts
FROM Product
JOIN Category ON Product.CategoryID = Category.Id
ORDER BY TotalProducts DESC
LIMIT 1;
"""
q4 = cursor.execute(query4).fetchall()
print("Largest category by number of unique products: ", q4)
# (*Stretch*)
# Who's the employee with the most territories?
# Use `TerritoryId` (not name, region, or other fields) as the unique
# identifier for territories.
# oh well, tried
query5 = """
SELECT Employee.LastName, COUNT(DISTINCT Territory.Id)
FROM Employee, Territory, EmployeeTerritory
WHERE EmployeeTerritory.EmployeeId = Employee.Id AND EmployeeTerritory.TerritoryId = Territory.Id
GROUP BY employee.id
ORDER BY EmployeeTerritory.TerritoryId DESC
LIMIT 1;
"""
q5 = cursor.execute(query5).fetchall()
print("Employee with the most territory: ", q5)
| true |
4123bb0780a44f041013de6ed3a427f4b26fa4c3 | Enfors/ref | /python-ref/fluent-python/numpy_arrays.py | 440 | 4.1875 | 4 | #!/usr/bin/env python3
"A brief example of NumPy from chapter 2."
import numpy
from demo import headline
print(headline("General"))
a = numpy.arange(12)
print("a:", a)
print("type(a):", type(a))
print("a.shape:", a.shape)
a.shape = 3, 4
print("a.shape:", a.shape)
print("a:", a)
print("a[2]:", a[2])
print("a[2, 1]:", a[2, 1])
print("a[:, 1]:", a[:, 1])
# transpose == swapping rows with columns
print("a.transpose():", a.transpose())
| false |
dea52760f4b0fdc9ec36f24b3bbe26386ebe99ee | yeseongcho/- | /프로그래밍1/object oriented Circle example class variable.py | 1,530 | 4.25 | 4 |
class Circle :
PI = 3.14
def __init__(self, rad) :
self.rad = rad
self.area = self.comp_area()
self.cir = self.comp_cir()
def __str__(self) :
return "(%6.2f %6.2f %6.2f)" % (self.rad, self.area, self.cir)
def comp_area(self) :
return self.PI*self.rad**2
#return Circle.PI*self.rad**2
def comp_cir(self) :
return 2*self.PI*self.rad
#return 2*Circle.PI*self.rad
def display(self) :
print(self)
def main() :
try :
r = input("Enter a radius")
r = float(r)
circle = Circle(r)
circle.display()
except ValueError :
print("Please enter a number")
main()
main()
# No change main function -- 객체지향 프로그램의 가장 큰 장점이다!! by
"""
class Circle :
PI = 3.14
def __init__(self, rad) :
self.rad = rad
#self.area = self.comp_area()
#self.cir = self.comp_cir()
def __str__(self) :
return "(%6.2f %6.2f %6.2f)" % (self.rad, self.comp_area(), self.comp_cir())
def comp_area(self) :
return self.PI*self.rad**2
#return Circle.PI*self.rad**2
def comp_cir(self) :
return 2*self.PI*self.rad
#return 2*Circle.PI*self.rad
def display(self) :
print(self)
def main() :
try :
r = input("Enter a radius")
r = float(r)
circle = Circle(r)
circle.display()
except ValueError :
print("Please enter a number")
main()
main()
"""
| false |
a17e5f50b6a60ed73224a98deca6b44447f00c17 | HanqingXue/LeetCode-1 | /Stacks/simplifypath.py | 1,891 | 4.1875 | 4 | """
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
"///"
"/..."
"""
"""Create a stack, pass all the non ".." paths. Append all words, if .. you go back"""
class Solution:
# @param path, a string
# @return a string
def simplifyPath(self, path):
#print(path.split("/")) #Split somehow creates random empty strings
path = filter(None, path.split("/")) #removes empty strings in list
stack = []
for char in path:
# "." mean current dir, so DO NOTHING
if char == ".":
continue
#Pop because like "cd .."
elif char == "..":
if stack != []:
stack.pop()
#Append FOLDER NAME
else:
stack.append(char)
path_str = ""
#print(stack)
if stack == [] or ("" in stack):
return "/"
for i in range(len(stack)):
path_str += "/" + stack[i]
return path_str
print(Solution().simplifyPath("///"))
"""
def simplifyPath(self, path):
if list(path).count("/") % 2 != 0:
return path
#print(path.split("/")) #Split somehow creates random empty strings
path = filter(None, path.split("/")) #removes empty strings in list
#print(path)
stack = []
for char in path:
if char.isalpha():
stack.append(char)
path_str = ""
if stack == []:
return "/"
for i in range(len(stack)):
path_str += "/" + stack[i]
return path_str
"""
| true |
4fa7a62bcd8caca8a67137d3de89fe89dfee5812 | joaramirezra/Can-You-Solve-a-Problem | /In-house/tempConverter.py | 859 | 4.3125 | 4 | def tempConvert():
"""
tempConvert() convert temperature from one unit to another,
Celcius to Fahrenheit (°C to °F) and vice versa.
Variables: unit: str; value: int
"""
# take input from the user
unit = input("Which unit is your temperature: C or F? ")
value = eval(input("Enter the value of your temperature you want to convert: "))
# converting user input to lower case
unit = unit.lower()
# condition to check the unit we want to onvert from for the right formular
if unit == "c":
# capturing the formular and rounding it to two decimal places
Fahrenheit = round((value *(9/5)) + 32, 2)
print(f" {value}°C is {Fahrenheit}°F.")
else:
Celsius = round((value - 32) * (5/9), 2)
print(f" {value}°F is {Celsius}°C.")
tempConvert()
| true |
71dde31596d508e87cb548f4a1e9b1913c55de11 | Wilsonilo/MIT-6.00.1x | /week2/finger_exervice_is_in.py | 1,627 | 4.40625 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
We can use the idea of bisection search to determine if a character is in a string, so long as the string is sorted in alphabetical order.
First, test the middle character of a string against the character you're looking for (the "test character"). If they are the same, we are done - we've found the character we're looking for!
If they're not the same, check if the test character is "smaller" than the middle character. If so, we need only consider the lower half of the string; otherwise, we only consider the upper half of the string. (Note that you can compare characters using Python's < function.)
Implement the function isIn(char, aStr) which implements the above idea recursively to test if char is in aStr. char will be a single character and aStr will be a string that is in alphabetical order. The function should return a boolean value.
As you design the function, think very carefully about what the base cases should be.
'''
# Your code here
#set vars
middle = int(len(aStr) / 2)
size = int(len(aStr))
#basecase
if size > 0:
if char == aStr[middle]:
return True
elif size > 1:
# left / small
if char < aStr[middle]:
return isIn(char, aStr[0:middle])
# right major
else:
return isIn(char, str(aStr[middle:size]))
else:
return False
else:
return False
print(isIn("w", "ddhipruxxxz")) | true |
7850c22a796eb29004b67391c4db6b385f87707a | ansumanmishra/python-tuts | /5-lists.py | 831 | 4.375 | 4 | import sys
import os
# Creating list
first_list = ['list1', 'list2', 'list3']
print(first_list)
# Appending to list
first_list.append('list4')
print(first_list)
# Adding a new item to a defined position
first_list.insert(0, 'list0')
print(first_list)
# Length of a list
print(len(first_list))
# Create second list
second_list = ['list5', 'list6', 'list7']
# Combining lists
print(first_list + second_list)
# Getting elements from lists
print(first_list[1]) # Prints list2
# Remove from list by name
first_list.remove('list3')
print(first_list)
# Reverse list
animals = ["dog", "cow", "horse", "cat"]
animals.reverse()
print(animals)
# Sort list
animals.sort()
print(animals)
# Delete list
del animals
#print(animals)
# Max & Min of a list
list_numbers = [1, 5, 6, 7, 2]
print(max(list_numbers))
print(min(list_numbers)) | true |
ef354d70b1be8bad936da7b72353963d5efbb609 | iamspriyadarshi/rosalind-solutions | /Complementing_a_Strand_of_DNA.py | 488 | 4.28125 | 4 | # Written by Shreyansh Priyadarshi.
# This code can reverse the DNA chain and then find its complementary strand.
# Enter DNA sequence below between ''.
DNA = ''
reverse_complement = ''
for i in DNA:
if i == 'A':
reverse_complement += 'T'
elif i == 'T':
reverse_complement += 'A'
elif i == 'C':
reverse_complement += 'G'
else:
reverse_complement += 'C'
reverse_complement_output = ''.join(reversed(reverse_complement))
print(reverse_complement_output)
| true |
795eeec22b6693172437e68cb50c8438777c7bbd | mandrakean/Estudo | /Python_Guan/ex033.py | 564 | 4.15625 | 4 | num1= int(input('digite o primeiro número: '))
num2= int(input('digite o segundo número: '))
num3= int(input('digite o terceiro número número: '))
if num1 > num2 and num1 > num3:
print('o maior número é o {}'.format(num1))
elif num2 > num3:
print('o maior número é o {}'.format(num2))
else:
print('o maior número é o {}'.format(num3))
if num1 < num2 and num1 < num3:
print('o menor número é o {}'.format(num1))
elif num2 < num3:
print('o menor número é o {}'.format(num2))
else:
print('o menor número é o {}'.format(num3)) | false |
7ef46c10904f7003d99d9eef94f8583f8192d8f5 | ToLoveToFeel/LeetCode | /Python/_0048_Rotate_Image/Solution.py | 855 | 4.1875 | 4 | # coding=utf-8
from typing import List
# 执行用时:40 ms, 在所有 Python3 提交中击败了61.26%的用户
# 内存消耗:14.9 MB, 在所有 Python3 提交中击败了37.08%的用户
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(0, n):
j = 0; k = n - 1
while j < k:
matrix[j][i], matrix[k][i] = matrix[k][i], matrix[j][i]
j += 1; k -= 1
for i in range(0, n):
for j in range(0, i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
if __name__ == "__main__":
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Solution().rotate(matrix)
print(matrix)
| false |
52f49980eefe03cbad2c58fec37c3f5b5ecd0cd1 | AadiKuchlous/Py.se1.ass1 | /comparing 2 numbers.py | 280 | 4.21875 | 4 | no1 = int(input("Enter a number \n"))
no2 = int(input("Enter another number \n"))
if(no1<no2):
print(no1,"is less than "+str(no2), "\n")
elif(no1>no2):
print(no1,"is greater than than "+str(no2)+"\n")
else:
print("Both numbers are equal \n")
print("End of program")
| true |
851a8c6f1d15e53d850e9d3c4a0916cd8c14fcde | longhikee/Clutter | /Test/python/basic/sort.py | 485 | 4.28125 | 4 | print(sorted([2,3,4,7,1,6]))
print(sorted(['a','g','c','h','z','i']))
items=['bread','eggs','milk','cheese']
print("sorted(items)~~~~")
print(sorted(items))
items.sort()
print("item.sort()~~~~")
print(items)
items.sort(key=lambda x: x,reverse=True)
print("item.sort() in reverse~~~")
print(items)
books = [('book1','a',10),('book2','b',8),('book3','c',6)]
#the third element sorted
sorted(books,key=lambda books:books[2])
print(books)
print(sorted(books,key=lambda books:books[2]))
| false |
4d6dbf543d8dd56e0ade9b7e07c60b0b47ebefba | kumarnitishbehera/python_class | /Dictionary Python.py | 507 | 4.375 | 4 | fruits={"orange":"a sweet ans sour fruit",
"apple":"good for health",
"leamon":"has vitamin c in it",
"carrot":"used as a salad",
"carrot" :"can be used in many dishes",
"mango" :"best summer fruit"
}
print(fruits)
fruits["mango"]="seasonal fruit, very popular"
print(fruits)
name=input("what fruit you like:")
print(fruits.get(name))
name=input("what fruit you like:")
if name in fruits:
print(fruits[name])
else:
print("fruit not found!!!!!!")
| true |
0dff02e663af712c40f467b252b027778c01037f | hpalheta/minibiopython | /py03operadores.py | 1,956 | 4.25 | 4 | # coding: utf-8
'''
Programa : py03_operadores.py
Homepage : http://www
Autor : Helber Palheta <hpalheta@outlook.com>
Execução:
python py03_operadores.py
'''
#tabela apoio
'''
===== ========================= ==========================
Tipo Descrição Ex:
===== ========================= ==========================
(+) Soma res = 3 + 1, x = a + b
(-) Subtração res = 9 - 1, x = a - b
(*) Multiplicação res = 2 * 3, x = a x b
(/) Divisão. res = 10 / 2, x = a / b
(%) Módulo (resto) res = 10 % 3, x = a % b
(**) Potenciação res = 2**2, x = a ** b
(//) Divisão Resultado Inteiro res = 10 // 3 , x = a // b
===== ========================= ==========================
'''
#função print
print("Testando operadores")
print("\n");
#Variavel a recebe valor 10
a = 10
#Variável b recebe valor 3
#print
b = 3
#Variável x recebe soma a + b
x = a + b
#print da operação
print("Operacao (x = a + b) %d + %d = %d " %(a,b,x))
print("\n");
#Variável x recebe subtracao a - b
x = a - b
#print da operação
print("Operacao (x = a - b) %d - %d = %d " %(a,b,x))
print("\n");
#Variável x recebe multiplicacao a * b
x = a * b
#print da operação
print("Operacao (x = a * b) %d * %d = %d " %(a,b,x))
print("\n");
#Variável x recebe divisão a / b
x = a / b
#print da operação
print("Operacao (x = a * b) %d / %d = %f " %(a,b,x))
print("\n");
#Variável x recebe divisão inteiro a // b
x = a // b
#print da operação
print("Operacao (x = a // b) %d // %d = %d " %(a,b,x))
print("\n");
#Variável x recebe modulo a / b
x = a % b
#print da operação
print("Operacao (x = a %% b) %d %% %d = %d " %(a,b,x))
print("\n");
#Variável x recebe potencia a ^ b
x = a ** b
#print da operação
print("Operacao (x = a ** b) %d ** %d = %d " %(a,b,x))
print("\n");
| false |
0f51888466ce1ba89519e80e57ba823cbb4ab426 | stixaw/PythonScripts | /Critter.py | 622 | 4.25 | 4 | # We Learn Chapter 8
#Simple Critter
# Demonstrate a basic class and object
class Critter(object):
"""a virtual pet"""
def __init__(self, name):
print "A new Critter has been born!"
self.name = name
def __str__(self):
rep = "Critter object\n"
rep += "name: " + self.name + "\n"
return rep
def talk(self):
print "\nHi, I am ", self.name, "\n"
#main
crit1 = Critter("Poopie")
crit1.talk()
crit2 = Critter("Loopie")
crit2.talk()
print "Printing crit1: "
print crit1
print "Directly accessing crit2.name: "
print crit2.name
raw_input("\n\nPress the enter key to exit.") | false |
7cd4b936b9be967773a9dfa454f1e18ad4f6f454 | stixaw/PythonScripts | /HackerRank6of30.py | 1,516 | 4.1875 | 4 | Python answers:
for i in range(int(input())): s=input(); print(*["".join(s[::2]),"".join(s[1::2])])
for N in range(int(input())):
S = input()
print(S[::2], S[1::2])
'''The colon, inside an array index, can set up to 3 numbers/parameters:
The first one is the "from" number (included), the second is the "to" number (excluded), and the third is the "pace".
a[::2] will retrieve all array items (since it does not set up any from or to, and set the "pace"), starting from index 0, incrementing the index two by two and accessing all even indexes (0,2,4,6, and so on).
s[1::2] will retrieve all array items, from index 1, incrementing the index two by two and accessing all odd indexes (1,3,5,7,9, and so on).
This is Python's syntax for slicing lists: alist[start:end:step]. You can hide these values to take their default, for example: alist[::] means a full copy of the list. alist[1:3] slices a list taking item from index 1 to index 3 (non-inclusive).
alist[::2] makes makes a new list taking every other item from alist starting at 0.'''
def inputs():
global S
S = input()
if (len(S) in range (2, 10001)):
s1 = S[0::2]
s2 = S[1::2]
print (s1 + " " +s2)
T = int(input())
if (T>=1 and T<=10):
for i in range (0,T):
inputs()
for i in range(int(input().strip())):
print((lambda x: x[::2] + ' ' + x[1::2])(input().strip()))
for i in range(int(raw_input())):
s=raw_input()
print(s[::2]+" "+s[1::2]) | true |
c1a93d4497c6ea0664f0c1cd304e902091bb2b6c | stixaw/PythonScripts | /HackerRankPythonListAgain.py | 2,067 | 4.4375 | 4 | #Lists again
'''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 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 of the subsequent lines contains one of the commands described above.
Constraints
The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]'''
#Solution Python2:
def commandMe(N):
list = []
for n in range(N):
cmdArr = raw_input().split(' ')
cmd = cmdArr[0]
args = cmdArr[1:]
if len(cmdArr)>0:
if cmd != 'print':
params = "("+ ",".join(args)+")"
cmd += params
eval("list."+cmd)
else:
print list
if __name__ == '__main__':
N = int(input())
commandMe(N)
#Python 3:
def commandMe(N):
list = []
for n in range(N):
cmdArr = input().split()
cmd = cmdArr[0]
args = cmdArr[1:]
if len(cmdArr)>0:
if cmd != 'print':
cmd = "list." + cmdArr[0]
params = "("+ ",".join(args)+")"
cmd += params
eval(cmd)
else:
print(list)
if __name__ == '__main__':
N = int(input())
commandMe(N) | true |
78815513bf7cb5594a7a13e7fdc0c38f14ef4da0 | stixaw/PythonScripts | /handleit.py | 476 | 4.15625 | 4 | #handle exceptions
#try/except
try:
num = float(raw_input("Enter a Number: "))
except:
print "That was not a number"
#handle Valueerror specific only
try:
num = float(raw_input("Enter a Number: "))
except(ValueError):
print "that was not a number hoser!"
#handle multiple exceptions
print
for value in (None, "hi!")
try:
print "attempting to convert", value, "->",
print float(value)
except(TypeError, ValueError):
print "you screwed"
| true |
2ad992a6b6acf8693729aa8e1b4e167dace1efc5 | stixaw/PythonScripts | /Newmessage.py | 558 | 4.5 | 4 | #No Vowels
#demonstrates creating a new string from an existing one wihtout Vowels
print "this program takes a message and creates a new one without Vowels"
#get the message
message = raw_input("Please enter a message: ")
#set up for new message
new_message = ""
VOWELS = "a","e","i","o","u"
print
for letter in message:
if letter.lower() not in VOWELS:
new_message += letter
print "A new string has been created:", new_message
print "\nYour new message without vowels is: ", new_message
raw_input("\nPress Enter to exit") | true |
b5b7b5f0a33711eee3524f9ab0c82b64da26c690 | tripletrouble1/python-learning | /largest of 3.py | 296 | 4.15625 | 4 | a=int(input("enter the 1st number"))
b=int(input("enter the 2nd number"))
c=int(input("enter the 3rd number"))
if (a >= b) and (a >= c):
print(f"the largest number is {a}")
elif (b >= a) and (b >= c):
print(f"the largest number is {b}")
else:
print(f"the largest number is {c}")
| true |
10347dd559b506666e4a9be65b16982fa95c9d88 | jplindquist/Projects | /Numbers/prime_factorization.py | 733 | 4.15625 | 4 | #!/usr/bin/python
"""
Have the user enter a number and
dislay all Prime Factors (if there are any)
"""
"""
Check whether the given number is prime or not
"""
def isPrime(x):
# 1 and 2 are both prime numbers...
if x ==1 or x == 2:
return True
# If it's divisible by 2, it's not a prime number...
if x % 2 == 0:
return False
# If x is evenly disivisble by 3, or any number up to sqrt(x) + 1
# the number is not a prime number
for i in range(3, int(x ** 0.5) + 1, 2):
if x % i == 0:
return False
return True
def main():
for i in range(1, 100):
print "The number %d is prime: %r" % (i, isPrime(i))
if __name__ == "__main__":
main()
| true |
d4c83d487a3ea1b57fd22d1f0a9b34b85bcdd265 | chandru-55/Exe_programs | /dict_ran1_4.py | 499 | 4.46875 | 4 | '''
Define a function which can print a dictionary where the keys are numbers between 1 and
3 (both included) and the values are square of keys.
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
'''
# decalring dictionary function
def dict_fun(x):
if x in range(1,4):
d = dict() #defining
d[x]= x**2
print(d)
def main():
for x in range(1,4):
dict_fun(x)
if __name__=="__main__":
main()
| true |
8ee0f1f6e4a0f4233fd360b04297a8f090ca46eb | ZavrazhinMA/PythonPart1 | /hw_2_1.py | 689 | 4.125 | 4 | """1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого
элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя,
а указать явно, в программе."""
list_to_type = ['text', 2, 2.21, True, 1, (1, 3, 7), {3, None, True}, None]
for number, element, in enumerate(list_to_type, 1):
print("{}) {} - тип элемента {}".format(number, element, type(element)))
| false |
783420711eb3db785c2aca9116136461514fe822 | ZavrazhinMA/PythonPart1 | /hm_1.py | 796 | 4.375 | 4 | """1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел
и строк и сохраните в переменные, выведите на экран."""
int_number = 1
print(int_number, type(int_number))
a = float(int_number)
print(a, type(a))
b = 0x11
c = 0o12
print(b-c)
print(b, type(b))
print(c, type(c))
float_var = float(input('введите целое число '))
print(float_var, "- целое число преобразовалось в вещественное")
line_var = input("введите произвольный набор символов ")
print(line_var, " - \t", type(line_var))
bool_var = True
print(type(bool_var))
| false |
90489e7cc9592356c88f89d8c540b886ec450bf4 | xaveng/HackerRank | /Python/Insertion Sort - Part 1/Solution.py | 2,519 | 4.5625 | 5 | '''
Created on 2016. 1. 17.
@author: SeoJeong
'''
from _ctypes import Array
'''
Sorting
One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms.
Insertion Sort
These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list.
Insert element into sorted list
Given a sorted list with an unsorted number e in the rightmost cell, can you write some simple code to insert e into the array so that it remains sorted?
Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort.
Guideline: You can copy the value of e to a variable and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until V can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with e.
Input Format
There will be two lines of input:
Size - the size of the array
Arr - the unsorted array of integers
Output Format
On each line, output the entire array every time an item is shifted in it.
Constraints
1≤Size≤1000
−10000≤e≤10000,e∈Arr
Sample Input
5
2 4 6 8 3
Sample Output
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 3 4 6 8
Explanation
3 is removed from the end of the array.
In the 1st line 8>3, so 8 is shifted one cell to the right.
In the 2nd line 6>3, so 6 is shifted one cell to the right.
In the 3rd line 4>3, so 4 is shifted one cell to the right.
In the 4th line 2<3, so 3 is placed at position 2.
Task
Complete the method insertionSort which takes in one parameter:
Arr - an array with the value e in the right-most cell.
Next Challenge
In the next Challenge, we will complete the insertion sort itself!
'''
def printArr(arr):
print(" ".join(map(str, arr)))
pass
if __name__ == '__main__':
size = int(input().strip())
arr = list(map(int, input().strip().split()))
temp = 0
for i in range(1, len(arr)):
if arr[i - 1] > arr[i]:
temp = arr[i]
while arr[i - 1] > temp and i != 0:
arr[i] = arr[i - 1]
printArr(arr)
i -= 1
pass
arr[i] = temp
printArr(arr)
pass
pass
| true |
bc4cd68e26d738633bd4019ba170a8040e3e96de | xaveng/HackerRank | /Python/Find Digits/Find Digits/Find_Digits.py | 1,506 | 4.3125 | 4 | #!/bin/python3
import sys
'''
Given an integer, NN, traverse its digits (dd1,dd2,...,ddn) and determine how many digits evenly divide NN (i.e.: count the number of times NN divided by each digit ddi has a remainder of 00). Print the number of evenly divisible digits.
Note: Each digit is considered to be unique, so each occurrence of the same evenly divisible digit should be counted (i.e.: for N=111N=111, the answer is 33).
Input Format
The first line is an integer, TT, indicating the number of test cases.
The TT subsequent lines each contain an integer, NN.
Constraints
1<=T<=15
0<N<109
Output Format
For every test case, count and print (on a new line) the number of digits in NN that are able to evenly divide NN.
Sample Input
2
12
1012
Sample Output
2
3
Explanation
The number 1212 is broken into two digits, 11 and 22. When 1212 is divided by either of those digits, the calculation's remainder is 00; thus, the number of evenly-divisible digits in 1212 is 22.
The number 10121012 is broken into four digits, 11, 00, 11, and 22. 10121012 is evenly divisible by its digits 11, 11, and 22, but it is not divisible by 00 as division by zero is undefined; thus, our count of evenly divisible digits is 33.
'''
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
digits = ''.join(sorted(str(n).replace('0', '')))
result = 0
for i in range(1, 10):
count = digits.count(str(i))
if count != 0 and n % i == 0:
result += count
pass
pass
print(result)
pass | true |
f53b13525d802ef6ec9643375640198bc14b8cf3 | fx86/euler | /primes.py | 345 | 4.21875 | 4 | '''
all basic functions about prime numbers appear here
'''
def isprime(n):
''' checks if a number is prime or not '''
if n <= 3:
return n >= 2
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, int(n ** 0.5) + 1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
| false |
3d4063ada36af3779b7ee1a329409ab97a025f70 | zfoteff/CPSC353 | /p1/project1.py | 2,972 | 4.28125 | 4 | """
Name: Zac Foteff
Class: CPSC 353
Date Submitted: [XXXXX]
Assignment: Project 1
Description: Program implements the Transposition Cipher, a symmetric key
cipher, as well as methods to encrypt and decrypt any given string
"""
import random
"""
Method returns a list containing all 26 ordered letters of the alphabet
"""
def a_list():
a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# Generates list of the letters of the alphabet
a_list = [x for x in a]
return a_list
"""
Generates a random permutation of the alphabet and returns that permutation to
be used as the key for the Transposition Cipher
"""
def key_gen():
# Create list of the letters of the alphabet
perm = a_list()
# Shuffles that list in place
random.shuffle(perm)
return perm
"""
Returns the encryption of the plaintext string, p, using the random permutation
of the alphabet, key
p: Plaintext string to be encrypted
key: list with random permutation of the alphabet
"""
def encrypt(p, key):
# Empty ciphertext string
c = ""
# Next sequence strips spaces, punctuation marks, and other characters
# not in the alphabet from the string and then makes the string uppercase
# for ease of handling later
plaintext = p.replace(" ", "")
plaintext = plaintext.strip(",.:;?!")
plaintext = plaintext.upper()
for x in plaintext:
# Retrieve the element from the key that corresponds with the ASCII #
# of each plain text character, then append that element to the
# ciphertext string for encryption
c += key[ord(x)-65]
return c
"""
Returns decryption of the ciphertext string, c, using the random permutation of
the alphabet, key
"""
def decrypt(c, key):
# Empty plaintext string
p = ""
# Make an list containing key and all elements of the alphabet
decypher = key + a_list()
# Sort first 26 elements into lexigraphical order, making the same swaps
# to the last 26 elements of the list
for i in range(0, 25):
# If the ASCII value of the character is different than the index it
# exists at, swap it with the element at the correct index
if (ord(i)-65 != i):
temp = decypher[ord(i)-65]
decypher[ord(i)-65] = decypher[i]
decypher[i] = temp
# Make those same swaps to the alphabet section of list
# With k in lexographical order, parse each character in the ciphertext to
# construct the plaintext from the shuffled alphabet
for x in c:
p += decypher[ord(x+26)-65]
return p
# Main loop
while True:
key = key_gen()
userPlaintext = input("Enter a message to encode (No numbers) or 'q' to quit: ")
if userPlaintext == "q":
break
userCiphertext = encrypt(userPlaintext, key)
print("Your encrypted message is: "+userCiphertext)
print("That message decrypted is: "+decrypt(userCiphertext, key)+"\n\n")
| true |
0a891ac511c6202c27265da1b50610d6508a2953 | DanielJoseph-Lehmuth/UHCIS2348-Spring21-Lehmuth | /Homework4/Zylab_14.11.py | 1,124 | 4.34375 | 4 | # Daniel Lehmuth
# 1936204
# This function is used to sort user inputted numbers into a selection sorted list
def selection_sort_descend_trace(num_list):
num_list = [int(s) for s in num_list] # first converts the strings to integers
for i in range(len(num_list) - 1):
large_num = i
for j in range(i + 1, len(num_list)):
if num_list[j] > num_list[large_num]: # if j is bigger than large_num, j becomes the new value of large_num
large_num = j
temp = num_list[i] # this block swaps num_list[i] and num_list[large_num]
num_list[i] = num_list[large_num]
num_list[large_num] = temp
for num in num_list: # this for loop prints each iteration on a line
if num != num_list[-1]:
print(num, end=" ")
else:
print(num, "")
return num_list
if __name__ == "__main__":
user_input = input()
numbers = user_input.split(" ") # takes the user input and turns it into a list
selection_sort_descend_trace(numbers) # this calls the function defined above
| true |
4c6ab7313a32d408103e86645001729b8c4354bd | mikedcurry/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,274 | 4.1875 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n elements
for i in range(len(arr)):
# begin with assumption that i is smallest
current_at = i
smallest_at = current_at
# Looks ahead to each consecutive value after i in the list
# if j-term is smaller than i-term, declares j smallest
for j in range(i+1, len(arr)):
if arr[j] < arr[smallest_at]:
smallest_at = j
# swaps places iff smallest is different than current
# otherwise nothing -- assigns itself to itself
arr[i], arr[smallest_at] = arr[smallest_at], arr[i]
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# iterate through list
for i in range(len(arr)):
for j in range(len(arr)-1):
# kind of wonky, but j has to be 1 less than list times
# want to start at i+1, and end at j+1
j += 1
if arr[j-1] > arr[j]:
# swap values iff left term is bigger than right
arr[j-1], arr[j] = arr[j], arr[j-1]
return arr
# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):
return arr | true |
3eb2c3231ca880bf7890a4cb274591e1883b70d8 | krook98/hangman | /main.py | 1,429 | 4.125 | 4 | import random
words = ['backlog', 'beacon', 'bike', 'bone', 'broke']
word = random.choice(words)
good_guesses = [None for good_guess in word]
guesses = []
x = True
while x:
letter = input("Please enter your letter:")
# check if variable letter contains only letters and if there is only one letter
if not letter.isalpha() and len(letter) == 1:
print("Sorry, you must enter only a single letter.")
continue
# check if the letter was already guessed
if letter in guesses:
print("You have already guessed this letter.")
continue
# if you guessed the letter, add it to already guessed ones
guesses.append(letter)
# check if the letter is in a word
good_indexes = []
for i in range(len(word)):
if word[i] == letter:
good_indexes.append(i)
# check if there was actually a good guess
if len(good_indexes) == 0:
print("Wrong guess.")
continue
print("Good guess!")
print(f"Those are letter(s) of index(es) {good_indexes}")
for letter_index in good_indexes:
# add the correctly guessed letters to a list
good_guesses[letter_index] = letter
# print only correctly guessed letters
print([l for l in good_guesses if l is not None])
# Finishing the process when player guessed all letters
if None not in good_guesses:
print("Nice job! You won!")
x = False
| true |
2dcfdb441e2d73b8bb0b6fe2cd3491f2ec44ab37 | davruk/webdev1 | /unit_conv_2.py | 341 | 4.28125 | 4 | print("Hy, I convert km into miles!")
while True:
km = float(input("Please, enter the value in km: "))
# conversion factor = 0.62138
miles = km * 0.62138
print(f"{km} {miles}")
user_convert_again = input("Would you like to do another conversion (y/n)")
if user_convert_again != "y":
print("By,by! Thank you!")
| true |
db1fb14a8ebf3297fcb6886709ed2a6823819387 | gpxlnx/CursoIntensivoDePython | /Parte1/Cap9/dog.py | 873 | 4.25 | 4 | class Dog():
"""Uma tentativa simple de modelar um cachorro."""
def __init__(self, name, age):
"""Inicializa os atributos name e age."""
self.name = name
self.age = age
def sit(self):
"""Simula um cachorro sentando em resposta a um comando."""
print(self.name.title() + " in now sitting.")
def roll_over(self):
"""Simula um cachorro rolando em resposta a um comando."""
print(self.name.title() + " rolled over!. ")
"""My dog"""
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
"""Your dog"""
your_dog = Dog('Kiara', 1)
print(f'Meu cachorro(a) chama ' + your_dog.name.title() + '.')
print(f'Ele(a) tem ' + str(your_dog.age) + ' de idade.')
your_dog.sit()
your_dog.roll_over()
| false |
51e47c122dc6f6f61117aa07141f12855b2f4888 | drvpereira/hackerrank | /cracking the coding interview/techniques/time complexity primality/solution.py | 311 | 4.1875 | 4 | from math import floor, sqrt
def is_prime(n):
if n == 2:
return True
elif n == 1 or n % 2 == 0:
return False
for x in range(3, floor(sqrt(n))+1, 2):
if n % x == 0:
return False
return True
for _ in range(int(input())):
if (is_prime(int(input()))):
print('Prime')
else:
print('Not prime') | false |
2a694902e98bff82d9da2fe81f2c27352fd02862 | amiiitparmar/Python-course-with-notes---Basic-to-Advanced- | /chapter3.py | 1,526 | 4.4375 | 4 | # a = 45
# b = 'amit'
# print(a , b)
# #Slicing
# greeting = "Good Morning"
# name = " amit "
# print(type(name))
# c= greeting + name
# print(c)
# name = "amitparmar"
# print(name[2])
# String ka character access toh kr skte ho but change nai kr skte
# print(name[0:2])
# Negative indexing
# c = name[-3:-1]
# print(c)
# Slicing with skip value
# d = name [1::3]
# print(d)
# Story = "Once upon a time there was a boy named amit who got 80 lac per annum package from the google"
# # print(len(Story))
# print(Story.endswith("rry"))
# print(Story.count("upon"))
# print(Story.capitalize())
# print(Story.find("was"))
# print(Story.replace("upon", "sincere"))
# Escape sequence character
# \n \t
# story = "Amit is a good boy\n and very smart "
# print(story)
# Practice set
# name= input("Enter your name ")
# print("Good Morning ," + name)
# letter = ''' Dear <|Name|>,
# You are selected !
# Date: <|DATE|>
# '''
# name = input("Enter your name\n")
# date = input("Enter your date\n")
# letter =letter.replace("<|Name|>", name)
# letter =letter.replace("<|DATE|>", date)
# print(letter)
# Find double spaces
# st = "This is a string with double spaces"
# doubleSpaces=st.replace(" "," ")
# # doubleSpaces=st.find(" ")
# print(doubleSpaces)
# letter = "Dear harry, This python course is nice!Thanks!"
# print(letter)
# formatted_letter = "Dear harry,\n\t T his python course is nice!Thanks!"
# print(formatted_letter)
| false |
c24a1c6903de0529e5388b20eb64d523fc55fdbb | NateBigStone/lab02_python_basics | /03_student_dataclass.py | 907 | 4.5625 | 5 | from dataclasses import dataclass
"""
Type in the dataclass code from the slides/video
Add one more field: gpa, a float
Write a main function to create some example Student objects with some example names, college_id and GPA values.
Verify you can read the name, college ID and GPA for an example student. Verify when you print an example student, the GPA is included.
Add some comments in your code to compare the dataclass version to the "traditional" version
"""
@dataclass
class Student:
name: str
college_id: int
gpa: float
#Using a dataclass vs the tradition version uses much less code and simplifies this common usage of classes
def main():
alice = Student('Alice', 12345, 2.0)
bob = Student('Bob', 98765, 3.6)
nate = Student('Nate', 8675309, 4.0)
print(alice)
print(bob)
print(f'Name: {nate.name} GPA: {nate.gpa}')
if __name__ == "__main__":
main()
| true |
86b3a4a8b31fe1495eeee5859c3bb66ef6c04c3d | Igor-Rizzo/fundamentos_python | /modulo_dois/_aula_8.py | 701 | 4.125 | 4 | #DESAFIO 1: Transforme a frase1 em uma lista de palavras e guarde o resultado em uma variavel chamada palavras1
frase1 = "Desafio manipulação de strings"
frase2 = "jhonatan,rafael,carol,camilla"
palavras1 = frase1.split()
#Desafio 2: Transforme a frase2 em uma lista de palavras guarde o resultado em uma variavel chamada palavras2
palavras2 = frase2.split(',')
#DESAFIO 3: Pegue o palavras1 e transforme elas no seguinte string: "Desafio,manipulação,de,strings". Imprima o resulte no console
print(','.join(palavras1))
#DESAFIO 4: Pegue o palavras2 transforme elas no seguinte string: frase2 = "jhonathan & rafael & carol & camila". imprima o resultado no console
print(' & '.join(palavras2)) | false |
4497c0933b9a2e154c20829c28fef22064370858 | Shraddhat5191/Python_File | /if else/largest1.py | 462 | 4.28125 | 4 | num1=int(input("enter the enput"))
num2=int(input("enter the enput"))
num3=int(input("enter the enput"))
if num2>num1 or num2>num3:
print("largest num1")
if num1>num2 or num1>num3:
print("largest num2")
if num2>num3 or num3>num2:
print("less num3")
else:
print("num3 not largest")
else:
print("num2 not lergest")
else:
print("num1 not largest")
| false |
5122937537008454d26a0c004b3444952069bb52 | Shraddhat5191/Python_File | /if else/secondmax.py | 365 | 4.15625 | 4 | user1=int(input("enter the enput"))
user2=int(input("neter the enput"))
user3=int(input("enter the input"))
if user1>user2>user3 or user3>user2>user1:
print(user2,"is second greater num")
if user2>user2<user1 or user1>user3<user2:
print(user3,"is second greater num")
if user3>user1>user2 or user2>user1>user3:
print(user1,"is second greater num")
| true |
438440c471a3a6e3f792b2385c50ed495fe208f2 | Shraddhat5191/Python_File | /if else/alphvo.py | 209 | 4.15625 | 4 | character=input("enter the alphabet")
if character == 'a' or character== 'e' or character == 'i' or character == 'o' or character == 'u':
print("this is a vowel")
else:
print("this is a consonent") | true |
26a6b602d6a6a019b69088bfcf121e86dd20ac1e | Ph1lll/Python | /savings per day.py | 425 | 4.125 | 4 |
# Asking the user how many pounds do they have
pounds = input("How many pounds do you have? ")
while (not pounds.isdigit()):
pounds = input("How many pounds do you have? ")
#Convert string into float
pounds = float(pounds)
# Exchange rate of pounds to euros (2021)
exchange = 1.16
Euros = pounds * exchange
# Why not
print("{:.2f}€".format(Euros))
day_spend = Euros/4
print("{:.2f}€ per day".format(day_spend)) | true |
4dca61ba905f0a9329184efb72db22c7e16c4129 | emi-ve/Pizza_Slice_Lists | /Pizza_Slice.py | 1,200 | 4.375 | 4 | # Your code below:
toppings = ["pepperoni","pineapple","cheese","sausage","olives","anchovies","mushrooms"]
prices = [2,6,1,3,2,7,2]
# count $2 slices
num_two_dollar_slices = prices.count(2)
#count length of toppings list
num_pizzas = len(toppings)
print(num_pizzas)
#change int to string, and print result in a sentence
new_string = str(num_pizzas)
print("We sell " + new_string + " different kinds of pizza!")
#create manual 2D list from previous data
pizza_and_prices = [[2,"pepperoni"],[6,"pineapple"],[1,"cheese"],[3,"sausage"],[2,"olives"],[7,"anchovies"],[2,"mushrooms"]]
print(pizza_and_prices)
#sort list
pizza_and_prices.sort(reverse=False)
#select cheapest pizza, store in variable
cheapest_pizza = pizza_and_prices[0]
print(cheapest_pizza)
#Get the last item of the pizza_and_prices list and store it in a variable called priciest_pizza.
priciest_pizza = pizza_and_prices[-1]
print(priciest_pizza)
#remove the most expensive slice
pizza_and_prices.pop()
print(pizza_and_prices)
#insert new pizza to list
pizza_and_prices.insert(3,[2.5,"peppers"])
print(pizza_and_prices)
#slice 3 cheapest pizzas, store in variable
three_cheapest = pizza_and_prices[:3]
print(three_cheapest)
| true |
58c695fa63e3ad56d2d4d6bf8936005ca4bdbe19 | imdangun/python.19.08 | /python.19.08/13 if.py | 1,015 | 4.125 | 4 | x = 10
if x == 10:
print('10')
if x == 10: print('10')
if x == 10:
pass
if x == 10:
print('10')
print('십')
x = 15
if x>=10:
print('10 이상')
if x == 15:
print('15 입니다.')
if x == 20:
print('20 입니다.')
# 10 이상
# 15 입니다.
x = 5
if x == 10:
print('10입니다.')
else:
print('10이 아닙니다.')
# False: None, False, 0, 0.0, '', "", [], (), {}, set()
if x>0 and x<20:
print('20미만 수입니다.')
# 20미만 수입니다.
if 0<x<20:
print('20미만 수입니다.')
# 20이하 입니다.
x = 30
if x == 10:
print('10입니다.')
elif x == 20:
print('20입니다.')
else:
print('10이나 20이 아닙니다.')
# 10이나 20이 아닙니다.
button = int(input())
if button == 1:
print('콜라')
elif button == 2:
print('사이다')
elif button == 3:
print('환타')
else:
print('버튼을 잘못 눌렀습니다.')
# >? 2
# 사이다 | false |
a89542f6b59a9ec47e009c7cee083fdaabc38c96 | ugurcan-sonmez-95/Python-Projects | /CaesarCipher.py | 2,491 | 4.75 | 5 | #!/usr/bin/env python3
### CAESAR CIPHER ###
# The program implements a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25.
# This cipher rotates the letters of the alphabet (A to Z).
# The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
# For example, key 3 encrypts "ABC" to "DEF".
my_string = "abcdefghijklmnopqrstuvwxyz"
def encrypt(text,key):
# This function is used to encrypt the given text.
encrypt_string = "abcdefghijklmnopqrstuvwxyz" * 2
output = ""
for char in text:
if char in my_string:
index = encrypt_string.index(char)
output += encrypt_string[index + key]
else:
output += char
return output
def decrypt(text,key):
# This function is used to decrypt the given text.
decrypt_string = "zyxwvutsrqponmlkjihgfedcba" * 2
output = ""
for char in text:
if char in my_string:
index = decrypt_string.index(char)
output += decrypt_string[index + key]
else:
output += char
return output
# At the final step, we define the user's choices and make the program ready for use.
if __name__ == '__main__':
print(" Enter 1 to encrypt a text\n Enter 2 to decrypt a text\n Enter 3 to do them both\n ")
choice = int(input("Please enter a choice: "))
if choice == 1:
string_txt = input("Enter the text you want to encrypt: ")
key = int(input("Enter a key between 1-25: "))
print("The encrypted text is: ")
print(encrypt(string_txt, key))
elif choice == 2:
string_txt = input("Enter the text you want to decrypt: ")
key = int(input("Enter a key between 1-25: "))
print("The decrypted text is: ")
print(decrypt(string_txt, key))
elif choice == 3:
string_txt = input("Enter the text you want to encrypt and decrypt at the same time: ")
key = int(input("Enter a key between 1-25: "))
print("The encrypted text is: ")
print(encrypt(string_txt, key))
print("The decrypted text is: ")
print(decrypt(string_txt, key))
else:
print("Your choice is invalid. Please try again!")
| true |
6243146c5bd1b790b340fea3bce89adb3c49a7c8 | tamatskiv/python | /task5_2.py | 513 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
print('Enter the height and the width of the rectangular door:')
h = int(input())
w = int(input())
print ('Enter three dimensions of the box:')
a = int(input())
b = int(input())
c = int(input())
if a <= h and b <= w:
print('yes')
elif b <= h and a <= w:
print('yes')
elif a <= h and c <= w:
print('yes')
elif c <= h and a <= w:
print('yes')
elif b <= h and a <= w:
print('yes')
elif a <= h and c <= w:
print('yes')
else:
print('no')
| false |
b9a096abe287d3ed9e7af8080e247cb8a0aecd26 | Sibusiso-Mgidi/vac_programme | /src/intro_day3.py | 2,167 | 4.375 | 4 |
class Student(object):
"""
This is a blueprint for the student demographic data
"""
def __init__(self, firstname, lastname, student_number):
self.student_firstname = firstname
self.student_lastname = lastname
self.student_number = int(student_number)
def __repr__(self):
return "{} {}".format(self.student_firstname, self.student_lastname)
class Course(object):
"""
This is ablueprint for course information
"""
def __init__(self, course_name, course_code, lecturer_name):
self.course_name = course_name
self.course_code = course_code
self.lecturer_name = lecturer_name
def __repr__(self):
return "{} {}".format(self.course_name, self.lecturer_name)
class Question(object):
"""
This is a blueprint that stores the question and corresponding answer
"""
def __init__(self, question_statement, correct_answer ):
self.question_statement = question_statement
self.correct_answer = correct_answer
def __repr__(self):
return "{} {}".format(self.question_statement, self.correct_answer)
def get_ask_and_evaluate(self):
"""
This method prints the question, accepts solution from the student
and returns True if the solution is correct else it returns False.
"""
print(self.question_statement)
user_solution = input("")
if user_solution == self.correct_answer:
return True
else:
return False
class Assessment(object):
"""
This is ablue print for putting questions together to ask students
"""
def __init__(self, title,date):
self.title = title
self.date = date
self.question = list()
self.mark = 0
def __repr__(self):
return " "
# student_object = Student("Thapelo", "Seletisha", "1234567")
# course_object = Course("Linear Algebra", "MATH2025", "Zellenyik")
question_object = Question("Was Mandela born on the 18th of July 1950?", "False")
question_1 = question_object.get_ask_and_evaluate()
print(question_1)
| true |
5de0a598dea77c191f6d266f2bc1f16bd4741222 | ZhekunXIONG/Andorra_RNC | /ARIEL/SV/sv.py | 2,440 | 4.125 | 4 | # import os and urllib modules
# os for file path creation
# urllib for accessing web content
import urllib
import os
# this is the first part of the streetview, url up to the address, this url will return a 600x600px image
pre = "https://maps.googleapis.com/maps/api/streetview?size=300x300"
head = "&heading="
pitch = "&pitch=-0.76"
loc = "&location="
# this is the second part of the streetview url, the text variable below, includes the path to a text file containing one address per line
# the addresses in this text file will complete the URL needed to return a streetview image and provide the filename of each streetview image
text = "a.txt"
# this is the third part of the url, needed after the address
# API key
suf = "&key=AIzaSyAC9P4Njf_yRogkp0M-cPpWr5Op_r6hvg4"
# this is the directory that will store the streetview images
# this directory will be created if not present
dir = r"img"
# checks if the dir variable (output path) above exists and creates it if it does not
if not os.path.exists(dir):
os.makedirs(dir)
# opens the address list text file (from the 'text' variable defined above) in read mode ("r")
with open(text, "r") as text_file:
# the variable 'lines' below creates a list of each address line in the source 'text' file
lines = [line.rstrip('\n') for line in open(text)]
print "THE CONTENTS OF THE TEXT FILE:\n" + str(lines)
# start a loop through the 'lines' list
for line in lines:
# get several angles from each point
for ang in range(0, 360, 30): # 0 to 360 in jumps of 30 degrees
# string clean-up to get rid of commas in the url and filename
ln = line.replace(",", "")
print '\n'
print "CLEANED UP ADDRESS LINE:\n" + ln
# creates the url that will be passed to the url reader, this creates the full, valid, url that will return a google streetview image for each address in the address text file
URL = pre + head + str(ang) + pitch + loc + ln + suf
print "URL FOR STREETVIEW IMAGE:\n" + URL
# creates the filename needed to save each address's streetview image locally
filename = os.path.join(dir, ln + "_angle_" + str(ang) + ".png")
print "OUTPUT FILENAME:\n" + filename
# you can run this up to this line in the python command line to see what each step does
# final step, fetches and saves the streetview image for each address using the url created in the previous steps
urllib.urlretrieve(URL, filename)
| true |
f05933ee92e389ff076dcdd95449daa9ee9c97a9 | BLACKGOATGG/python | /basic-knowledge/py_2_数组,元组,for循环/基本:初识py数组.py | 567 | 4.1875 | 4 | #======================================================
# 列表非常适合用于存储在程序运行期间可能变化的数据集。
# 列表是可以修改的,这对处理网 站的用户列表或游戏中的角色列表至关重要。
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(len(bicycles))
print("0",bicycles[0])
print(bicycles[0].title())
print("1",bicycles[1])
print("2",bicycles[2])
print("-1",bicycles[-1])
print("-2",bicycles[-2])
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
| false |
78c7617a98aa7de82176ae9953a53265c76e2dbe | BLACKGOATGG/python | /basic-knowledge/py_5_用户输入与while/while.py | 1,672 | 4.125 | 4 | # ===========================================================
print('while 循环')
# for循环用于针对集合中的每个元素都一个代码块
# 而while循环不断地运行,直到指定的条件不满足为止。
print('\n使用while循环')
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
print('\n避免无限循环')
# 每个while循环都必须有停止运行的途径,这样才不会没完没了地执行下去。
# 如上面代码不小心遗漏了代码行current_number += 1,将形成死循环
# 每个程序员都会偶尔因不小心而编写出无限循环,在循环的退出条件比较微妙时尤其如此。
# 如果程序陷入无限循环,可按Ctrl + C,也可关闭显示程序输出的终端窗口。
# 要避免编写无限循环,务必对每个while循环进行测试,确保它按预期那样结束。
# 如果你希望程序在用户输入特定值时结束,可运行程序并输入这样的值;
# 如果在这种情况下程序没有结束,请检查程序处理这个值的方式
# 确认程序至少有一个这样的地方能让循环条件为False或让break语句得以执行。
print('\n让用户选择何时退出')
# 可使用while循环让程序在用户愿意时不断地运行
# 我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就接着运行
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
message = ""
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
| false |
6fed8049db787681c2c8af457a3832bdbd9adcc7 | rahul148/PythonTraining | /interview/erp meshsoftinterview.py | 2,750 | 4.21875 | 4 | #silcinf with string.................
str1="hello world"
print(str1[2:5])##o/p:"llo"
str1="rahull"
print(str1[0])#it will dsiplay the character which persent at index 0 o/p:"r"
#for with else.............
i=[1,2,3]#if "i" list is empty then it will directly goto the else loop.
for a in i:
print("it is in for loop")
else:
print("it is in else part")
#<<<1>>#The for ... else statement is used to implement search loops.
##In particular, it handles the case where a search loop fails to find anything.
for z in range(10):
if z == 5:
# We found what we are looking for
print("we found 5")
break # The else statement will not execute because of the break
else:
# We failed to find what we were looking for
print("we failed to find 5")
z = None
print('z = ', z)
#<<2>>>append() and extend() in Python.............................
"""
#Append::
Adds its argument as a single element to the end of a list.
The length of the list increases by one.
append() takes exactly one argument
"""
mylist=[1,2,3,4]
mylist.append(20)
print(mylist)
"""mylist.append(20,20)
TypeError: append() takes exactly one argument"""
###....import Note...#############....................
"""NOTE: A list is an object. If you append another list onto a list,
the first list will be a single object at the end of the list.
"""
my_list = ['geeks', 'for', 'geeks']
another_list = [6, 0, 4, 1]
my_list.append(another_list)
print(my_list)
##---extend():
""" Iterates over its argument and adding each element to the list and extending the list.
The length of the list increases by number of elements in it’s argument
"""
mylist=[1,2,3,'rahul']
print(mylist)
newlist=[0,4,5]
mylist.extend(newlist)
print("after extend::",mylist)
###importend Note about extends::###....................
"""
NOTE: A string is an iterable, so if you extend a list with a string,
you’ll append each character as you iterate over the string.
"""
mylist=["rahul",22,33,44]
s='rahul'
mylist.extend(s)
print("list after the strin extends::",mylist)
#o/p:
#->>list after the strin extends::
#['rahul', 22, 33, 44, 'r', 'a', 'h', 'u', 'l']
s=['rahul']
mylist.extend(s)
print("list after the strin extends::",mylist)
#o/p:
#"""list after the strin extends::
#['rahul', 22, 33, 44, 'rahul']"""
#what is output of the following programs::
#a=2,c=3,b=2 #...error-1 ===>..its show the error can't assign the literals
a=2
c=3
b=2
if a==b and c!=a or c==b:
print("IN the first if statements are excuted......")
###.... c=2 if c==b and b==a:....error-2 ===> invalid syntax...........
c=2
if c==b and b==a:
print("Its in second if statement is excuted")
| true |
b8b0710ab8dba442e6a293d35fb7038aeb7b01b4 | rahul148/PythonTraining | /showthefile-extension.py | 201 | 4.15625 | 4 | #show the file extension
file=input("enter the file name with extension::")
fexten=file.split(".")
print("the extension of the file is::" +repr(fexten[-1]))
#"repr"==it display output in single qouate
| true |
d9c3a123815d704e7fe75c06882ce09b19cda44d | sudoberlin/python-DSA | /BST.py/insert.py | 1,325 | 4.25 | 4 | # Python program to demonstrate insert operation in binary search tree
# A utility class that represents an individual node in a BST
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
# A utility function to insert a new node with the given key
def insert(root, node):
if root is None:
root = node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
# A utility function to do inorder tree traversal
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
def post_order(root):
if root:
post_order(root.left)
post_order(root.right)
print(root.val)
def pre_order(root):
if root:
print(root.val)
pre_order(root.left)
pre_order(root.right)
r = Node()
insert(r, Node(334))
insert(r, Node(2))
insert(r, Node(440))
insert(r, Node(700))
insert(r, Node(603))
insert(r, Node(8))
print("inorder: ")
inorder(r)
print("post order: ")
post_order(r)
print("pre order: ")
pre_order(r) | true |
72c2c6e8baadf325acb354844bd648357ae7f85d | anasalawa/Python | /Programs/factorial2.py | 258 | 4.375 | 4 | # Rewriting the factorial program using for loops
# Read n from the user
n = int(input("Enter a non-negative number: "))
# Compute n-factorial
result = 1
for i in range(1, n + 1):
result = result * i
# Display the result
print(n, "factorial is", result) | true |
927bbbeee382c636767ce29ce19aec6a6b90e8b1 | anasalawa/Python | /Programs/average.py | 532 | 4.40625 | 4 | # Compute the average of a collection of numbers entered by the user.
# The user will enter Enter to indicate that no more values will be entered
# and the average should be displayed.
value = input("Enter a number (Enter to quit): ")
total = 0
count = 0
# Read values until the user enters 0
while value != "":
total = total + float(value)
count = count + 1
value = input("Enter a number (Enter to quit): ")
if count == 0:
print("No values were entered.")
else:
print ("The average of those numbers is ", total / count) | true |
b1638f8edf52600befe28d94d42ef66de7e6e287 | anasalawa/Python | /Programs/lettergrade.py | 685 | 4.3125 | 4 | #Converting from a letter grade into the equivalent number of grade points
# A = 4.0
# B = 3.0
# C = 2.0
# D = 1.0
# F = 0.0
letter = input("What is your letter grade? ")
# if statement for the # of gradepoints for the entered letter
if letter == "A" or letter == "a":
gp = 4.0
elif letter == "B" or letter == "b":
gp = 3.0
elif letter == "C" or letter == "c":
gp = 2.0
elif letter == "D" or letter == "d":
gp = 1.0
elif letter == "F" or letter == "f":
gp = 0.0
else:
gp = -1.0
# Print the number of grade points.
if gp >= 0.0:
print ("The letter grade", letter, "is equal to", gp, "grade points.")
else:
print("Please enter a valid letter grade ranging from A to F") | true |
405037817d49b9c69afaea05c2c0935c421314e8 | anasalawa/Python | /Programs/fslexample.py | 656 | 4.15625 | 4 | # Count the number of times that what occurs in data
def countItems(data, what):
count = 0
for item in data:
if item == what:
count = count + 1
return count
# Count the number of times that what occurs in data
def countItems2(data, what):
count = 0
while len(data) > 0:
if data.pop() == what:
count = count + 1
return count
values = [1,2,1,3,1,2,3,4]
print("1 occurs in values", countItems(values, 1), "times using countItems.")
print("1 occurs in values", countItems2(values, 1), "times using countItems.")
# if you inverse the order of the print statements, the program will
# no longer work because you are using the method data.pop() | true |
fee4f2b7d7a27a63866487b0a29a457297caf24b | anasalawa/Python | /Programs/asn2help.py | 396 | 4.3125 | 4 | # Read integers from the user, and for each integer, report the difference
# between it and its immediate predecessor.
prev = int(input("Enter an integer (0 to quit): "))
while prev != 0:
value = int(input("Enter an integer (0 to quit): "))
print("The difference between", prev, "and", value, "is", value - prev)
# this is the key element. use this when graphing temperature
prev = value
| true |
4c69d8f6b9214fe8720e9978de5b7ce732176b7f | HussainPythonista/SomeImportantProblems | /sorT/InsertionSort.py | 483 | 4.1875 | 4 | def InsertionSort(listValue):
#Pointer
for pointer in range(1,len(listValue)):
current=listValue[pointer]
sortedArray=pointer-1
while sortedArray>=0 and current<listValue[sortedArray]:
listValue[sortedArray+1]=listValue[sortedArray]
sortedArray-=1#To check the values inside the sortedArray
listValue[sortedArray+1]=current
return listValue
listValue=[5,3,2,4,21,4,54,54,321]
print(InsertionSort(listValue)) | true |
561f3180466fd919d31a38bf03366facc24d5537 | zwcoop/guttag_intro_comp_ed3 | /ch3/pg49-fe.py | 539 | 4.25 | 4 | # Change the code in fig3-2.py so that it returns the largest
# rather than the smallest divisor.
# Hint: if y*z = x and y is the smallest divisor of x, z is the
# largest divisor.
x = int(input('Enter an integer greater than 2: '))
smallest_divisor = None
largest_divisor = None
for guess in range(2, x):
if x % guess == 0:
smallest_divisor = guess
largest_divisor = x//guess
break
if largest_divisor != None:
print('Largest divisor of', x, 'is', largest_divisor)
else:
print(x, 'is a prime number')
| true |
632bac368eaa4e2b8ea7f7ad15a499995f142f4c | Akash-Vijay/Encryption | /Decryptor.py | 971 | 4.4375 | 4 | """
Project : Decrpytor.py
Description : Program to decode a message, encrypted using 'Encryptor'
Creator : Akash Vijay
Date : 7th June, 2021
Updated :
"""
#Requesting for inputs
characters = int(input("Enter the number of characters :"))
key = int(input("Enter the Decryption key :"))
#Resolving the key into actual keys
key_1 , key_2 = key // 1000 , key % 1000
#Storing the encrypted segments in a list
encrypted = []
char = 0
for char in range(characters): #Stores the Encrypted segments into a list
encrypted_val = int(input("Enter the segment: "))
encrypted.append(encrypted_val)
#Decrypting
decrypted = ''
for char in encrypted:
decoded = char - ((key_1 * key_2) - (key_2 + 300) * (75 + key_1)) # Reverse Computing to obtain ASCII value
message_segment = chr(decoded) # Converting ASCII value to string
decrypted += str(message_segment)
#Generating the output
print("The message is : " + decrypted)
| true |
01b8ad6a04f071b0f5d3d7ada5b257cdf6848739 | binfyun/Run_setup_sheet_project | /ex1.py | 542 | 4.21875 | 4 | #!/usr/bin/python
def greetings(): # Define a function that print the desires words/sentences
print """
Hello David
Hello David and our world
Why am I doing this?
I must be going insane?
Must I keep doing this?"""
name = raw_input('Hi who am I speaking to? ') # Allowing use to input a name
while name != 'David':
name = raw_input('Hi who am I speaking to? ') # If name is not David then keep asking user for a name
greetings(); # Call the function greetings which containing sentences we want to display on the monitor
| true |
e736bd52dc1240ed87e4f038d78884c55a83360a | mreffatti/pands | /Week4/guess2.py | 471 | 4.125 | 4 | import random
num = random.randint(0,100)
guess = int(input("Guess a number between 0 and 100 (-1 to quit) "))
while guess != -1:
if guess == num:
print("You got it")
break
else:
if guess < num:
print("Too low - Please try a higher number")
else:
print("Too high - Please try a lower number")
guess = int(input("Guess a number between 0 and 100 (-1 to quit)"))
print(f"The number was {num}.") | true |
c4a6857421c09467db8e6d14f216cb08f054b141 | sbuckley02/python_programs | /ceasercipher.py | 1,591 | 4.21875 | 4 | '''
This program allows you to encipher or decipher messages using Ceaser's method. This method
involves shifting every letter by the key. For example, "a" shifted by the key of 2 would be
"c". Deciphering does the opposite ("c" becomes "a").
'''
def encipher(string,amount):
encoded = ''
for char in string:
def addToEncoded(min,max):
if ord(char) >= min and ord(char) <= max:
newOrd = ord(char)+(amount%26)
while newOrd < max:
newOrd+=26
if newOrd > max:
newOrd = newOrd%max+()
encoded+=chr(newOrd)
if ord(char) >= 65 and ord(char) <= 90:
newOrd = ord(char)+(amount%26)
while newOrd < 65:
newOrd+=26
if newOrd > 90:
newOrd = newOrd%90+64
encoded+=chr(newOrd)
elif ord(char) >= 97 and ord(char) <= 122:
newOrd = ord(char)+(amount%26)
while newOrd < 97:
newOrd+=26
if newOrd > 122:
newOrd = newOrd%122+96
encoded+=chr(newOrd)
else:
encoded+=char
return encoded
def decipher(string,amount):
return encipher(string,-amount)
mode = input('Would you like to encipher or decipher something? ').lower()
if mode == 'encipher':
print(encipher(input('Enter the message to encipher. '),int(input('Enter the key to encipher it with (an integer). '))))
else:
mode_two = input('Do you know the key? (YES or NO) ').lower()
if mode_two == 'yes':
print(decipher(input('Enter the message to decipher. '),int(input('Enter the key to attempt to decipher it with (an integer). '))))
else:
message = input('Enter the message to decipher. ')
for num in range(25):
print(f'{decipher(message,num+1)} (key = {num+1})') | true |
296de9e932bac5e105fc2f81ce18664beea50813 | sbuckley02/python_programs | /hotelroom.py | 1,286 | 4.125 | 4 | '''
I was in Europe with some people and I shared a room with three others. There were a few
sleeping options, and some were clearly better than others. To decide who would get their
preferred sleeping option, and in which order, I created this program.
How it worked: The program generated a random number between 1 and 10. We took turns guessing,
until someone got the number. Until the order was set, the program repeated this.
'''
#these you change
names = ['Buckley','Conor','Cregin','Chris']
firstnum = 1
lastnum = 10
#this you don't change
prefixes = ['first','second','third','fourth','fifth']
turn = 0
from random import randint
orderednames = []
end = len(names)-1
while end >= 0:
rand = randint(0,end)
orderednames.append(names[rand])
names.pop(rand)
end += -1
def update_turn():
global turn
if turn == len(orderednames)-1:
turn = 0
else:
turn += 1
def complete_round(prefix):
global orderednames
num = randint(firstnum,lastnum)
while True:
if int(input(f'{orderednames[turn]}, what is the {prefix} number? (between {firstnum} and {lastnum}) ')) != num:
print('WRONG')
else:
print(f'{orderednames[turn]}, you got it')
orderednames.pop(turn)
break
update_turn()
for n in range(len(orderednames)-1):
complete_round(prefixes[n])
turn = 0 | true |
9f74edc4842016cc101fafc00832de15e43dc940 | damump/Data-Science-Journey | /even_or_odd.py | 965 | 4.5 | 4 | ##Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.
##Hint: how does an even / odd number react differently when divided by 2?
##Extras:
#If the number is a multiple of 4, print out a different message.
#Ask the user for two numbers: one number to check (call it num) and one number to divide by (check).
# If check divides evenly into num, tell that to the user. If not, print a different appropriate message.
num1 = int(input("Enter the even or odd number\n"))
num2 = int(input("Whatchu wanna divide by???\n"))
if num1 %2 ==0:
print("this is an even number\n")
else:
print("nah this is not even\n")
if num1 %num2 == 0:
print("this is divisible by " + str(num2) + "\n")
else:
print("this is not divisible by " + str(num2) + "\n")
if num1 %4 == 0:
print(str(num1) + " Is a multiple of 4\n")
else:
print(str(num1) + " Is not a multiple of 4\n")
| true |
5ea09665f1028678dcde4f468c9b8d7b60e90c53 | phneutro73/Python | /ejercicio9.py | 247 | 4.1875 | 4 | '''
Ejercicio 9. Programa que pide un numero indefinidamente hasta que se introduce 111
'''
numero = 0
while numero != 111:
numero = int(input("Introduce un número: "))
else:
print (f"\nEnhorabuena el número {numero} es el correcto!\n") | false |
ede4c3770aa0fab1099f0a1cbacc5dfbfd43ad6d | nitinKumarInfy12/Python_material | /MyPyhton/Detailed_Study/Debuging/Exception.py | 1,224 | 4.21875 | 4 | #! python3
# functions would have raise Exception statements with some exception message
# code must have try-except block to handle the execution an dexception else the code will throw error
# you can obtain the exception as a string by calling traceback.format_exc()
# import builtins
# help (builtins) will give the list of available builtin exceptions
class CoffeeCup:
def __init__(self, temperature):
self.__temperature = temperature
def drink_coffee(self):
if self.__temperature > 85:
#print("Its too hot to drink")
raise Exception("Its too hot to drink")
elif self.__temperature < 65:
#print("Its too cold to drink")
raise Exception("Its too cold to drink")
else:
print("Its ok to drink")
try:
cup = CoffeeCup(87)
print(cup.drink_coffee())
except Exception as err:
print('An exception happened: ' + str(err))
# we can add Else and Finalle too to the try-except block
else: # else statement will not be executed whenever there is any exception
print ('__else__')
finally: # it is gu')ranteed to execute, dosent matter error occurs or not
print ('__finally__')
print("Program continued...") | true |
cf96345c837cf8d1d230685211623d8b68e3790a | nitinKumarInfy12/Python_material | /MyPyhton/SummaryCommands/Class_Init.py | 1,245 | 4.40625 | 4 | class Rectanggle:
#pass # to create an empty class
def __init__(self): # served as constructor of the class. it is teh first statement wil be called for any class/object
print('the __init__(self) is called')
###### Method
## for every method inside a class first argument must be self(or any keyword used as self) to initialize teh method
# select the rows and click on Ctrl + / to comment all teh selected rows
# rect1 = Rectanggle()
# rect2 = Rectanggle()
#
# rect1.height = 20
# rect1.width = 30
#
# rect2.height = 40
# rect2.width = 50
#
# print(rect1.height * rect1.width)
# print(rect2.height * rect2.width)
######################################################################
class car:
def __init__(self, color, speed):
self.color = color
self.speed = speed
#print(speed)
#print(color)
ford = car('Red',200) # object of teh car class
honda = car('Blue',220)
print(ford.color)
print(honda.speed)
################################################################################
class Square:
def __init__(abc, height, width):
abc.height = height
abc.width = width
print ("area of the Square :", abc.height * abc.width)
sqr1 = Square(20,22)
| true |
3ef29cd516c3d70c6292c86c6ce400133463d1d3 | nitinKumarInfy12/Python_material | /MyPyhton/SummaryCommands/escape_character.py | 900 | 4.40625 | 4 | # '\' is the escape charatcter
# r'' is the raw string notation to python
#Typing r'\d\d\d-\d\d\d-\d\d\d\d' is much easier than typing '\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d'
"""
Remember that escape characters in Python use the backslash (\). The string value '\n' represents a single newline
character, not a backslash followed by a lowercase n. You need to enter the escape character \\ to print a single
backslash. So '\\n' is the string that represents a backslash followed by a lowercase n. However, by putting an r
before the first quote of the string value, you can mark the string as a raw string, which does not escape characters.
Since regular expressions frequently use backslashes in them, it is convenient to pass raw strings to the re.compile()
function instead of typing extra backslashes. Typing r'\d\d\d-\d\d\d-\d\d\d\d' is much easier than typing
'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d'. """ | true |
e748a65eae13a99d94a3f78eac86d9d1e0993e62 | nitinKumarInfy12/Python_material | /MyPyhton/SummaryCommands/Decorators.py | 1,697 | 4.71875 | 5 | # decorators wrap a function and modify its behaviour without changing the source code of the function
def decorator_func(func):
def wrapper_func():
print('X' * 20)
func()
print('x' * 10)
return wrapper_func # example of closure
'''
def say_hello():
print('Hellow world')
hello = decorator_func(say_hello)
hello()
# this both line of declaing decorator can be replaced with onle line above teh function thas has to be decorated '@decorator_func'
'''
#hello = decorator_func(say_hello)
#hello()
@decorator_func
def say_hello():
print('Hello world')
say_hello()
# multiple decorators can also be used with onefunction
print("==================================multiple decorators==================")
def decorator_x(func):
def wrapper_func():
print('X' * 20)
func()
print('x' * 10)
return wrapper_func # example of closure
def decorator_y(func):
def wrapper_func():
print('y' * 20)
func()
print('y' * 10)
return wrapper_func # example of closure
@decorator_y
@decorator_x
def say_hello():
print('Hellow world')
# call th function
say_hello()
print( 'or the the notation of declaring decorators')
helloDec = decorator_x(decorator_y(say_hello)) #comment the @decorator_y and @decorator_x before executing this line
helloDec()
print('=============another example==========')
def decorator_div(func):
def wraper_func(x,y):
if (y==0):
print('division with 0 is not allowed')
return 0
return func(x,y)
return wraper_func
@decorator_div
def divideFun(x,y):
return x / y
print(divideFun(15,3))
print(divideFun(15,0))
| true |
8f52271ca2b76c543ffc0a5c99235551795d8362 | ArondevIta/curso-python | /lista.py | 1,040 | 4.15625 | 4 | secreto = 'perfume'
digitados = []
chances = 3
while True:
if chances <= 0:
print('Você perdeu :(')
break
letra = input('Digite uma letra: ')
if len(letra) > 1:
print('Opa, você não pode digitar mais de uma letra...')
continue
digitados.append(letra)
if letra in secreto:
print(f'ISSO AÍÍÍÍ: a letra "{letra}" existes na palavra secreta')
else:
print(f'OOPS: a letra "{letra}" não existre na palavra secreta')
digitados.pop()
secreto_temporario = ''
for letra_secreta in secreto:
if letra_secreta in digitados:
secreto_temporario += letra_secreta
else:
secreto_temporario += '*'
if secreto_temporario == secreto:
print(f'Muito bem, você ganhouuu!!! A palavra era {secreto_temporario}.')
break
else:
print(f'A palavra secreta está assim: {secreto_temporario}')
if letra not in secreto:
chances -= 1
print(f'Você ainda tem {chances} chances.')
| false |
05cdc96e83480a0d75513dbd02429fc164905ab0 | RogerMCL/PythonExercises | /Ex018.py | 288 | 4.15625 | 4 | #EXERCÍCIO 018:
from math import sin, cos, tan, radians
ang = float(input('Informe o ângulo em graus: '))
rad = radians(ang)
print(f'\nsen({ang}) = {sin(rad):.2f}') #radians(x) - converte rad em graus
print(f'cos({ang}) = {cos(rad):.2f}')
print(f'tan({ang}) = {tan(rad):.2f}')
| false |
98cbdb0ffdb6748427256d7554c4b3dbb79fff98 | elias-santos87/Exercicios | /Exercicio 2.py | 359 | 4.1875 | 4 | # Exercício 2
# Faça um programa que solicite um número do usuário e apresente a seguinte mensagem na tela:
# "O número digitado foi [número]".
# Solução 1
num = input('Digite o número: ')
print(f'O número digitado foi {num}')
# solução 2
num = float(input('Digite um número: '))
print(f'O numero digitado foi {num} ')
| false |
6f9f60190dff3bc1f7416e8a0f3fed7609a7cf3a | cinhori/LeetCode | /python_src/merge_two_sorted_lists.py | 1,581 | 4.125 | 4 | # 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
#
# 示例:
# 输入:1->2->4, 1->3->4
# 输出:1->1->2->3->4->4
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 48ms, 51.09%; 13.8MB, 7.14%
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
# 52ms, 30.48%; 13.7MB, 7.14%
def mergeTwoLists2(self, l1, l2):
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
# 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev.next = l1 if l1 is not None else l2
return prehead.next
if __name__ == "__main__":
l1 = ListNode(1)
l1.next=ListNode(2)
l1.next.next=ListNode(4)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
res = Solution().mergeTwoLists2(l1, l2)
while res is not None:
print(res.val)
res = res.next
| false |
4c410d822a91d9e882d723a4fa83588a6e0c33fd | exw/rosalind | /src/03FIB.py | 2,183 | 4.40625 | 4 | # Rabbits and Recurrence Relations
# Problem
# A sequence is an ordered collection of objects (usually numbers), which are allowed to repeat. Sequences can be finite or infinite. Two examples are the finite sequence (π,−2 √ ,0,π) and the infinite sequence of odd numbers (1,3,5,7,9,…) . We use the notation a n to represent the n -th term of a sequence.
# A recurrence relation is a way of defining the terms of a sequence with respect to the values of previous terms. In the case of Fibonacci's rabbits from the introduction, any given month will contain the rabbits that were alive the previous month, plus any new offspring. A key observation is that the number of offspring in any month is equal to the number of rabbits that were alive two months prior. As a result, if F n represents the number of rabbit pairs alive after the n -th month, then we obtain the Fibonacci sequence having terms F n that are defined by the recurrence relation F n =F n−1 +F n−2 (with F 1 =F 2 =1 to initiate the sequence). Although the sequence bears Fibonacci's name, it was known to Indian mathematicians over two millennia ago.
# When finding the n -th term of a sequence defined by a recurrence relation, we can simply use the recurrence relation to generate terms for progressively larger values of n . This problem introduces us to the computational technique of dynamic programming, which successively builds up solutions by using the answers to smaller cases.
# Given: Positive integers n≤40 and k≤5 .
# Return: The total number of rabbit pairs that will be present after n months if we begin with 1 pair and in each generation, every pair of reproduction-age rabbits produces a litter of k rabbit pairs (instead of only 1 pair).
import sys
# Get parameters from stdin
text = sys.stdin.readline().strip('\n')
args = text.split(' ')
months = int(args[0])
rate = int(args[1])
# Initalize number of rabbits
progeny = 1
# Initialize dictionary for number of rabbits in each generation
generation = dict()
# Evaluate recurrence relation
for i in range(months):
progeny = progeny + rate * generation.get(i-2,0)
generation[i] = progeny
print progeny
| true |
d3e0a8fe323e9c5ec881bb3be2643a24e6bfcc69 | BAmercury/DSP_Bioinformatics | /inclass_assignment_4.py | 1,927 | 4.15625 | 4 | # ECES T580 In Class Assignment 3
# Bhautik (Brian) Amin
# Program was built for Python 2.7
# Provides Fucntions and Class to generate trees
class TreeNode:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
def TreeGenerator(A):
if A is None or len(A) == 0:
return None
mid = len(A) // 2
root = TreeNode(A[mid])
root.left = TreeGenerator(A[:mid])
root.right = TreeGenerator(A[mid+1:])
return root
# Given a constructed binary tree, traverse and return values in a python list from lowest to highest
def TreeTraverser(root):
# Get topmost node of binary tree
current = root
in_order = [] # Python list to store values in order
temp = [] # Temporary list
running = True
while (running):
# Run to the leftmost node from the current node
if current is not None:
temp.append(current) # Append current node value
current = current.left # Move to left node
else: # If we are at left most, backtrack
if (len(temp) > 0): # Check if empty
current = temp.pop() # Pull out the left most node
print(current.val) # Print the value of this node, and append to in_order python list
in_order.append(current.val)
current = current.right # Now move to right
else:
running = False # We have finished navigating the binary tree
if (len(temp) < 0): # If stack is empty
running = False
return in_order
root = TreeGenerator([1,2,3,4,5,6,7]) # Generate the tree
in_order = TreeTraverser(root) # Traverse
print(in_order)
""" OUTPUT:
1
2
3
4
5
6
7
[1, 2, 3, 4, 5, 6, 7]
"""
root = TreeGenerator([2,3,4,5,6,7,9]) # Generate the tree
in_order = TreeTraverser(root) # Traverse
print(in_order)
""" OUTPUT:
2
3
4
5
6
7
9
[2, 3, 4, 5, 6, 7, 9]
""" | true |
4f5095e0a89ccaa33cd612b969bdc387f42416a4 | lizhenggan/TwentyFour | /01_Language/05_Python/study/lesson_04/09.元组.py | 1,757 | 4.375 | 4 | # 元组 tuple
# 元组是一个不可变的序列
# 它的操作的方式基本上和列表是一致的
# 所以你在操作元组时,就把元组当成是一个不可变的列表就ok了
# 一般当我们希望数据不改变时,就使用元组,其余情况都使用列表
# 创建元组
# 使用()来创建元组
my_tuple = () # 创建了一个空元组
# print(my_tuple,type(my_tuple)) # <class 'tuple'>
my_tuple = (1, 2, 3, 4, 5) # 创建了一个5个元素的元组
# 元组是不可变对象,不能尝试为元组中的元素重新赋值
# my_tuple[3] = 10 TypeError: 'tuple' object does not support item assignment
# print(my_tuple[3])
# 当元组不是空元组时,括号可以省略
# 如果元组不是空元组,它里边至少要有一个,
my_tuple = 10, 20, 30, 40
my_tuple = 40,
# print(my_tuple , type(my_tuple))
my_tuple = 10, 20, 30, 40
# 元组的解包(解构)
# 解包指就是将元组当中每一个元素都赋值给一个变量
a, b, c, d = my_tuple
# print("a =",a)
# print("b =",b)
# print("c =",c)
# print("d =",d)
a = 100
b = 300
# print(a , b)
# 交互a 和 b的值,这时我们就可以利用元组的解包
a, b = b, a
# print(a , b)
my_tuple = 10, 20, 30, 40
# 在对一个元组进行解包时,变量的数量必须和元组中的元素的数量一致
# 也可以在变量前边添加一个*,这样变量将会获取元组中所有剩余的元素
a, b, *c = my_tuple
a, *b, c = my_tuple
*a, b, c = my_tuple
a, b, *c = [1, 2, 3, 4, 5, 6, 7]
a, b, *c = 'hello world'
# 不能同时出现两个或以上的*变量
# *a , *b , c = my_tuple SyntaxError: two starred expressions in assignment
print('a =', a)
print('b =', b)
print('c =', c)
| false |
b19ed4f19739e4502e4360899422ecdd0c098a52 | crisuvas/Aprender | /insert_sql.py | 582 | 4.125 | 4 | import sqlite3
def insert():
db1 = sqlite3.connect('books.db')
print("You are in the insert function")
name1 = str(input("Write the title of your novel\n"))
author1 = str(input("Write the author of the novel\n"))
year1 = str(input("Write the year of the novel\n"))
consult = db1.cursor()
str_consult = "INSERT INTO books(name, author, year) VALUES" \
"('"+name1+"','"+author1+"',"+year1+");"
print(str_consult)
consult.execute(str_consult)
consult.close()
db1.commit()
db1.close()
insert()
| true |
1329db42e63325f5aea4da259999c851f41175a0 | Nehal31/Python | /PProgramz/pz5.py | 529 | 4.125 | 4 | ''' Swap two varivale using temp variable '''
''' Swap two varivale without using temp variable '''
a = input('Enter the value of a : ')
b = input('Enter the value of b : ')
print('Given value of a = {0} and b ={1}'.format(a,b))
#swap using temp variable:
t = a
a = b
b = t
print('swap using temp variable:')
print('Changed value of a = {0} and b ={1}'.format(a,b))
#swap without temp variable:
print('swaping without temp variable:')
a,b = b,a
print('Changed value of a = {0} and b ={1} '.format(a,b))
| false |
e983a61fc61ac6bfee80e62a90b559ce62ba3a25 | Nehal31/Python | /PProgramz/pz27.py | 248 | 4.15625 | 4 | ''' display the calander of given month '''
import calendar
#take the year
yy = int(input('Enter the year YYYY : '))
#take the month
mm = int(input('Enter the month MM : '))
#print the month
print(calendar.month(yy,mm))
| false |
28ce74a8dc9ebc2b19c4e45d1913b1c17ab86ed9 | Nehal31/Python | /HeadFirst2e/Chapter1/random.py | 767 | 4.1875 | 4 | """
This code repeatedly check the time at random time interval
'datetime' module contains 'datetime' submodule which gives today's time
using 'today()' built in function
'random' module contains 'randrange(int)' function which return a random
integer of that range excluding last number
'time module' provides 'sleep()' funtion whose parameter are seconds
"""
from datetime import datetime
import random
import time
odds = [i for i in range(1,60,2)]
for i in range(10):
current_minutes = datetime.today().minute
if current_minutes in odds:
print("Minutes are odd")
else :
print("Minutes are not odd")
# random number generation
rand_int = random.randint(1,60)
time.sleep(rand_int)
| true |
da77e7aafacd0ea728ee7f8766111834bceff017 | Nehal31/Python | /HeadFirst2e/Chapter4/vowels7.py | 208 | 4.1875 | 4 | '''
the code uses the set() to find the vowels in the input sequence
'''
vowels = set('aeiou')
value = input("Enter the String")
i = vowels.intersection(set(value))
for v in sorted(i):
print(v)
| true |
393a044f612e959a108b2bce36929870179c17d1 | kouyx/Coding-challenge | /Leetcode/merge-two-sorted-lists.py | 977 | 4.15625 | 4 | """
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 or not l2:
return l1 or l2
head = z = ListNode(None)
while l1 and l2:
if l1.val > l2.val:
z.next = l2
l2 = l2.next
else:
z.next = l1
l1 = l1.next
z = z.next
z.next = l1 or l2
return head.next
if __name__ == "__main__":
a = None
b = None
c = a or b
print(c)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.