blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
23a78d6732247649e4996df5839718f6987e7a4b | ShuLingLai/Firstproject | /5pdf.py | 2,133 | 4.34375 | 4 | #函式
def add_x_and_y(x, y):
pass #這個函式先不做事情
# --------------------------------------------------------------
def add_x_and_y1(x, y):
"""
add x and y1 and return sum
:param x: eg.10
:param y: eg.7
:return: x+y
"""
sum1 = x + y
return sum1
a = 10
b = 7
a_b = add_x_and_y1(a, b)
print(a_b)
#函式的功用
c = 5
d = 20
c_d = add_x_and_y1(c, d)
print(c_d)
#--------------------------------------------------------------
#預設值
def add_x_and_y2(x, y=15):
"""
add x and y2 and return sum
:param x: eg.7
:param y: eg.15
:return: x+y
"""
sum2 = x + y
return sum2
c = 7
c_ = add_x_and_y2(c)
print(c_)
#--------------------------------------------------------------
#變動數量量的參參數個數
def add_x_and_y3(x, *y): #第二個之後的被歸納為y
"""
add x and y3 and return sum
:param x:
:param y:
:return: x+y
"""
sum3 = x + sum(y) #sum(y)為保留字 ,為y的總和
return sum3
a = 10 #等於x
b = 6
c = 8
d = 5
e = 9
a_e = add_x_and_y3(a, b, c, d, e)
print(a_e)
a_e_20 = add_x_and_y3(a, b, c, d, e,20)
print(a_e_20)
#--------------------------------------------------------------
def add_x_and_y_return_multi_value(x, y):
sum_num = x + y
avg = sum_num/2
return sum_num, avg
f = 5
g = 20
f_g = add_x_and_y_return_multi_value(f, g)
print(f_g)
f_g_sum, f_g_avg1 = add_x_and_y_return_multi_value(f, g)
print(f_g_sum)
print(f_g_avg1)
#--------------------------------------------------------------
#匿名函式
#從list中過濾出奇數
ls = [5, 9, 6, 4, 56, 478, 78, 91]
def is_odd(x):
return x % 2 == 1 #挑出奇數
#result = list(filter(is_odd, ls)) #怎麼過濾,過濾什麼
result = list(filter(lambda x: x % 2 == 1, ls)) #函式只用到一次,把它隱藏在裡面
print(result)
#--------------------------------------------------------------
#模組
def get_weather_observe():
return 'weather_observe'
def get_weather_forecast():
return 'weather_forecast'
import WeatherService as WeatherService | false |
446598af9a2c72219e915db9fe01437fc8fc9d7e | shantinavgurukul/loop_question | /odd_even.py | 383 | 4.125 | 4 | num=int(input("enter the number="))
while(num<=10):
if(num%2==0):
print("even num",num)
else:
print("odd num",num)
num=num+1
# num=1
# number=int(input("enter the number = "))
# while(num<=number):
# if(num%10==2):
# if(num%2==0):
# print(num,"even number")
# else:
# print(num,"odd number")
# num=num+1 | false |
17094896a237ce2d5f4cc2e0a3b770058f187bcb | fatihtkale/Term-Todo | /script.py | 1,174 | 4.15625 | 4 | import sqlite3
conn = sqlite3.connect('db.db')
query = conn.cursor()
def run_program():
def get_info():
query = conn.cursor()
query.execute("SELECT * FROM Information")
rows = query.fetchall()
for row in rows:
print(row)
run_program()
def save_info(value):
query.execute("INSERT INTO information (info) values ('"+value+"')")
conn.commit()
run_program()
def delete_info(value):
query.execute("DELETE FROM information WHERE info=?", (value,))
conn.commit()
run_program()
print("Choose one of the options listed below")
print("[S]ave for saving a information | [D]elete | [L]ist all the information | [Q]uit the program")
choice = input()
if choice.lower() == "s":
print("Type a piece of information you want to save.")
val = input()
save_info(val)
elif choice.lower() == "d":
print("Type the data you want to remove")
val = input()
delete_info(val)
elif choice.lower() == "l":
get_info()
elif choice.lower() == "q":
conn.close()
return 0
run_program() | true |
8ff6e4d16550bff45f3c2e75d17f18cd1640adb1 | mvg2/astr-119-hw-2 | /variables_and_loops.py | 771 | 4.15625 | 4 | import numpy as np # imports the numpy module
def main():
i = 0 # assign integer value 0 to variable i
n = 10 # assign integer value 10 to variable n
x = 119.0 # assign float value 119.0 to variable x
# we can use numpy to declare arrays quickly
y = np.zeros(n, dtype=float) # declares 10 zeroes (referenced by variable n)
# we can use for loops to iterate with a variable
for i in range(n): # runs the loop 10 times
y[i] = 2.0 * float(i) + 1. # set y = 2i + 1 as floats
# we can also simply iterate through a variable
for y_element in y:
print(y_element)
# execute the main function
if __name__ == "__main__":
main()
| true |
cbaf511f13d0d0b892ea3a11a7b57f3bde24076e | maryjo6384/gitdemo | /dictreverse.py | 750 | 4.25 | 4 | #program to reverse the key and value in the dictionary
#pls review
dict ={"a":"!","b":"@","c":"#","d":"$","e":"5","f":"^","g":"&","h":"*","i":"(","j":"!)","k":"!@","l":"!#","m":"!$",
"n":"!%","o":"!^","p":"!&","q":"!*","r":"!(","s":"!)","t":"@@","u":"@#","v":"@%","w":"^y","x":"@^","y":"@&","z":"@("}
rev_dict= {}
def reverse():
list_keys = list(dict.keys())
list_val = list(dict.values())
for i in range(0, len(list_val)):
value = list_keys[i]
key = list_val[i]
rev_dict[key] = value
def find_key_value(str):
if str in dict:
return dict[str]
else:
reverse()
return rev_dict[str]
val = input("Enter the key/value to be found:")
print(find_key_value(val))
print(rev_dict)
| false |
157c530a6a6f8d7bc729cbf6c1b945b3bdd83507 | Moosedemeanor/learn-python-3-the-hard-way | /ex03.py | 1,195 | 4.625 | 5 | # + plus
# - minus
# / slash
# * asterisk
# % percent
# < less-than
# > greater-than
# <= less-than-equal
# >= greater-than-equal
# print string text question
print("I will now count my chickens:")
# print Hens string then perform calculation
print("Hens", 25 + 30 / 6)
# print Roosters string then perform calculation
print("Roosters", 100 - 25 * 3 % 4)
# print string statement
print("Now I will count the eggs:")
# print the result of the calculation
# PEMDAS - Parentheses Exponents Multiplication Division Addition Subtraction
print(3 + 2 + 1 - 5 + 4 % 2 - 1.00 / 4 + 6)
# print string question
print("Is it true that 3 + 2 < 5 -7?")
# perform the actual calculation
print(3 + 2 < 5 -7)
# print string question, perform addition
print("What is 3 + 2?", 3 + 2)
# print string question, perform subtraction
print("What is 5 - 7?", 5 - 7)
# print string question
print("Oh, that's what it's False.")
# print string question
print("How about some more.")
# print string, perform boolean operation
print("Is it greater?", 5 > -2 )
# print string, perform boolean operation
print("Is is greater or equal?", 5 >= -2)
# print string, perform boolean operation
print("Is it less or equal?", 5 <= -2) | true |
75888241e7d1af247414e9cdb72a2a2e9ebf70f3 | theodorp/CodeEval_Easy | /ageDistribution.py | 1,798 | 4.40625 | 4 | # AGE DISTRIBUTION
# CHALLENGE DESCRIPTION:
# You're responsible for providing a demographic report for your local school district based on age. To do this, you're going determine which 'category' each person fits into based on their age.
# The person's age will determine which category they should be in:
# If they're from 0 to 2 the child should be with parents print : 'Still in Mama's arms'
# If they're 3 or 4 and should be in preschool print : 'Preschool Maniac'
# If they're from 5 to 11 and should be in elementary school print : 'Elementary school'
# From 12 to 14: 'Middle school'
# From 15 to 18: 'High school'
# From 19 to 22: 'College'
# From 23 to 65: 'Working for the man'
# From 66 to 100: 'The Golden Years'
# If the age of the person less than 0 or more than 100 - it might be an alien - print: "This program is for humans"
# INPUT SAMPLE:
# Your program should accept as its first argument a path to a filename. Each line of input contains one integer - age of the person:
# 0
# 19
# OUTPUT SAMPLE:
# For each line of input print out where the person is:
# Still in Mama's arms
# College
################################
def ageDistribution(test):
age = int(test.strip())
if age < 0 or age > 100:
return('This program is for humans')
elif age in range(0,2):
return("Still in Mama's arms")
elif age in range(3,4):
return("Preschool Maniac")
elif age in range(5,11):
return('Elementary school')
elif age in range(12,14):
return('Middle school')
elif age in range(15,18):
return('High school')
elif age in range(19,22):
return('College')
elif age in range(23,65):
return('Working for the man')
elif age in range(66,100):
return('The Golden Years')
file = open("ageDistribution.txt", "r")
for test in file:
print(ageDistribution(test)) | true |
bb889189b4f6ed0e6e0119fa5f2612904fa95921 | theodorp/CodeEval_Easy | /swapCase.py | 645 | 4.25 | 4 | # SWAP CASE
# CHALLENGE DESCRIPTION:
# Write a program which swaps letters' case in a sentence. All non-letter characters should remain the same.
# INPUT SAMPLE:
# Your program should accept as its first argument a path to a filename. Input example is the following
# Hello world!
# JavaScript language 1.8
# A letter
# OUTPUT SAMPLE:
# Print results in the following way.
# hELLO WORLD!
# jAVAsCRIPT LANGUAGE 1.8
# a LETTER
def swapCase(filename):
f = open(filename,'r')
for test in f:
test = test.strip()
t2 = ''.join([i.lower() if i.isupper() else i.upper() for i in test])
print(t2)
f.close()
swapCase('swapCase.txt') | true |
e32d4c0ff6b060534d93f0d05d181de0bb6785d4 | theodorp/CodeEval_Easy | /happyNumbers.py | 1,204 | 4.25 | 4 | # HAPPY NUMBERS
# CHALLENGE DESCRIPTION:
# A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers.
# INPUT SAMPLE:
# The first argument is the pathname to a file which contains test data, one test case per line. Each line contains a positive integer. E.g.
# 1
# 7
# 22
# OUTPUT SAMPLE:
# If the number is a happy number, print out 1. If not, print out 0. E.g
# 1
# 1
# 0
# For the curious, here's why 7 is a happy number: 7->49->97->130->10->1.
# Here's why 22 is NOT a happy number: 22->8->64->52->29->85->89->145->42->20->4->16->37->58->89 ...
def happy(n):
past = set()
while n != 1:
n = sum(int(i)**2 for i in str(n))
if n in past:
return (0)
past.add(n)
return (1)
def happyNumbers(filename):
f = open(filename, 'r')
for test in f:
t = test.strip()
print(happy(int(t)))
# print(happy(7))
happyNumbers('happyNumbers.txt')
| true |
fe8869fcc3952b4c795d5f4723d578c234e93b8d | theodorp/CodeEval_Easy | /majorElement.py | 1,138 | 4.15625 | 4 | # THE MAJOR ELEMENT
# CHALLENGE DESCRIPTION:
# The major element in a sequence with the length of L is the element which appears in a sequence more than L/2 times. The challenge is to find that element in a sequence.
# INPUT SAMPLE:
# Your program should accept as its first argument a path to a filename. Each line of the file contains a sequence of integers N separated by comma. E.g.
# 92,19,19,76,19,21,19,85,19,19,19,94,19,19,22,67,83,19,19,54,59,1,19,19
# 92,11,30,92,1,11,92,38,92,92,43,92,92,51,92,36,97,92,92,92,43,22,84,92,92
# 4,79,89,98,48,42,39,79,55,70,21,39,98,16,96,2,10,24,14,47,0,50,95,20,95,48,50,12,42
# OUTPUT SAMPLE:
# For each sequence print out the major element or print "None" in case there is no such element. E.g.
# 19
# 92
# None
# Constraints:
# N is in range [0, 100]
# L is in range [10000, 30000]
# The number of test cases <= 40
def majorElement(test):
from collections import Counter
line = test.strip().split(',')
c = Counter(line).most_common(1)
x,y = c[0]
return (x if y > len(line)/2 else 'None')
file = open("majorElement.txt", "r")
for test in file:
print(majorElement(test)) | true |
2c991f2a5e7da455ff2fcecc75ec4d7368e2af72 | theodorp/CodeEval_Easy | /lowerCase.py | 588 | 4.3125 | 4 | # LOWERCASE
# CHALLENGE DESCRIPTION:
# Given a string write a program to convert it into lowercase.
# INPUT SAMPLE:
# The first argument will be a path to a filename containing sentences, one per line. You can assume all characters are from the english language. E.g.
# HELLO CODEEVAL
# This is some text
# OUTPUT SAMPLE:
# Print to stdout, the lowercase version of the sentence, each on a new line. E.g.
# hello codeeval
# this is some text
def lowerCase(filepath):
f = open(filepath, "r")
for line in f:
print(line.lower().strip())
f.close()
lowerCase("lowerCase.txt") | true |
bc608d508ceb1236e5f6d020d216af56e751434c | theodorp/CodeEval_Easy | /mixedContent.py | 1,038 | 4.15625 | 4 | # MIXED CONTENT
# CHALLENGE DESCRIPTION:
# You have a string of words and digits divided by comma. Write a program
# which separates words with digits. You shouldn't change the order elements.
# INPUT SAMPLE:
# Your program should accept as its first argument a path to a filename. Input
# example is the following
# 8,33,21,0,16,50,37,0,melon,7,apricot,peach,pineapple,17,21
# 24,13,14,43,41
# OUTPUT SAMPLE:
# melon,apricot,peach,pineapple|8,33,21,0,16,50,37,0,7,17,21
# 24,13,14,43,41
def mixedContent(test):
line = test.strip().split(',')
numbers = []
words = []
for i in line:
try:
numbers.append(int(i))
except ValueError:
words.append(i)
pass
return(words, numbers)
test_cases = open('mixedContent.txt','r')
for test in test_cases:
words, numbers = mixedContent(test)
if len(words) and len(numbers) > 0:
print(','.join(words) + "|" + ','.join(map(str, numbers)))
elif len(words) == 0:
print(','.join(map(str, numbers)))
elif len(numbers) == 0:
print(','.join(words))
test_cases.close() | true |
05b9dbed2d6c37958599957c9a05b177f3b08b73 | jbhennes/CSCI-220-Programming-1 | /Chapter 7 Decisions/LetterGrade.py | 507 | 4.15625 | 4 | ## LetterGrade.py
def main():
print ("Given a numerical grade, returns the letter grade.")
# Get the numerical grade
grade = input("Enter your numerical grade: ")
if grade >= 90:
print ("Letter grade = A")
elif grade < 90 and grade >= 80:
print ("Letter grade = B")
elif grade < 80 and grade >= 70:
print ("Letter grade = C")
elif grade < 70 and grade >= 60:
print ("Letter grade = D")
else:
print ("Letter grade = F")
main()
| true |
28e47d7fd4572ff14512a9e86541cfeb8ee0e848 | jbhennes/CSCI-220-Programming-1 | /rectArea.py | 1,039 | 4.25 | 4 | #This function calculates the area of a rectangle.
def rectArea():
#Purpose of the program.
print("This program calculates the area of a rectangle.")
units = input("First, tell me the units that will be used: ")
#Define variables
length = eval(input("Please input the length of the rectangle: "))
width = eval(input("Please input the width of the rectangle: "))
#Perform the calculation.
area = length * width
print("The area of the rectangle is", area, units, "squared.")
#Restart command.
restart = int(input("Would you like to restart? (1 = Yes / 0 = No): "))
if restart == (1):
rectArea()
elif restart == (0):
print("Gsme Over")
elif restart < (0) or > (1):
print("Funny. Try again.")
restart = int(input("( Yes = 1 / No = 0): "))
if restart == (1):
rectArea()
elif restart == (0):
print("Game Over")
elif restart < (0) or > (1):
print("Fine, have it your way.")
rectArea()
| true |
4c114ee054f6bca751ac665fb7fce7a63dcf6f1c | jbhennes/CSCI-220-Programming-1 | /Chapter 11 - lists/partialListFunctions.py | 1,967 | 4.375 | 4 | # listFunctions.py
# Author: Pharr
# Program to implement the list operations count and reverse.
from math import sqrt
def getElements():
list = [] # start with an empty list
# sentinel loop to get elements
item = raw_input("Enter an element (<Enter> to quit) >> ")
while item != "":
list.append(item) # add this value to the list
item = raw_input("Enter an element (<Enter> to quit) >> ")
return list
# count(list, x) counts the number of times that x occurs in list
def count(list, x):
num = 0
for item in list:
if item == x:
num = num + 1
return num
# isinBad(list, x) returns whether x occurs in list
# This is bad because it is inefficient.
def isinBad(list, x):
occurs = False
for item in list:
if item == x:
occurs = True
return occurs
# isin(list, x) returns whether x occurs in list
# This is better because it is more efficient.
def isin(list, x):
return False
# reverse(list) reverses the list
# This function destructively modifies the list.
# It would be easier to write if it just returned the reversed list!
def reverse(list):
print "Your code will reverse the list in place"
def main():
print 'This program reads a list, counts the number of elements,'
print 'and reverses the list.'
data = getElements()
item = raw_input("Enter element you want to count in the list: ")
theCount = count(data, item)
print "\nTnere are", theCount, "occurrences of", item, "in", data
item = raw_input("\nEnter element that should occur in the list: ")
occurs = isinBad(data, item)
if occurs:
print item, "occurs in", data
else:
print item, "does not occur in", data
occurs = isin(data, item)
if occurs:
print item, "occurs in", data
else:
print item, "does not occur in", data
reverse(data)
print "\nTne reversed list is", data
main()
| true |
913c3d0fafc5017bc72172796e8b2c793d190c61 | jbhennes/CSCI-220-Programming-1 | /Chapter 7 Decisions/MaxOfThree3.py | 729 | 4.46875 | 4 | ## MaxOfThree3.py
## Finds largest of three user-specified numbers
def main():
x1 = eval(input("Enter a number: "))
x2 = eval(input("Enter a number: "))
if x1 > x2:
temp = x1
x1 = x2
x2 = temp
print ("here")
print ("The numbers in sorted order are: ")
print (str(x1) + " " + str(x2))
## x3 = eval(input("Enter a number: "))
##
## # Determine which number is the largest
##
## max = x1 # Is x1 the largest?
## if x2 > max:
## max = x2 # Maybe x2 is the largest.
## if x3 > max:
## max = x3 # No, x3 is the largest.
##
## # display result
## print ("\nLargest number is", max)
main()
| true |
e97f890f65d8e44456af6118610c52f96d0e82ab | jbhennes/CSCI-220-Programming-1 | /Chapter 7 Decisions/MaxOfThree1.py | 508 | 4.53125 | 5 | ## MaxOfThree1.py
## Finds largest of three user-specified numbers
def main():
x1 = input("Enter a number: ")
x2 = input("Enter a number: ")
x3 = input("Enter a number: ")
# Determine which number is the largest
if x1 >= x2 and x1 >= x3: # x1 is largest
max = x1
elif x2 >= x1 and x2 >= x3: # x2 is largest
max = x2
else: # x3 is largest
max = x3
# display result
print "\nLargest number is", max
main()
| true |
2f6867f9b3569cfddafea7b46bf11ad254713d75 | jbhennes/CSCI-220-Programming-1 | /Chapter 8 While/GoodInput5.py | 493 | 4.28125 | 4 | ## GoodInput5.py
# This program asks the user to enter exactly 12 or 57.
# This version is WRONG!!!!!!
def main():
number = input("Enter the number 12 or 57: ")
# This version tries to move the negation in, but incorrectly,
# thus creating an infinite loop:
while number != 12 or number != 57:
print "That number was not the requested value.\n"
number = input("Enter the number 12 or 57: ")
print "Thank you for entering", number
main()
| true |
835df901f9c9ababa430f2314a3a608503a51894 | Matt-McConway/Python-Crash-Course-Working | /Chapter 6 - Dictionaries/ex6-11_pp115_cities.py | 542 | 4.15625 | 4 | """
"""
cities = {"Auckland": {"Country": "New Zealand", "population": 1300000,
"fact": "Originally the capital"},
"Wellington": {"Country": "New Zealand", "population": 300000,
"fact": "Currently the capital"},
"Dunedin": {"Country": "New Zealand", "population": 120000,
"fact": "Largest city in Otago"}
}
for city, fact in cities.items():
print(city + ":")
for key, value in fact.items():
print(key + ": " + str(value))
print("\n")
| false |
1ef289b88e2cf959f9e0f533df0ccfa180605154 | Matt-McConway/Python-Crash-Course-Working | /Chapter 7 - User Input and While Loops/ex7-2_pp121_restaurantSeating.py | 216 | 4.15625 | 4 | """
"""
toBeSeated = input("How many people are dining tonight? ")
if int(toBeSeated) > 8:
print("I'm sorry, you are going to have to wait for a table.")
else:
print("Right this way, your table is ready.")
| true |
72cdb814f466e26f8b799db19b4a06b69570076f | chetanpawar19/Python-Scripts | /PasswordGenerator.py | 1,103 | 4.25 | 4 | """
the script allows you to generate random password based on your choice of length, password combination.
requirements-
python 3 (any version)
random module of python in-built
author -chetan pawar
version- v1.0.1
"""
import random
digits_choice='0123456789'
alpha_uppercase_choice='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
alpha_lowercase_choice='abcdefghijklmnopqrstuvwxyz'
special_char_choice='!@#$%^&*()'
no_of_passwords = int(input("how many passwords do you want?"))
digits=int(input('How many digits:'))
alpha_uppercase=int(input('How many uppercase chars:'))
alpha_lowercase=int(input('How many lower case chars:'))
special_char=int(input('How many special chars:'))
combination_dict={digits_choice:digits,alpha_uppercase_choice:alpha_uppercase,alpha_lowercase_choice:alpha_lowercase,special_char_choice:special_char}
for i in range(no_of_passwords):
password=''
l=[]
for key,value in combination_dict.items():
for i in range(0,int(value)):
password=password+random.choice(str(key))
l =list(password)
random.shuffle(l)
print('Password for you:',(''.join(l)))
| false |
45142c33c0203fe1bc2386bb7b53e0fb919f5b27 | Gutencode/python-programs | /conditionals/gradePercent.py | 829 | 4.3125 | 4 | ## Program to compute the grade from given percentage.
def grade(percent):
""" This function takes the percentage as input and returns the relevant grade. """
if (percent > 100):
print("Please enter the correct obtained percentage")
elif (percent >= 90):
return("A")
elif (percent >= 80):
return("B")
elif (percent >= 70):
return("C")
elif (percent >= 60):
return("D")
elif (percent >= 50):
return("E")
elif (percent >= 40):
return("F")
elif (percent >= 30):
return("G")
else:
return("Fail")
# Input from the user.
percent = float(input("Please enter the obtained percentage : "))
# Function get called and the statement print the corresponding returned grade.
print("You earned",grade(percent),"grade")
| true |
c6acf0c506bae2c792f8e9f647036776c335b506 | innovation-platform/Mad-Lib-generator | /mad.py | 1,203 | 4.125 | 4 | import tkinter
from tkinter import *
main=Tk()
main.geometry("500x500")
main.title("Mad Libs Generator")
Label(main,text="Mad Libs Generator",font="arial",bg="black",fg="white").pack()
Label(main,text="Click one:",font="italic",bg="white",fg="black").place(x=40,y=80)
def madlib1():
name=input("Enter a name of a boy:")
color=input("Enter a color name")
food=input("Enter a food name")
adjective=input("Enter an adjective")
profession=input("Enter a professsion")
print("Once upon a time there lived a person called "+name+".He was "+color+"colored. He always ate "+food+".He was a very "
+adjective+". He was a "+profession+".")
def madlib2():
animal=input("Enter name of an animal")
color=input("Enter color of an animal")
food=input("Enter food")
adjective=input("Enter an adjective")
print(animal+" is an animal which is in "+color+" color. It eats "+food+". It is a very "+adjective+" animal.")
Button(main,text="A Person",font="italic",command=madlib1,bg="black",fg="white").place(x=40,y=160)
Button(main,text="An Animal",font="italic",command=madlib2,bg="black",fg="white").place(x=40,y=240)
main.mainloop()
| true |
a907255a5ecbd9c126c08cad5693e319344d6027 | Alekssin1/first_lab_OOP | /first_task.py | 649 | 4.15625 | 4 | import sys
# cut first element(name of the file)
expression = "".join(sys.argv[1:])
# We use join to make our expression a string with
# spaces and then using the function eval
# check whether the user input is empty
if expression:
try:
print(eval(expression))
except ZeroDivisionError:
print("Attempt to divide a number by zero")
except NameError:
print("Incorrect input! Name error, try again")
except SyntaxError:
print("Invalid syntax. Try again.")
except EOFError or KeyboardInterrupt:
print("Error, incorrect input! Try again.")
else:
print("You need to enter an expression")
| true |
be9109066f9f34b4fa21aa46312871fb244c35ec | griadooss/HowTos | /Tkinter/05_buttons.py | 2,223 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode Tkinter tutorial
In this script, we use pack manager
to position two buttons in the
bottom right corner of the window.
author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""
#We will have two frames.
#There is the base frame and an additional frame, which will expand in both directions and
#push the two buttons to the bottom of the base frame.
#The buttons are placed in a horizontal box and placed to the right of this box.
from Tkinter import Tk, RIGHT, BOTH, RAISED
from ttk import Frame, Button, Style
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Buttons")
self.style = Style()
self.style.theme_use("default")
frame = Frame(self, relief=RAISED, borderwidth=1)
frame.pack(fill=BOTH, expand=1)
#We create another Frame widget.
#This widget takes the bulk of the area.
#We change the border of the frame so that the frame is visible.
#By default it is flat.
self.pack(fill=BOTH, expand=1)
closeButton = Button(self, text="Close")
closeButton.pack(side=RIGHT, padx=5, pady=5)
#A closeButton is created.
#It is put into a horizontal box.
#The side parameter will create a horizontal box layout, in which the button is placed to the right of the box.
#The padx and the pady parameters will put some space between the widgets.
#The padx puts some space between the button widgets and between the closeButton and the right border of the root window.
#The pady puts some space between the button widgets and the borders of the frame and the root window.
okButton = Button(self, text="OK")
okButton.pack(side=RIGHT)
#The okButton is placed next to the closeButton with 5px space between them.
def main():
root = Tk()
root.geometry("300x200+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main() | true |
f82da39fce4bb6efbffd817b4651cb1027e15410 | griadooss/HowTos | /Tkinter/01_basic_window.py | 2,700 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode Tkinter tutorial
This script shows a simple window
on the screen.
author: Jan Bodnar
last modified: January 2011
website: www.zetcode.com
"""
#While this code is very small, the application window can do quite a lot.
#It can be resized, maximized, minimized.
#All the complexity that comes with it has been hidden from the application programmer.
from Tkinter import Tk, Frame, BOTH
#Here we import Tk and Frame classes.
#The first class is used to create a root window.
#The latter is a container for other widgets.
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
#Our example class inherits from the Frame container widget.
#In the __init__() constructor method we call the constructor of our inherited class.
#The background parameter specifies the background color of the Frame widget.
self.parent = parent
#We save a reference to the parent widget. The parent widget is the Tk root window in our case.'''
self.initUI()
#We delegate the creation of the user interface to the initUI() method.
def initUI(self):
self.parent.title("Simple")
#We set the title of the window using the title() method.
self.pack(fill=BOTH, expand=1)
#The pack() method is one of the three geometry managers in Tkinter.
#It organizes widgets into horizontal and vertical boxes.
#Here we put the Frame widget, accessed via the self attribute to the Tk root window.
#It is expanded in both directions. In other words, it takes the whole client space of the root window.
def main():
root = Tk()
#The root window is created.
#The root window is a main application window in our programs.
#It has a title bar and borders.
#These are provided by the window manager.
#It must be created before any other widgets.
root.geometry("250x150+300+300")
#The geometry() method sets a size for the window and positions it on the screen.
#The first two parameters are width and height of the window.
#The last two parameters are x and y screen coordinates.
app = Example(root)
#Here we create the instance of the application class.
root.mainloop()
#Finally, we enter the mainloop.
#The event handling starts from this point.
#The mainloop receives events from the window system and dispatches them to the application widgets.
#It is terminated when we click on the close button of the titlebar or call the quit() method.
if __name__ == '__main__':
main()
| true |
2a535a9f8cf2b45ffc9469195319a9a0df2df168 | griadooss/HowTos | /Tkinter/14_popup_menu.py | 1,706 | 4.40625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode Tkinter tutorial
In this program, we create
a popup menu.
author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""
'''Popup menu'''
# In the next example, we create a popup menu.
# Popup menu is also called a context menu.
# It can be shown anywhere on the client area of a window.
# In our example, we create a popup menu with two commands.
from Tkinter import Tk, Frame, Menu
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Popup menu")
self.menu = Menu(self.parent, tearoff=0)
#A context menu is a regular Menu widget.
#The tearoff feature is turned off.
#Now it is not possible to separate the menu into a new toplevel window.
self.menu.add_command(label="Beep", command=self.bell())
self.menu.add_command(label="Exit", command=self.onExit)
self.parent.bind("<Button-3>", self.showMenu)
#We bind the <Button-3> event to the showMenu() method.
#The event is generated when we right click on the client area of the window.
self.pack()
#The showMenu() method shows the context menu.
#The popup menu is shown at the x and y coordinates of the mouse click.
def showMenu(self, e):
self.menu.post(e.x_root, e.y_root)
def onExit(self):
self.quit()
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
| true |
cf108c19ac33a9286c8daba5bff0c3f9b7098711 | djcolantonio/PythonProjects | /homework_function_scor.py | 407 | 4.15625 | 4 | # This program evaluates the score and LOOPS
while True:
score = input('What is your score: ')
try:
if int(score) >= 90:
print('This is an excellent score')
elif int(score) >=80:
print('This is a good score')
else:
print('You need a better score')
break
except ValueError:
print('Please enter a number')
| true |
04a6d1f06fde2c1e1c1b886d0f92cf912a294a81 | djcolantonio/PythonProjects | /for and while loop.py | 226 | 4.125 | 4 | # for loop example
print('Today is')
for i in range(5):
print('Thursday Five Times ' + str(i))
# for while loop
print('Today is')
i=0
while i < 5:
print('Thursday Five Times ' + str(i))
i = i + 1
| false |
534456b717efe50a9709c45edeedf8579a945769 | CGayatri/Python-Practice1 | /control_3.py | 298 | 4.3125 | 4 | ## program 3 - to display a group of messages when the condition is true - to display suite
str = 'Yes'
if str == 'Yes':
print("Yes")
print("This is what you said")
print("Your response is good")
'''
F:\PY>py control_3.py
Yes
This is what you said
Your response is good
''' | true |
a3df363bd6c12796722d7c243b009bd04a213538 | CGayatri/Python-Practice1 | /control_13.py | 252 | 4.28125 | 4 | ## program 13 - to display each character from a string using sequence index
str = 'Hello'
n = len(str) # find no. of chars in str
print("Lenght :", n)
for i in range(n):
print(str[i])
'''
F:\PY>py control_13.py
Lenght : 5
H
e
l
l
o
''' | true |
6804a11ea2a813351e7b51112737afdddd3ab834 | CGayatri/Python-Practice1 | /inputs1.py | 225 | 4.21875 | 4 | ### program - 1 to accept a string from keyboard
# accepting a string from keyboard
str = input("Enter a string: ")
print("U entered: ", str)
#Output:
'''
F:\PY>py inputs1.py
Enter a string: Gayatri Chaudhari
U entered: Gayatri Chaudhari
'''
| false |
75dc369c4b309a387583cc7dc8d05d91c29cf318 | CGayatri/Python-Practice1 | /Module1/CaseStudy_1/demo5.py | 501 | 4.34375 | 4 | # 5.Please write a program which accepts a string from console and print the characters that have even indexes.
# Example: If the following string is given as input to the program:
# H1e2l3l4o5w6o7r8l9d
# Then, the output of the program should be:
# Helloworld
str = input("Enter input string : ")
str = str[0: len(str) : 2]
print(str)
'''
F:\PY\Module1\CaseStudy_1>py demo5.py
Enter input string : H1e2l3l4o5w6o7r8l9d
Helloworld
F:\PY\Module1\CaseStudy_1>
'''
| true |
abbff9bfdf999a1e6e1026dca5edb78d3833974c | CGayatri/Python-Practice1 | /string_1.py | 799 | 4.1875 | 4 | ## program 1 - to access each element of a string in forward and reverse orders using while loop
# indexing on strings
str = 'Core Python'
# access each character using whie loop
i = 0 # i = 0, 1, 2, 3, ... (n-1)
n = len(str)
while i<n: # 0 to n-1
print(str[i], end=' ')
i+=1
print()
# access in reverse order
i=-1 # i = -1, -2, -3, ... (-n)
while i>=-n: # -1 to -n
print(str[i], end=' ') #str[i]
i-=1
print()
# access in reverse order using negative index
i=1 # i = 1, 2, 3, ... n
#n = len(str)
while i<=n: # 1 to n
print(str[-i], end=' ') #str[-i]
i+=1
'''
F:\PY>py string_1.py
C o r e P y t h o n
n o h t y P e r o C
n o h t y P e r o C
F:\PY>
''' | false |
ffbc972b3eb83c04f21056e27e493a0ee9b1e4db | CGayatri/Python-Practice1 | /control_20.py | 343 | 4.375 | 4 | ## program 20 - to display stars in right angled triangular form using a single loop
# to display stars in right angled triangular form - v2.0
for i in range(1, 11):
print('* ' * (i)) # repeat star (*) for i times
## v1.0 :
'''
for i in range(1, 11):
for j in range(1, i+1):
print('* ', end='')
print()
''' | false |
286c01b126996d05ee34b93bca9b3616a3199d69 | CGayatri/Python-Practice1 | /string_13_noOfWords.py | 668 | 4.125 | 4 | ## Program 13 - to find the number of words in a string
# as many number of spaces; +1 wuld be no of words
# to find no. of words in a string
str = input('Enter a string : ')
i=0
count=0
flag = True # this becomes False when no space is found
for s in str:
# Count only when there is no space previously
if (flag==False and str[i]==' '):
count+=1
# If a space is found, make flag as True
if (str[i]==' '):
flag = True
else :
flag = False
i=i+1
print('No. of words :', (count+1))
'''
F:\PY>py string_13_noOfWords.py
Enter a string : You are a sweet girl baby
No. of words : 6
''' | true |
456bc270c408a04758347728e9bd02c1b3a96e52 | CGayatri/Python-Practice1 | /string_9_chars.py | 1,010 | 4.4375 | 4 | ## Working with Characters -- get a string --> get chars using indexing or slicing
## program 9 - to know the type of character entered by the user
str = input('Enter a character : ')
ch = str[0] # take only 0th character niito ch
# test ch
if (ch.isalnum()):
print("It is an alphabet or numeric character")
if (ch.isalpha()):
print("It is an alphabet")
if (ch.isupper()):
print("It is capital letter")
else :
print("It is lowercase letter")
else :
print("It is a numeric digit")
elif (ch.isspace()):
print("It is a space")
else :
print("It may be a special character")
'''
F:\PY>py string_9_chars.py
Enter a character : a
It is an alphabet or numeric character
It is an alphabet
It is lowercase letter
F:\PY>py string_9_chars.py
Enter a character : &
It may be a special character
F:\PY>py string_9_chars.py
Enter a character : 5
It is an alphabet or numeric character
It is a numeric digit
''' | true |
ea4b5b1bdd6bb54b8c439ee2ecfa37a0d0149748 | CGayatri/Python-Practice1 | /control_11.py | 707 | 4.15625 | 4 | ## program 11 - to display even numbers between m and n (minimum and maximum range)
m , n = [int(i) for i in input("Enter comma separated minimum and maximum range: ").split(',')]
# 1 to 10 ===>
x = m # start from m onwards
#x = 1 # start from ths number
# make start as even so that adding 2 to it would give next even number
if(x%2 != 0):
x = x + 1
while(x>=m and x<=n):
print(x)
x+=2
print("End")
"""
F:\PY>py control_11.py
Enter comma separated minimum and maximum range: 1, 10
2
4
6
8
10
End
F:\PY>
"""
'''
while(x>=m and x<=n):
if(x%2 == 0):
print(x)
x+=2
print("End")
F:\PY>py control_11.py
Enter comma separated minimum and maximum range: 1, 10
End
'''
| true |
9d029614f80818e96a163348028788b3b4639937 | CGayatri/Python-Practice1 | /string_8.py | 416 | 4.28125 | 4 | ## Splitting and Joining Strings
## Program 8 - to accept and display a group of numbers
# string.split(seperator)
# separator.join(string)
str = input('Enter numbers separated by space : ')
# cut the string where a space is found
lst = str.split(' ')
# display the numbers from teh list
for i in lst :
print(i)
'''
F:\PY>py string_8.py
Enter numbers separated by space : 10 20 30 40
10
20
30
40
''' | true |
bdde2a9d113f48aac14994980bad4e84caedd315 | CGayatri/Python-Practice1 | /prime.py | 558 | 4.15625 | 4 | # program to display prime numbers between range
#Take the input from the user:
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
"""
F:\PY>py prime.py
Enter lower range: 1
Enter upper range: 10
2
3
5
7
F:\PY>py prime.py
Enter lower range: 10
Enter upper range: 50
11
13
17
19
23
29
31
37
41
43
47
F:\PY>
""" | true |
457950d15654565ce70aa6b6c664eeb431ea25a2 | CGayatri/Python-Practice1 | /function_12_functionReturnsAnotherFun.py | 452 | 4.25 | 4 | ## Program 12 - to know how a function can return another function
# functions can return other functions
def display():
def message():
return 'How are you?'
return message
# call display() function and it returns message() function
# in following code, 'fun' refers to the name : 'message' @ line:9
fun = display()
print(fun())
#Output:
'''
F:\PY>py function_12_functionReturnsAnotherFun.py
How are you?
''' | true |
8e9e41a1adabea2eef1da2b4f66e6f1794105b1a | CGayatri/Python-Practice1 | /input22_argparse.py | 660 | 4.59375 | 5 | ## program - 22 : to find the power value of a number when it is rised to a particular power
import argparse
# call the ArgumentParser()
parser = argparse.ArgumentParser()
# add the arguments to teh parser
parser.add_argument('nums', nargs=2)
# retrieve arguments from parser
args = parser.parse_args()
#find the power value
#args.nums is a list
print("Number =", args.nums[0])
print("It\'s power =", args.nums[1])
# calculate power by coverting strings to numbers
result = float(args.nums[0]) ** float(args.nums[1])
print("power rsult = ", result)
"""
F:\PY>py input22_argparse.py 10.5 3
Number = 10.5
It's power = 3
power rsult = 1157.625
""" | true |
d0ceb6917502b06bc741630afdf20a439299646b | lightTouchDev/lFpiepr | /flip.py | 1,240 | 4.21875 | 4 | #!/usr/bin/python3
# Write a program that reverses every other letter of a given string
# Ex. Hello -> eHllo | World -> oWlrd
from itertools import zip_longest
## With import
def flipper(word):
w = word[::2]
x = word[1::2]
r = ''
for i,a in zip_longest(x,w, fillvalue=''):
r += i
r += a
print(r)
flipper('Hello')
## w/out import
def flip(word):
r = ''
for i in range(1,len(word), 2):
r += word[i]
r += word[i - 1]
if len(word) % 2 != 0:
r += word[ -1 ]
print(r)
flip('Hello')
#---------------------------------
## Failed attempts
# only works for words with 5+ letters
# def flip(word):
# l = [word[i] for i in range(1,len(word),2)]
# f = [word[i] for i in range(0,len(word),2)]
# for i in l:
# f.insert(l.index(i) + -3,i)
# print(f)
# flip('World')
# Works with strings of even number, else leaves off final element
# def flipper(word):
# w = word[::2]
# x = word[1::2]
# r = ''
# for i in range(len(x)) or range(len(w)):
# if len(word) % 2 == 0:
# r += x[i] + w[i]
# else:
# r += x[i] + w[i]
# r += word[-1]
# print(r)
# flipper('world')
| false |
69d2b90af1c5dfa0145321e0d808576599d31ec7 | raiyanshadow/BasicPart1-py | /ex21.py | 272 | 4.40625 | 4 | # Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
n = int(input("ENTER NUMBER: "))
if n % 2 == 0:
print("That is an even number.")
else:
print("That is an odd number.")
| true |
493f3e7118bd295e73cd8e119f1af85f16415535 | novigit/learn_ete3 | /12_prune_tree.py | 771 | 4.15625 | 4 | #!/usr/bin/env python
from ete3 import Tree
# Let's create simple tree
t = Tree('((((H,K),(F,I)G),E),((L,(N,Q)O),(P,S)));', format=1)
print("Original tree looks like this:")
print(t)
# /-H
# /-|
# | \-K
# /-|
# | | /-F
# /-| \-|
# | | \-I
# | |
# | \-E
# --|
# | /-L
# | /-|
# | | | /-N
# | | \-|
# \-| \-Q
# |
# | /-P
# \-|
# \-S
# Prune the tree in order to keep only some leaf nodes.
# Pruning means to discard all nodes and associated branches except those
# that are requested
t.prune(["H","F","E","Q", "P"])
print("Pruned tree")
print(t)
# /-H
# /-|
# /-| \-F
# | |
# --| \-E
# |
# | /-Q
# \-|
# \-P | false |
89d58cabd879fb0e9a0f3b01bf665c754f367653 | SharonOBoyle/python-lp3thw | /ex7.py | 1,028 | 4.25 | 4 | # print the sentence to the screen
print("Mary had a little lamb.")
# print the sentence to the screen, substituting 'snow' inside the {}
print("Its fleece was white as {}.".format('snow'))
# print the sentence to the screen
print("And everywhere that Mary went.")
# this printed 10 . characters in succession on the same line i.e. ".........."
print("." * 10) # what'd that do?
# creates a variable named end* and assigns the character value to it
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
#debugging by printing the variable value :)
#print(end10)
# prints the words "Cheese Burger" but concatenating the value of each
# specified variable, when you print, instead of a new line use a space
# watch that comma at the end. try removing it to see what happens
# Removing the comma causes an error: SyntaxError: invalid syntax
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ')
print(end7 + end8 + end9 + end10 + end11 + end12)
| true |
e127418b2765a0cb6c76915003aafd5535aea7c1 | SharonOBoyle/python-lp3thw | /ex30.py | 1,007 | 4.25 | 4 | # create a variable named people with value 40
people = 40
cars = 4
trucks = 15
# if the boolean expression is true, execute the code in the block, otherwise skip it
if cars > people or trucks > people:
print(">>> if cars > people or trucks > people:", cars, people, trucks)
print("We should go somewhere")
# execute this condition if the above if boolean expression is false
# if the boolean expression is true, execute the code in the block, otherwise skip it
elif cars < people:
print(">>> elif cars < people:", cars, people)
print("We should not take the cars.")
# execute this condition if both the above if and elif boolean expressions are false
else:
print (""We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars and people != 40 :
print("Maybe we could take the trucks.")
else:
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay home then.")
| true |
270bd98e879bcc4a2af763a7b6a399b812bce881 | SharonOBoyle/python-lp3thw | /ex15.py | 1,229 | 4.59375 | 5 | # import the argv module (argument variable/vector) from the sys package
# argv holds the arguments specified when running this script
# from the command line
from sys import argv
# unpack argv and assign it to the variables on the left, in that order
script, filename = argv
# open the file with the open() function which returns the file object
# assign the file object to a variable named txt
txt = open(filename, "a")
txt.write("appended some text")
txt.close()
txt = open(filename)
# display this message on screen
print(f"Here's your file {filename}:")
# call a function named "read" on txt i.e. run the "read" command on it
# and print the results
print(txt.read())
# close the file
txt.close()
# Ask user to input the filename at the prompt
print("Type the filename again:")
# prompt the user and assign the value of what user typed in
# to a variable named "file_again"
file_again = input("> ")
# assign the file to a variable called "txt_again"
# open a file, and return it as a file object
txt_again = open(file_again)
# read the file and print the output to the screen,
# by calling the function "read()" on txt_again
# print the contents of the file
print(txt_again.read())
# close the file
txt_again.close()
| true |
52c5e443a0c2dcd3f63995cdb92740bc6678e9e5 | sharkseba/taller-progra | /EjerciciosFunciones/ejercicio3.py | 842 | 4.3125 | 4 | """ Crear una funcion que calcule el promedio de los datos de una lista
La función debe recibir como parámetros una lista de datos
La funcion debe retornar el promedio """
# Dos formas de hacer este ejercicio
def promedio_forma_1(lista_datos):
suma_datos = 0 # Variable acumuladora de datos
contador_datos = 0 # Variable contador de datos
for dato in lista_datos:
suma_datos = suma_datos + dato
contador_datos = contador_datos + 1
promedio = suma_datos / contador_datos
return promedio
def promedio_forma_2(lista_datos):
return (sum(lista_datos) / len(lista_datos))
# Programa principal
lista = [1,2,3,4,5,6,7,8,9,10] # El primedio debería ser 5,5
print('Promedio utilizando la forma 1: ', promedio_forma_1(lista))
print('Promedio utilizando la forma 2: ', promedio_forma_2(lista))
| false |
234a3e8927399a4f381b0c9b8b7e717abd33269e | sharkseba/taller-progra | /Ejercicios Control Flujo-condicionales/ejercicio21.py | 496 | 4.1875 | 4 | vocales = 'aeiou'
s = input('Ingrese una letra: ')
# Verificamos que el usuario haya ingresado solo 1 carácter
if len(s) == 1:
# Verificamos que la letra pertenezca al alfabeto
if s.isalpha():
if s in vocales or s in vocales.upper():
print('La letra ingresada es una vocal')
else:
print('La letra ingresada es una consonante')
else:
print('El carácter ingresado no es una letra')
else:
print('Debe ingresar solo 1 carácter')
| false |
6113df963dc863bf01725cf9b01e68d99945b460 | walkeZ/Learning | /Python/1806/demo/练习05-摄氏度和华氏度转化.py | 952 | 4.21875 | 4 | '''
需求:# 用户输入摄氏温度s,输出华氏度h,h=(s*1.8)+32
# 接收用户输入
'''
# celsius = float(input('输入摄氏度:'))
# fahrenheit=(celsius*1.8)+32
# print('华氏温度:fahrenheit = ',fahrenheit)
print("-----------------方法&装饰器---------------------")
# 装饰器
def outer(func):
def inner():
print('装饰器')
func() # 这里要括号
return inner # 这里不用括号
# 封装方法
@outer # 引用装饰器
def c_t_f():
celsius = float(input('c_t_f输入摄氏度:'))
fahrenheit = (celsius * 1.8) + 32
print('摄氏温度:celsius = ', celsius,' 华氏温度:fahrenheit = ', fahrenheit)
# 华氏度 转 摄氏度
def ftc():
f=float(input('ftc 请输入华氏度:'))
c=(f-32)/1.8
print('华氏度:f = ',f,' 摄氏度 c = ',c)
ftc=outer(ftc)
ftc() # 调用要括号
c_t_f()
| false |
de8ea9d23568b4d76643e70ccd4b0d8f4725e3a5 | 729416873/luqy | /test-workspace/testrun/class/C5类变量与实例变量.py | 649 | 4.125 | 4 | # self不是关键字,他其实是可以替换成其他的,但是关键字是不可变的
#类变量 与 实例变量
class Student():
# 类变量
name = 'qiyue'
age = 0
sum = 1
def __init__(self,name,age):
# self.实例变量的名字 ——实例变量 ,用来保存类的特征值
self.name = name # 特征值只和对象相关,与类无关
self.age = age
def do_homework(self):
print('homework')
student1 = Student('石敢当',18)
student2 = Student('喜小乐',18)
print(student1.name)#对象.name
print(student2.name)
print(Student.name)#类.name
| false |
d616671e022050c16a9ab70912fd0d1ca6e1b97d | jmo24/Python | /EDX-6.00.1x/lect6-oddTuple.py | 547 | 4.3125 | 4 | '''
('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this
input would return the tuple ('I', 'a', 'tuple')
'''
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
# Your Code Here
#length = len(aTup)
#print length
#oddTuple = ()
i = 0
newTuple = ()
while i <len(aTup):
if i % 2 == 0:
#print i
newTuple = newTuple + (aTup[i],)
i = i + 1
return newTuple
aTup = ('I', 'am', 'a', 'test', 'tuple')
print oddTuples(aTup) | false |
81e0a9530720aef7190e88ce5fdabe5ab43b86d4 | ClearlightY/Python_learn | /top/clearlight/base/liaoxuefeng/base/Dict.py | 1,297 | 4.1875 | 4 | # dict: 使用键-值存储
d = {'Mike': 90, 'Bob': 70, 'Luck': 100}
print(d['Luck'])
# 最后放入key的value, 将会把前面的值冲掉
d['Mike'] = 98
print(d)
# 避免key不存在的错误
# 1. 通过in判断key是否存在
if 'Mike' in d:
print(d['Mike'])
# get(): 如果key不存在可以返回None或者返回指定的value, 若存在则返回key对应的value
print(d.get('Bob'))
print(d.get('Blue', -1))
print(d.get('Bob', 99))
print(d.get('Blue'))
# pop(key)方法: 删除一个key, 同时对应的value也会从dict中删除
luck = d.pop('Luck')
print(luck)
print(d)
# set: 是一组key的集合, 但不存储value.
# 没有重复的值, 且set(list)需要提供一个list作为输入集合
# 无序 无重复 的集合
s = set([1, 1, 2, 2, 3, 3])
print(s)
s = {1, 1, 2, 2, 3, 3}
print(s)
# 添加元素
s.add(4)
print(s)
s.add(-12)
print(s)
# 移除元素
s.remove(3)
print(s)
# &: 交集 |: 并集
s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
print(s1 & s2)
print(s1 | s2)
l = [1, 1, 2, 2, 3, 3, 4]
s = set(l)
print('s:', s)
s1 = (1, 2, 3)
s2 = (1, [2, 3])
print('s1:', s1)
print('s2:', s2)
# 如果存入set时存在list则会报错, 因为list属于可变(不可hash),因此不能存入s2
d = {s1, s1}
print('d:', d)
# set可以直接用{}定义 等价于 set([])
| false |
d0be707b6b95674e7a55339a7774568045b2a525 | stacykutyepov/python-cp-cheatsheet | /educative/slidingWindow/non_repeat_substring.py | 537 | 4.21875 | 4 | """
time: 13 min
errors: none!
"""
def non_repeat_substring(str):
maxLen, i = 0, 0
ht = {}
for i, c in enumerate(str):
if c in ht:
maxLen = max(maxLen, len(ht))
ht.clear()
ht[c] = True
maxLen = max(len(ht), maxLen)
return maxLen
def main():
print("Length of the longest substring: " + str(non_repeat_substring("aabccbb")))
print("Length of the longest substring: " + str(non_repeat_substring("abbbb")))
print("Length of the longest substring: " + str(non_repeat_substring("abccde")))
main() | true |
4b598ac15547bccf6febd027fc489c6d28657761 | rashi174/GeeksForGeeks | /reverse_array.py | 666 | 4.15625 | 4 | """
Given a string S as input. You have to reverse the given string.
Input: First line of input contains a single integer T which denotes the number of test cases. T test cases follows, first line of each test case contains a string S.
Output: Corresponding to each test case, print the string S in reverse order.
Constraints:
1 <= T <= 100
3 <= length(S) <= 1000
Example:
Input:
3
Geeks
GeeksforGeeks
GeeksQuiz
Output:
skeeG
skeeGrofskeeG
ziuQskeeG
** For More Input/Output Examples Use 'Expected Output' option **
Contributor: Harsh Agarwal
Author: harsh.agarwal0
"""
for _ in range(int(input())):
s=input()
print(s[::-1]) | true |
c28f332fc9cbc62aa584fb9cca14452e89904da7 | jieunjeon/daily-coding | /Leetcode/716-Max_Stack.py | 2,235 | 4.125 | 4 |
"""
https://leetcode.com/problems/max-stack/
716. Max Stack
Design a max stack that supports push, pop, top, peekMax and popMax.
push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.
Example 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
Note:
-1e7 <= x <= 1e7
Number of operations won't exceed 10000.
The last four operations won't be called when stack is empty.
Time Complexity: O(1), except for popMax O(n)
Space Complexity: O(n)
"""
class MaxStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.maxStack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack.append(x)
if not self.maxStack or x >= self.maxStack[-1]:
self.maxStack.append(x)
def pop(self):
"""
:rtype: int
"""
if self.stack[-1] == self.maxStack[-1]:
self.maxStack.pop()
return self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def peekMax(self):
"""
:rtype: int
"""
if self.maxStack:
return self.maxStack[-1]
def popMax(self):
"""
:rtype: int
"""
temp = []
while self.stack[-1] != self.maxStack[-1]:
temp.append(self.stack[-1])
self.stack.pop()
res = self.stack.pop()
self.maxStack.pop()
while temp:
self.push(temp[-1])
temp.pop()
return res
# Your MaxStack object will be instantiated and called as such:
# obj = MaxStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.peekMax()
# param_5 = obj.popMax() | true |
bb18fb0b36d359fcf7269535391e2d705a0cdf25 | RenataKukryakova/cs102 | /homework01/vigenere.py | 1,967 | 4.125 | 4 | def encrypt_vigenere(plaintext: str, keyword: str) -> str:
"""
Encrypts plaintext using a Vigenere cipher.
>>> encrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> encrypt_vigenere("python", "a")
'python'
>>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
'LXFOPVEFRNHR'
"""
ciphertext = ""
for l in range(len(plaintext)):
keyword = keyword.upper()
pos = l % len(keyword)
shift = ord(keyword[pos]) - ord("A")
if "a" <= plaintext[l] <= "z" or "A" <= plaintext[l] <= "Z":
if plaintext[l].isupper() and chr(ord(plaintext[l]) + shift) > "Z":
ciphertext += chr(ord(plaintext[l]) - 26 + shift)
elif "a" <= plaintext[l] <= "z" < chr(ord(plaintext[l]) + shift):
ciphertext += chr(ord(plaintext[l]) - 26 + shift)
else:
ciphertext += chr(ord(plaintext[l]) + shift)
else:
ciphertext += plaintext[l]
return ciphertext
def decrypt_vigenere(ciphertext: str, keyword: str) -> str:
"""
Decrypts a ciphertext using a Vigenere cipher.
>>> decrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> decrypt_vigenere("python", "a")
'python'
>>> decrypt_vigenere("LXFOPVEFRNHR", "LEMON")
'ATTACKATDAWN'
"""
plaintext = ""
for l in range(len(ciphertext)):
keyword = keyword.upper()
pos = l % len(keyword)
shift = ord(keyword[pos]) - ord("A")
if "a" <= ciphertext[l] <= "z" or "A" <= ciphertext[l] <= "Z":
if ciphertext[l].isupper() and chr(ord(ciphertext[l]) - shift) < "A":
plaintext += chr(ord(ciphertext[l]) + 26 - shift)
elif chr(ord(ciphertext[l]) - shift) < "a" <= ciphertext[l] <= "z":
plaintext += chr(ord(ciphertext[l]) + 26 - shift)
else:
plaintext += chr(ord(ciphertext[l]) - shift)
else:
plaintext += ciphertext[l]
return plaintext
| false |
21ea03e5095d04d74d6a5cae00df7cbb87a87bb7 | leonardosantos07/listas-exercicios-python | /estrutura_decisao/ex20.py | 741 | 4.21875 | 4 | #Faça um Programa para leitura de três notas parciais de um aluno.
#O programa deve calcular a média alcançada por aluno e presentar:
#A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva média alcançada;
#A mensagem "Reprovado", se a média for menor do que 7, com a respectiva média alcançada;
#A mensagem "Aprovado com Distinção", se a média for igual a 10.
nota1 = float(input('informe a primeira nota:'))
nota2 = float(input('informe a segunda nota:'))
nota3 = float(input('informe a terceira nota:'))
media = (nota1 + nota2 + nota3) / 3
if (media == 10):
print('o aluno esta aprovado com distinção')
elif (media>=7):
print('o aluno esta aprovado')
else:
print('o aluno esta reprovado')
| false |
6a5f82b4645e349246761c8b39829823fa7407a4 | Christopher14/Selection | /revision exercise 2.py | 240 | 4.15625 | 4 | #Christopher Pullen
#30-09-2014
#Revision exercise 2
age = int(input("please enter your age:"))
if age >= 17:
print ("you are legally able to drive a car with learner plates")
else:
print ("you are not legally able to drive a car")
| true |
7ed3bf159a9e29e856944f8fca2ad7c81bbb58cc | infx598g-s16/04-18-python3 | /interest.py | 1,118 | 4.40625 | 4 | # Prompt the user for an Initial Balance (and save to a variable)
# use the float() function to convert the input into a number.
balance = float(input("Initial balance: "))
# Prompt the user for an Annual Interest % (and save to a variable)
# use the float() function to convert the input into a number
interest = float(input("Annual interest % "))
# change the percentage number into a decimal (e.g. 6 turns into .06, 5 turns into .05, etc).
# remember to save your new value to a variable!
interest = interest/100
# Prompt the user for a Number of years (and save to a variable)
# use the int() function to convert the input into an integer
years = int(input("Years: "))
def calculate_interest(balance, interest, years):
new_balance = balance*(1+(interest/12))**(12*years)
interest_earned = new_balance - balance
return interest_earned
# Output the interest earned
earned = calculate_interest(balance, interest, years)
output = "Interest earned in "+str(years)+" years: $"+str(earned)
print(output)
# Output the total value
print("Total value after "+str(years)+" years: $"+str(earned + balance))
| true |
4fa6fd511e7dc72aaa4b372556c78a575a08b2ab | minh01082004m/C4T-BO5-Romace | /hey/session 4/session 5/test for/datati.py | 203 | 4.125 | 4 | #x= int(input(""))
#if x>0:
# print("x>0")
#else:
# print("x<0")
while True:
x= int(input("somethings"))
if x>0:
print("right")
break
else:
print("wrong")
| false |
a9bed29fb65836ee58d9de662e6ea4d1612ffdea | Mokarram-Mujtaba/Mini-Projects | /faulty calculator.py | 688 | 4.15625 | 4 | #Faulty calculator
#Design a calculator which gives wrong input whebn user enters the following calculation
# 45 * 3 = 555, 56+9 = 77, 56/6 = 4
x1=input("Enter the opertions you want.+,-,/,%,* \n")
x2=int(input("Enter the 1st number"))
x3=int(input("Enter the 2nd number"))
if x2==45 and x3==3 and x1=='*':
print("555")
elif x2==56 and x3==9 and x1=='+':
print("77")
elif x2==56 and x3==6 and x1=='/':
print("4")
elif x1=='*':
mult=x2*x3
print(mult)
elif x1=='+':
add=x2+x3
print(add)
elif x1=='-':
sub=x2-x3
print(sub)
elif x1=='/':
div=x2/x3
print(div)
elif x1=='%':
perc=x2%x3
print(perc)
else:
print("Something went wrong")
| true |
b5778f7a056996cd63f63aa462d925ecfb0edd86 | khan-c/learning_python | /py3tutorial.py | 397 | 4.34375 | 4 | print("hello world")
# this is a tuple as opposed to a list
# syntax would be either written like this or with parantheses
programming_languages = "Python", "Java", "C++", "C#"
# an array would use brackets like this:
languages_list = ["Python", "Java", "C++", "C#"]
# for - in loop
for language in programming_languages:
print(language)
for language in languages_list:
print(language) | true |
5b5c378c445b9de900f3a5a1a82970f784a4d2ca | spencercorwin/automate-the-boring-stuff-answers | /Chapter12MultiplicationTable.py | 952 | 4.15625 | 4 | #! usr/bin/env python3
#Chapter 12 Challenge - Multiplication Table Marker
#Takes the second argument of input, an integer, and makes a multiplication
#table of that size in Excel.
import os, sys, openpyxl
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet = wb.active
#tableSize = sys.argv[1]
tableSize = 6
fontObj = Font(bold=True)
#Loop to add the top row of 1 to tableSize then left column of save size, in bold
for topCell in range(1,tableSize+1):
sheet.cell(row=1, column=topCell+1).value = topCell
sheet.cell(row=1, column=topCell+1).font = fontObj
sheet.cell(row=topCell+1, column=1).value = topCell
sheet.cell(row=topCell+1, column=1).font = fontObj
#Loop through and multiply
for x in range(2,tableSize+2):
for y in range(2,tableSize+2):
sheet.cell(row=x, column=y).value = sheet.cell(row=x, column=1).value * sheet.cell(row=1, column=y).value
#Save the new workbook
wb.save('multiTable.xlsx')
| true |
43e0551fe36887ca2b140c7ab04352332c3b499f | DhruvGala/LearningPython_sample_codes | /TowerOfHanoi.py | 1,014 | 4.1875 | 4 | '''
Created on Oct 10, 2015
@author: DhruvGala
The following code is a general implementation of Tower of hanoi problem using python 3.
'''
from pip._vendor.distlib.compat import raw_input
'''
The following method carries out the recursive method calls to solve the
tower of hanoi problem.
'''
def towerOfHanoi(number,source,inter,dest):
if(number == 1):
print("Disk 1 from {} to {} ".format(source,dest))
else:
towerOfHanoi(number-1, source, dest, inter)
print("Disk {} from {} to {}".format(number,source,dest))
towerOfHanoi(number-1, inter, source, dest)
'''
the main method
'''
def main():
towerOfHanoi(takeInput(),"A","B","C")
'''
takes the input as the number of disk involved in the problem.
'''
def takeInput():
n = raw_input("Enter the number of disks: ")
try:
nDisk = int(n)
except:
print("Invalid input")
return nDisk;
#call the main method
if __name__ == "__main__": main() | true |
f916bcbca35a5b84111b9894f85bcc637628d1ff | arimont123/python-challenge | /PyBank/main.py | 2,137 | 4.125 | 4 | import os
import csv
#python file in same folder as budget_data.csv
csvpath = "budget_data.csv"
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
#start reading in data after first row of text
csvheader = next(csvreader)
#create empty lists to store data from each column
date = []
prof_loss = []
#loop through columns in file
for row in csvreader:
date.append(row[0])
prof_loss.append(float(row[1]))
num_months = len(date) #calculates total number of months
net_prof_loss = sum(prof_loss) #calculates net prof/loss over entire period
#create empty list to store changes in prof/loss over time
change = []
for i in range(1,len(prof_loss)):
#calculates difference in current month and previous month
change.append(prof_loss[i]-prof_loss[i-1])
avg_change = sum(change)/len(change)
#find max and min change
max_change = max(change)
min_change = min(change)
#For loop loops from 1 to length of prof/loss column
#Add 1 to the index of change in order to match index of date
max_date = str(date[change.index(max(change))+1])
min_date = str(date[change.index(min(change))+1])
#Print results to terminal
print("Financial Analysis")
print("-----------------------------------")
print(f"Total Months: {num_months}")
print(f"Total: $ {round(net_prof_loss)}")
print(f"Average Change: ${round(avg_change,2)}")
print(f"Greatest Increase in Profits: {max_date} (${round(max_change)})")
print(f"Greatest Decrease in Profits: {min_date} (${round(min_change)})")
#Output results into text file
f= open("bank_results.txt", 'w+')
f.write("Financial Analysis\n")
f.write("-----------------------------------\n")
f.write(f"Total Months: {num_months}\n")
f.write(f"Total: $ {round(net_prof_loss)}\n")
f.write(f"Average Change: ${round(avg_change,2)}\n")
f.write(f"Greatest Increase in Profits: {max_date} (${round(max_change)})\n")
f.write(f"Greatest Decrease in Profits: {min_date} (${round(min_change)})\n") | true |
27c5a897cd37bdb7a52017ea73996ace4d06380f | Arinze1020/List-of-my-script-project- | /ASK USER FOR A NUMBER AND ASK AND CHECK IF IT IS EVEN OR ODD/CHECK IF UNM IS EVEN OR ODD.PY.py | 213 | 4.21875 | 4 | prompt = "ENTER A NUMBER \n"
number = float(input(prompt))
if number%2 == 0:
print(number,"IS AN EVEN NUMBER")
elif number%2!= 0:
print(number,"IS AN ODD NUMBER")
else:
print("TRY INPUTING A NUMBER")
| false |
29c45bbdc3bf5ff5b822dbffc16ce7e1a91e7037 | kml1972/python-tutorials | /code/tutorial_27.py | 1,125 | 4.1875 | 4 |
shopping_list = [
'milk','eggs','bacon','beef',
'soup','bread','mustard','toothpaste'
]
# looping by index vs using an iterator
i = 0
while i < len(shopping_list):
curr_item = shopping_list[i]
print( curr_item )
i += 1
for curr_item in shopping_list:
print( curr_item )
#shopping_list.__iter__()
pencil_holder = iter(shopping_list)
#pencil_holder.__next__()
first = next(pencil_holder)
sec = next(pencil_holder)
print( first, sec )
# very large generator expression
pow_three = (n ** 3 for n in range(1000000000000))
# if you used a list comprehension you'd most likely run out of memory.
#pow_three = [n ** 3 for n in range(1000000000)]
# the generator will only calculate the first 10 powers of three and then pause until you use next() again
for t in range(10):
print(t, next(pow_three) )
# prints out the eleventh power of 3
print( next(pow_three) )
# use generators to create previous comprehensions
pow_four = tuple(n ** 4 for n in range(10))
pow_five = list(n ** 5 for n in range(10))
pow_six = set(n ** 6 for n in range(10))
pow_sev = dict( (n, n ** 7) for n in range(10))
| true |
3c99da6c123b0f76b02f11746f584acd92c00c48 | LKHUUU/SZU_Learning_Resource | /计算机与软件学院/Python程序设计/实验/实验1/problem1.py | 228 | 4.3125 | 4 | import math
radius = float(input("Enter the radius of a cylinder:"))
length = float(input("Enter the length of a cylinder:"))
area = radius*radius*math.pi
print("The area is", area)
print("The volume is", area*length)
| true |
502edac5b8c26c2ef81609d497f8084db91f0401 | zhaphod/ProjectEuler | /Python/proj_euler_problem_0001.py | 651 | 4.15625 | 4 | '''
Problem 1
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples
of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
sum = 0
def EulerProblem0001():
global sum
for i in range(1, 1000):
if i % 5 == 0 or i % 3 == 0:
print(i, end=" ")
sum += i
print("Sum with for loop = " + str(sum))
sum = 0
sum += 3 * (333 * 334 / 2)
sum += 5 * (199 * 200 / 2)
sum -= 15 * (66 * 67 / 2)
print("Sum with closed form = " + str(sum))
if __name__ == "__main__":
print("Euler problem one")
EulerProblem0001()
print("Sum = " + str(sum))
| true |
62cb1a8ac24e4382015eeb70a42a32e1087a7809 | Edwar2-2/PythonFullCoursexD | /07Ejercicios/Ejercicio1.py | 343 | 4.25 | 4 | """
Ejercicio 1.
- Crear variables una ""pais" y otra "continente"
- Mostrar su valor por pantalla (imprimir)
- Poner un comentario diciendo el tipo de dato
"""
pais = "Mexico" #String
continente = "America" #String
year = 2021 #Integer
print(pais)
print(continente)
print("{} - {} - {}".format(pais,continente,str(year)))
| false |
c65e8e6d41ac120b28cf31d9f9dcf4f74d78c45e | leonguevara/DaysInAMonth_Python | /main.py | 930 | 4.625 | 5 | # main.py
# DaysInAMonth_Python
#
# This program will give you the number of days of any given month of any given year
#
# Python interpreter: 3.6
#
# Author: León Felipe Guevara Chávez
# email: leon.guevara@itesm.mx
# date: May 31, 2017
#
# We ask for and read the month's number
month = int(input("Give me the number of the month (1 - 12): "))
# We ask for and read the year's number
year = int(input("Give me the number of the year (XXXX): "))
# We find out the number of days that last this particular month
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
daysOfMonth = 31
elif month == 4 or month == 6 or month == 9 or month == 11:
daysOfMonth = 30
else:
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
daysOfMonth = 29
else:
daysOfMonth = 28
# We display our findings
print("The numbers of days in this month is " + str(daysOfMonth))
| true |
e970e7280e098f8ba6d704bd1157320a55fa95a8 | jungjung917/Coderbyte_challenges | /easy/solutions/LetterChanges.py | 735 | 4.15625 | 4 | def LetterChanges(str):
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
vowels = "aeiou"
str_replace = ""
for index, letter in enumerate(str):
print index
if letter in letters:
if letter.lower() == 'z':
str = str[:index] + chr(ord(letter)-25) + str[index+1:]
else:
str = str[:index] + chr(ord(letter) + 1) + str[index+1:]
print str
for index,letter in enumerate(str):
if letter in vowels:
str = str[: index] + letter.upper() + str[index+1:]
return str
# keep this function call here
# to see how to enter arguments in Python scroll dohello*3")
print LetterChanges("a bcdefghijklmnopqrstuvwxyz123")
| false |
75972d8413cedaba4efe98bc5c28bbfed5c093ca | jungjung917/Coderbyte_challenges | /easy/solutions/ThirdGreatest.py | 1,142 | 4.5 | 4 | """
Using the Python language, have the function ThirdGreatest(strArr) take the array of strings stored in strArr and return the third largest word within in. So for example: if strArr is ["hello", "world", "before", "all"] your output should be world because "before" is 6 letters long, and "hello" and "world" are both 5, but the output should be world because it appeared as the last 5 letter word in the array. If strArr was ["hello", "world", "after", "all"] the output should be after because the first three words are all 5 letters long, so return the last one. The array will have at least three strings and each string will only contain letters.
"""
def ThirdGreatest(strArr):
len_dic = {}
for index, word in enumerate(strArr):
len_dic[index] = len(word)
for i in range(0,2):
max_value = max(len_dic.values())
for k,v in len_dic.items():
if v == max_value:
del len_dic[k]
break
keys = len_dic.keys()
values = len_dic.values()
max_index = values.index(max(len_dic.values()))
return strArr[keys[max_index]]
print ThirdGreatest(["one","two","three"])
| true |
bd5801f9768c16fdf16d9992dd47f5506cbdedcc | jungjung917/Coderbyte_challenges | /medium/solutions/StringScramble.py | 572 | 4.375 | 4 | """
the function StringScramble(str1,str2) take both parameters being passed and return the string true if a portion of str1 characters can be rearranged to match str2, otherwise return the string false. For example: if str1 is "rkqodlw" and str2 is "world" the output should return true. Punctuation and symbols will not be entered with the parameters.
"""
def StringScramble(str1,str2):
for letter in str2.lower():
if letter not in str1.lower():
return "false"
return "true"
print StringScramble("cdore","coder")
print StringScramble("ctiye","colrd")
| true |
26e0e5220c163bfc0631b25aabfb7395f986c941 | Endlex-net/practic_on_lintcode | /reverse-linked-list/code.py | 600 | 4.21875 | 4 | #-*-coding: utf-8 -*-
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the reversed linked list.
Reverse it in-place.
"""
def reverse(self, head):
# write your code here
now = head
temp = None
while now:
next = now.next
now.next = temp
temp = now
now = next
return temp | true |
979435e090e41bff2066755c1c0d65a4c33298cf | aryajayan/python-training | /day3/q2.py | 262 | 4.375 | 4 | # Given a dictionary {"name": "python", "ext": "py", "creator": "guido"}, print both keys and values.
d={"name": "python", "ext": "py", "creator": "guido"}
for key, value in d.items():
print(key, value)
# --Output--
# name python
# ext py
# creator guido | true |
cd8a38d26c03dd73fde61e337aecd5c02b7761b5 | aryajayan/python-training | /day3/q4.py | 485 | 4.25 | 4 | # Guessing Game. Accept a guess number and tell us if it's higher or less than the hardcoded number
num=10
guess_num=int(input("Guess the number : "))
if guess_num>num:
print("higher than the given number")
elif guess_num<num:
print("lower than the given number")
else:
print("You got the number")
# --Output--
# Guess the number : 6
# lower than the given number
# Guess the number : 29
# higher than the given number
# Guess the number : 10
# You got the number | true |
2aa9a4c79909747d5b6d9aafbbce8e2760e6331c | LinaSaidane/python_formation | /Boucles.py | 2,149 | 4.25 | 4 | """
les boucles: moyen de répéter un certain nbr de fois des instructions de notre
programme
"""
# Boucle :
# Programmer la table de multiplication par 7
nb = 10
print("1 *", nb , "=" , 1 * nb)
print("2 *", nb , "=" , 2 * nb)
print("3 *", nb , "=" , 3 * nb)
print("4 *", nb , "=" , 4 * nb)
print("5 *", nb , "=" , 5 * nb)
print("6 *", nb , "=" , 6 * nb)
print("7 *", nb , "=" , 7 * nb)
print("8 *", nb , "=" , 8 * nb)
print("9 *", nb , "=" , 9 * nb)
print("10 *", nb , "=" , 10 * nb)
# bloc d'instructions "while :
nb = input("Saisissez le nombre")
i = 0 #notre variable compteur
while i < 10:
print(i + 1, "*", nb, "=",(i + 1) * nb)
i += 1 #incrémente i de 1 à chaque tour de boucle
""" ne pas oublier d'incrémenter i sinon boucle infinie
puisque la valeur de i n'est (dans cet exemple jamais supérieure à 10
et la condition du while toujours vraie"""
# Pour arrêter une boucle ctrl + C
# Boucle for : travaille sur des séquences, les chaines de caractères sont des séquences de caractères
# construction : for element in sequence:
# element est une variable créee par le for
# exemple :
chaine = "Bonjour les ZER0S"
for lettre in chaine:
print(lettre)
# pas besoin d'incrémenter la variable lettre. Python se charge de l'incrémentation
# un grand avantage de l'instruction for
# in ne peut fonctionner qu'avec for
chaine = "Bonjour les ZER0S"
for lettre in chaine:
if lettre in "AEIOUYaeiouy": # lettre est une voyelle
print(lettre)
else: # lettre est une consonne
print("*")
# mot-clé : break --> interrompt une boucle
while 1: # 1 est toujours vrai -> boucle infinie
lettre = input (" Tapez 'Q' pour quitter : ")
if lettre =="Q":
print("Fin de la boucle")
break
# mot-clé : continue --> continue une boucle en repartant du while ou for
i = 1
while i < 20:
if i % 3 == 0:
i += 4
print ("On incrémente i de 4. i est maintenant égale à", i)
continue # on retourne au while sans exécuter les autres lignes
print("La variable i =", i)
i += 1 # Dans le cas classique on ajoute 1 à i | false |
69110ed6b4e2943ca3cb7ca4e56d5ce884b3bf60 | sumedhkhodke/waiver_assignment | /eas503_test.py | 2,239 | 4.53125 | 5 | """
------------
INSTRUCTIONS
------------
The file 'Students.csv' contains a dump of a non-normalized database. Your assignment is to first normalize the database
and then write some SQL queries.
To normalize the database, create the following four tables in sqlite3 and populate them with data from 'Students.csv'.
1) Degrees table has one column:
[Degree] column is the primary key
2) Exams table has two columns:
[Exam] column is the primary key column
[Year] column stores the exam year
3) Students table has four columns:
[StudentID] primary key column
[First_Name] stores first name
[Last_Name] stores last name
[Degree] foreign key to Degrees table
4) StudentExamScores table has four columns:
[PK] primary key column,
[StudentID] foreign key to Students table,
[Exam] foreign key to Exams table ,
[Score] exam score
Call the normalized database: 'normalized.db'.
Q1:
Write an SQL statement that selects all rows from the `Exams` table and sorts the exams by year and then exam name
Output columns: exam, year
Q2:
Write an SQL statement that selects all rows from the `Degrees` table and sorts the degrees by name
Output column: degree
Q3:
Write an SQL statement that counts the numbers of gradate and undergraduate students
Output columns: degree, count_degree
Q4:
Write an SQL statement that calculates the exam averages for exams and sort by the averages in descending order.
Output columns: exam, year, average
round to two decimal places
Q5:
Write an SQL statement that calculates the exam averages for degrees and sorts by average in descending order.
Output columns: degree, average
round to two decimal places
Q6:
Write an SQL statement that calculates the exam averages for students and sorts by average in descending order. Show only the top 10 students.
Output columns: first_name, last_name, degree, average
round to two decimal places
More instructions:
1) All work must be done in Python.
2) You CANNOT use 'pandas'.
3) You CANNOT use the 'csv' module to read the file
3) All SQL queries must be executed through Python.
4) Neatly print the output of the SQL queries using Python.
Hint:
Ensure to strip all strings so there is no space in them
"""
| true |
022d70630593eeccb4082c9378465f0551f39f9c | bhavesh-20/Genetic-Algorithm | /Sudoku/random_generation.py | 2,493 | 4.1875 | 4 | import numpy as np
"""Function which generates random strings for genetic algorithm, each string
is a representation of genetic string used in the algorithm. Randomness is used in a smart way to remove
the chance of each row having duplicates in sudoku and also trying to minimise conflicts with columns,
hence the generated random string doesn't have any duplicates row-wise and minimum duplicates column-wise"""
def random_generation():
l = ["x8xxxxx9x","xx75x28xx","6xx8x7xx5","37xx8xx51","2xxxxxxx8","95xx4xx32","8xx1x4xx9","xx19x36xx",
"x4xxxxx2x"]
rand_string = []
number_set = {1,2,3,4,5,6,7,8,9}
columns = []
for _ in range(9):
columns.append(set())
for i in l:
for j in range(9):
if i[j]!='x':
columns[j].add(int(i[j]))
for i in l:
s = ''
n = list(number_set - set([int(x) for x in i if x!='x']))
for column in range(9):
possible = set(n)
if i[column]!='x':
s+=i[column]
else:
a = list(possible - columns[column])
if len(a) == 0:
r = np.random.randint(0, len(n))
r = n[r]
n.remove(r)
s+=str(r)
else:
r = np.random.randint(0, len(a))
r = a[r]
n.remove(r)
s+=str(r)
rand_string.append(s)
rand_string = ''.join(x for x in rand_string)
return rand_string
"""Function which generates random strings for genetic algorithm, each string
is a representation of genetic string used in the algorithm. Randomness is used in a smart way to remove
the chance of each row having duplicates in sudoku, hence the generated random string doesn't have any duplicates
row-wise"""
def random_generation2():
l = ["x8xxxxx9x","xx75x28xx","6xx8x7xx5","37xx8xx51","2xxxxxxx8","95xx4xx32","8xx1x4xx9","xx19x36xx",
"x4xxxxx2x"]
rand_string = []
number_set = {1,2,3,4,5,6,7,8,9}
for i in l:
a = set([int(x) for x in i if x!='x'])
a = np.array(list(number_set - a))
np.random.shuffle(a)
a, k, string = list(a), 0, ""
for j in i:
if j=='x':
string+=str(a[k])
k+=1
else:
string+=j
rand_string.append(string)
rand_string = ''.join(x for x in rand_string)
return rand_string | true |
8c3267e725eb737b3335f0ff4d94977e1a90be59 | ViMitre/sparta-python | /1/classes/car.py | 797 | 4.15625 | 4 | # Max speed
# Current speed
# Getter - return current speed
# Accelerate and decelerate methods
# Accelerate past max speed
# What if it keeps braking?
class Car:
def __init__(self, current_speed, max_speed):
self.current_speed = current_speed
self.max_speed = max_speed
def get_speed(self):
return self.current_speed
def accelerate(self, speed):
new_speed = self.current_speed + speed
self.current_speed = min(self.max_speed, new_speed)
def decelerate(self, brake):
new_speed = self.current_speed - brake
self.current_speed = max(0, new_speed)
my_car = Car(60, 200)
my_car.accelerate(20)
print(my_car.get_speed())
my_car.decelerate(120)
print(my_car.get_speed())
my_car.accelerate(400)
print(my_car.get_speed())
| true |
25bd3427740a8c0d28c86d307a6c7b8911159002 | pauldepalma/RA | /A:BasicPython/ex7.py | 459 | 4.1875 | 4 |
def evenOrOdd(num):
if num % 2 == 0: #modulus operator
return True
return False
def main():
while (True):
print("Enter an integer")
num = int(input())
if evenOrOdd(num):
print(str(num) + " is even")
else:
print(str(num) + " is odd")
print("Enter Another (y/n)")
more = input()
if more == 'n':
break
main()
| false |
e3156589342632ac3996d4787be30275f7b9b062 | standrewscollege2018/2021-year-11-classwork-ethanbonis | /Zoo.py | 245 | 4.28125 | 4 | #This code will ask for your age and based on this info, will ask -
#you to pay the child price or to pay the adult price.
CHILD_AGE = 13
age = int(input("What is your age?"))
if age <= CHILD_AGE:
print("child")
else:
print("adult")
| true |
10dbdc70ade2b6ba83a7b1233d70e636d8747626 | ERAN1202/python_digital_net4u | /lesson_1/Final_Pro.Func.py | 2,213 | 4.15625 | 4 | '''create a menu:
a. IP system?
b. DNS system?
a
====
1. search for IP address from a list
2. add IP address to a list
3. delete IP address to a list
4. print all the IPs to the screen
b
===
1. serach for URL from a dictionary
2. add URL + IP address to a dictionary
3. delete URL from a dictionary
4.update the IP address of specific URL
5. print all the URL:IP to the screen'''
from time import sleep
def menu():
while(True):
choice_1=input("Menu:\n------------\na. IPSystem\nb. DNS System\n")
if (choice_1 == "a"):
choice_2 = input("Menu IP System:\n-----------\n1.search IP\n2.add IP\n3.delete IP\n4.Print all IP ")
if choice_2 == "1":
search_ip()
elif choice_2 == "2":
add_ip()
elif choice_2 == "3":
delete_ip()
elif choice_2 == "4":
print_IPs()
elif (choice_1 == "b"):
choice_3 = input("Menu DNS system:\n--------------\n1.search URL\n2.add IP+URL to dict.\n3.delete URL from dict.\n4.update IP address spec. URL\n5.print all the URL:IP to the screen")
if choice_3 == "1":
search_URL()
elif choice_3 == "2":
add_ip_URL()
elif choice_3 == "3":
delete_URL()
elif choice_3 == "4":
update_IPs()
elif choice_3 == "5":
print_URL()
else:
print("Enter a/b only")
continue
exit=input("Do you wnat to exit? yes/no")
if (exit == "yes"):
print("ByeBye")
break
def search_ip():
print("1")
def add_ip():
ip_added = input("IP add is : ")
print(str(ip_added))
filename = "C:/Users/eranb/Desktop/IP.txt"
file = open(filename, "a")
file.write(ip_added)
file.close()
file = open(filename, "r")
file.read()
file.close()
def delete_ip():
print("3")
def print_IPs():
print("4")
def search_URL():
print("1")
def add_ip_URL():
print("2")
def delete_URL():
print("3")
def update_IPs():
print("4")
def print_URL():
print("5")
menu()
| true |
abb2d0d74f582217f9a107b14ded58a7ed0719f1 | AvivSham/LeetCodeQ | /Easy/ReverseWordsInString.py | 373 | 4.21875 | 4 | def reverse_words(s: str) -> str:
s = s.split()
s.reverse()
return " ".join([i for i in s if i is not ""])
def reverse_words_v2(s: str) -> str:
return " ".join(reversed(s.split()))
def reverse_words_v3(s: str) -> str:
return " ".join(s.strip().split()[::-1])
if __name__ == '__main__':
print(reverse_words(" hello world! "))
| false |
cdd3dbd0d964d9d914893f60a95ed0a79129a626 | AvivSham/LeetCodeQ | /Easy/DistanceBetweenBusStops.py | 413 | 4.125 | 4 | from typing import List
def distance_between_bus_stops(distance: List[int], start: int, destination: int) -> int:
clockwise = sum(distance[min(start, destination):max(start, destination)])
counter_clockwise = sum(distance) - clockwise
return min(clockwise, counter_clockwise)
if __name__ == '__main__':
print(distance_between_bus_stops(distance=[1, 2, 3, 4], start=0, destination=1)) | true |
99fc98fe21ae10439644ff02e044d377e5a346c1 | rafawelsh/CodeGuildLabs | /python/Python labs/9.unit_converter.py | 254 | 4.1875 | 4 | #9.unit_converter.py
# ft = int(input("What is the distance in feet?: "))
# m = round((ft * 0.3048),5)
#
# print(ft,"ft is", m, "m")
def conversion(disntance, meter):
disntance = int(input("What is the distance? "))
unit = input("What are the units? ")
| true |
44131bea35c8b97c549b969a88593c770ad12418 | camillatoniatto/logica-da-programacao-python | /repeticao/while4.py | 392 | 4.1875 | 4 | #Ler um número N qualquer menor ou igual a 50 e apresentar o valor obtido da multiplicação
#sucessiva de N por 3 enquanto o produto for menor que 250 (N*3, N*3*3, N*3*3*3; etc)
numero=int(input("Insira um numero menor ou igual 50: "))
i=3
while numero<=50:
produto = numero * i
i = i * 3
if produto<=250:
print(produto)
else:
print("O número inserido foi maior que 50")
| false |
e4692682f070ad1e3ed787efbd8811d68d74d253 | a62mds/exercism | /python/linked-list/linked_list.py | 1,841 | 4.125 | 4 | # Skeleton file for the Python "linked-list" exercise.
# Implement the LinkedList class
class Node(object):
def __init__(self, value, next=None, prev=None):
self.value = value
self.next = next
self.prev = prev
def __str__(self):
return '{}'.format(self.value)
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
self.current = self.head
return self
def next(self):
if self.current is None:
raise StopIteration
else:
curr = self.current
self.current = self.current.next
return curr.value
def __len__(self):
l = 0
for node in self:
if node is None: break
else: l += 1
return l
def __str__(self):
return '<->'.join(str(node) for node in self)
def push(self, value):
if self.tail is None:
self.head = self.tail = Node(value)
else:
new_tail = Node(value)
self.tail.next = new_tail
new_tail.prev = self.tail
self.tail = new_tail
def pop(self):
old_tail = self.tail
self.tail = self.tail.prev
if self.tail is not None: self.tail.next = None
else: self.head = self.tail
return old_tail.value
def shift(self):
old_head = self.head
self.head = self.head.next
if self.head is not None: self.head.prev = None
else: self.tail = self.head
return old_head.value
def unshift(self, value):
if self.head is None:
self.head = self.tail = Node(value)
else:
new_head = Node(value)
self.head.prev = new_head
new_head.next = self.head
self.head = new_head
| true |
69c9988c1a00e304da3a71ba9e589142db2c17d9 | RCTom168/Intro-to-Python-1 | /Intro-Python-I-master/src/09_dictionaries.py | 2,180 | 4.53125 | 5 | """
Dictionaries are Python's implementation of associative arrays.
There's not much different with Python's version compared to what
you'll find in other languages (though you can also initialize and
populate dictionaries using comprehensions just like you can with
lists!).
The docs can be found here:
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
For this exercise, you have a list of dictionaries. Each dictionary
has the following keys:
- lat: a signed integer representing a latitude value
- lon: a signed integer representing a longitude value
- name: a name string for this location
"""
waypoints = [
{
"lat": 43,
"lon": -121,
"name": "a place"
},
{
"lat": 41,
"lon": -123,
"name": "another place"
},
{
"lat": 43,
"lon": -122,
"name": "a third place"
}
]
# Add a new waypoint to the list
# YOUR CODE HERE
waypoints.append({
"lat": 41,
"lon": -124,
"name": "that other place"
})
# Modify the dictionary with name "a place" such that its longitude
# value is -130 and change its name to "not a real place"
# Note: It's okay to access the dictionary using bracket notation on the waypoints list.
# YOUR CODE HERE
# The "a place" value takes up the 0 slot
waypoints[0]["lat"] = 43
waypoints[0]["lon"] = -130
waypoints[0]["name"] = "not a real place"
# Write a loop that prints out all the field values for all the waypoints
# YOUR CODE HERE
for waypoint in waypoints:
for v in waypoint.values():
print(v)
# Lecture Example
# input letters will be a list of single character
# lowercase strings (a-z)
def mapping(letters):
# create an empty dictionary
result = {}
# loop through the input provided
for letter in letters:
# add letter to the dictionary
# make the letter uppercase for the value
# leave lowercase for the key
result[letter] = letter.upper()
# return value
return result
# dictionary with key-values where the
# key is the lowercase letter from the input
# and value is the correlating uppercase letter
print(mapping(["a", "b", "e", "g"])) | true |
97bc7c2bc0b4e66bffdc567d062078282cc4053a | MurielSpot/python_note | /py/網易云課程(瘋狂的python).py | 2,273 | 4.15625 | 4 | '''
網易雲課程:《瘋狂的python:快速入門精講》略略略😀
😋😑😆😘🙄
'''
print('''
《英雄无敌》之英雄降临
1. 开局玩家起名字。
2. 列表初始化为英雄属性、名字、血值、攻击力、防御力。
3. 判断名字是否为空,默认为“玩家一”。
4. 判断英雄行动方向。
''')
print('''
***
Hero is me! Welcome to visit my world!
You must obey my world\'s rules, or you will be expelled~~
***
''')
#name = input('input your name:')
name='princess'
if not name:#name为假,name如果没有值就是假,否则为真
name='little cute guy'
print('''
***
I let you off easy for your insubordination this time!!!
Your name is specified as \'little cute guy\'.
***
''')
hp=100
visitorList=[name,hp]
print("your name:",visitorList[0],",your hp:",visitorList[1])
print("\n切片name[0:1],看看有那些字符被输出了:",name[0:1])
print("\n列表解析")
print('''
***
Now I will give you a mathematical problem:
please print all the natural numbers no more than 100 that can be mutiples of 3 or 5, and compute the sum of all the number.
***
''')
nums = []
for i in range(1,100):
if i%3==0 or i%5:
nums.append(i)
print('all the nums have been stored in the list \'nums\':',nums)
print('sum函数,你给它一个列表可以自动求和,sum(nums)=',sum(nums))
print('''
***
but you can use list comprehensions:
在需要改变列表而不是需要新建某列表时,可以用列表解析;
列表解析的表达式为:
[expr for iter_var in iterable]
[expr for iter_var in iterable if cond_expr]
***
''')
#[i*10 for i in range(10)]
#sum函数总用不了。。。TypeError: 'int' object is not callable
#之後試又能用了,可能是上次用的時候定義過sum變量,雖然這個sum變量在運行sum函數的時候已經刪掉了,但是好像仍然對程序產生了影響。
print(sum([i for i in range(10) if i%3==0 or i%5 ==0]))
print("\nopen a file , open('this.log','w'),this file is in SpiderFiles")
open('this.log','w')
open('this.log','w').write('abc')
name2='adddd'
print('\nname2 is:%s'%name2)
import os
if os.path.isfile('this.log'):
print('this.log file exists\n')
| false |
1ba1bd1ed3f48dc190b87e8225f4a0d51b907d62 | Raghavendrajoshi45/python | /faulty.py | 690 | 4.28125 | 4 | print("enter your number")
num1=int(input())
print("enter your number")
num2=int(input())
print('enter your choice '+' +,-,*,/,%')
num3=(input())
if (num1==45 and num2==3 and num3=='+'):
print("100")
elif (num1==45 and num2==3 and num3=='%'):
print("2")
elif (num1==45 and num2==3 and num3=='-'):
print(6)
elif num3 == '*':
num4 = num1 * num2
print(num4)
elif num3 == '+':
plus = num2 + num1
print(plus)
elif num3 == '/':
Dev = num2 / num1
print(Dev)
elif num3 == '-':
Dev = num2 - num1
print(Dev)
elif num3 == '%':
percent = num2 % num1
print(percent)
else:
print("Error! Please check your input") | false |
8b0f1b43a3016813b55ba8850d1f40c78b46b0d1 | krishnanandk/kkprojects | /regular expression/demo3.py | 1,078 | 4.125 | 4 | #quantifiers
# quantifiers
# x='a+' a including group
# x='a*' count including zero number of a
# x='a?' count a as each including zero no of a
# x='a{2}' 2 no of a position
# x='a{2,3}' minimum 2 a and maximum 3 a
# x='^a' check starting with a
# x='a$' check ending with a
import re
# x = "a+" #group of a
# r="aaa abc aaaa cga"
# matcher = re.finditer(x,r)
# for match in matcher:
# print("match available at", match.start())
# print("group", match.group())
# x = "a*" #count includiing zero number of a
# r="aaa abc aaaa cga"
# matcher = re.finditer(x,r)
# for match in matcher:
# print("match available at", match.start())
# print("group", match.group())
# x = "a?" #count as each includiing zero number of a
# r="aaa abc aaaa cga"
# matcher = re.finditer(x,r)
# for match in matcher:
# print("match available at", match.start())
# print("group", match.group())
x = "a{3}" #number of position
r="aaa abc aaaa cga"
matcher = re.finditer(x,r)
for match in matcher:
print("match available at", match.start())
print("group", match.group())
| false |
1b09af7656619a1281f588e050f722e326edca1b | krishnanandk/kkprojects | /functions/demo.py | 645 | 4.21875 | 4 | #inbuild function
#print()
#input()
#type
#normal syntax to create a function
#def functionname(arguments):
#function definition
#function call: #using fn name
#3methods
#1. Functions without an argument and no return type
#2. Function with arguments and no return type
#3. Function with arguments and return type
#1.
#def add():
# num1=int(input("enter number1"))
# num2=int(input("enter number2"))
# sum=num1+num2
# print(sum)
#add()
#2.
# def addition(num1,num2):
# sum=num1+num2
# print(sum)
# addition(30,50)
#3.
# def sumN(num1,num2):
# sum=num1+num2
# return sum
# data=sumN(15,25)
# print(data) | true |
a61f578bb01b0c574a3ba130db048990c2712189 | excaliware/python | /lcm.py | 1,328 | 4.28125 | 4 | """
Find the lowest common multiple (LCM) of the given numbers.
"""
import math
"""
Find the prime factors of the given number.
"""
def find_factors(n):
factors = []
# First, find the factor 2, if any.
while n % 2 == 0:
n = n // 2
factors.append(2)
# From now on, check odd numbers only.
d = 3
while d <= math.sqrt(n):
# Divide by the factor while it is possible.
while n % d == 0:
n = n // d
factors.append(d)
d = d + 2
if n > 1:
factors.append(n)
return factors
"""
Find the lowest common multiple (LCM) of the given numbers.
"""
def calc_lcm(nums):
ndict = {}
result = {}
for n in nums:
for f in find_factors(n):
if ndict.get(f) == None:
ndict[f] = 1
else:
ndict[f] += 1
for f in ndict.keys():
if result.get(f) == None:
result[f] = ndict[f]
elif ndict[f] > result[f]:
result[f] = ndict[f]
# New dict for the next number, if any.
ndict = {}
p = 1
for f in result.keys():
p *= math.pow(f, result[f])
return int(p)
# An alternative approach.
def lcm(a, b):
return a * b / gcd(a, b)
if __name__ == "__main__":
nums = [12, 18, 5, 3, 10]
lcm = calc_lcm(nums)
print("The LCM of %s is %d" % (nums, lcm))
# Check the correctness of the result.
for n in nums:
if lcm % n != 0:
print("%d / %d = %d" % (lcm, n, lcm / n))
| true |
5d83d1235d048388394af8a6e56bf55c289c7957 | johnyijaq/Pyhton-For-Everybody | /Course 3. Using Python to Access Web Data/Week 2. Regular Expressions.py | 2,782 | 4.5625 | 5 | Chapter 11 Assignment: Extracting Data With Regular Expressions
# Finding Numbers in a Haystack
# In this assignment you will read through and parse a file with text and
# numbers. You will extract all the numbers in the file and compute the sum of
# the numbers.
# Data Files
# We provide two files for this assignment. One is a sample file where we give
# you the sum for your testing and the other is the actual data you need to
# process for the assignment.
# Sample data: http://python-data.dr-chuck.net/regex_sum_42.txt
# (There are 87 values with a sum=445822)
# Actual data: http://python-data.dr-chuck.net/regex_sum_201873.txt
# (There are 96 values and the sum ends with 156)
# These links open in a new window. Make sure to save the file into the same
# folder as you will be writing your Python program. Note: Each student will
# have a distinct data file for the assignment - so only use your own data file
# for analysis.
# Data Format
# The file contains much of the text from the introduction of the textbook
# except that random numbers are inserted throughout the text. Here is a sample
# of the output you might see:
'''
Why should you learn to write programs? 7746
12 1929 8827
Writing programs (or programming) is a very creative
7 and rewarding activity. You can write programs for
many reasons, ranging from making your living to solving
8837 a difficult data analysis problem to having fun to helping 128
someone else solve a problem. This book assumes that
everyone needs to know how to program ...
'''
# The sum for the sample text above is 27486. The numbers can appear anywhere
# in the line. There can be any number of numbers in each line (including none).
# Handling The Data
# The basic outline of this problem is to read the file, look for integers using
# the re.findall(), looking for a regular expression of '[0-9]+' and then
# converting the extracted strings to integers and summing up the integers.
import re
fhand = open("regex_sum_378376.txt")
sum = 0
for line in fhand:
line = line.rstrip()
numbers = re.findall('[0-9]+', line)
if len(numbers) > 0:
for number in numbers:
sum= sum + int(number)
print(sum)
***********************************************
#Alternative
import re
#Extracting Digits and Summing them
fhand = open("regex_sum_378376.txt")
total = []
for line in fhand:
line = line.rstrip()
numbers = re.findall("([0-9]+)", line)
if len(numbers) < 1 : continue
for number in numbers:
num = float(number)
total.append(num)
#Alternative
#for i in range(len(numbers)):
#num = float(numbers[i])
#total.append(num)
print(sum(total))
| true |
491bee39b76c5252187bc734dddd247aa017ed7d | thomasyu929/Leetcode | /Tree/symmetricTree.py | 1,436 | 4.21875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 1 Recursive
# def isSymmetric(self, root: TreeNode) -> bool:
# if not root:
# return True
# return self.isLRSymmetric(root.left, root.right)
# def isLRSymmetric(self, left, right):
# if not left and not right:
# return True
# if (not left and right) or (left and not right) or (left.val != right.val):
# return False
# return self.isLRSymmetric(left.left, right.right) and self.isLRSymmetric(left.right, right.left)
# 2 Iteration
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
queue1, queue2 = [root.left], [root.right]
while queue1 and queue2:
node1, node2 = queue1.pop(), queue2.pop()
if not node1 and not node2:
continue
if (not node1 and node2) or (node1 and not node2):
return False
if node1.val != node2.val:
return False
queue1.append(node1.left)
queue1.append(node1.right)
queue2.append(node2.right)
queue2.append(node2.left)
return True | true |
e7c2a3d268ff5f03cb453656cf931a91a9e7a529 | ccmaf/Python-Stuff | /listfun.py | 265 | 4.28125 | 4 | #goal: make a list from user input and print out any
#number from the list that is < 5
print("please enter 3 numbers.")
n1 = input("n1: ")
n2 = input("n2: ")
n3 = input("n3: ")
list = [int(n1),int(n2),int(n3)]
for element in list:
if element < 5:
print(element) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.