blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
8a91d4bf14c9215077834ed74748ee2e6b8fa163
|
TheHugeHaystack/Solucion-a-problemas-con-Programacion
|
/temperature.py
| 1,636
| 4.65625
| 5
|
#Code by: rghost Academic Purposes
#This code is to do the following:
# Write a program that will prompt the user for a temperature asking the user between Fahrenheit and Celsius;
# then, convert it to the other. You may recall that the formula is C = 5 ∗ (F − 32)/9.
# Modify the program to state whether or not water would boil at the temperature given.
import string
if __name__ == '__main__':
c = True;
while c:
t=0;
opt = input("Please enter if you would like to convert from Celsius or Fahrenheit to the other (C/F): ");
if opt.lower() == "c":
t = input("Enter your temperature in Celsius ");
print("A temperature of " + str(t) + " degrees Celsius is "+ str(float(t)*(9/5)+32) +" in Fahrenheit");
if float(t)*(9/5)+32 >= 100:
print ("Water boils at this temperature (under typical conditions).")
else:
print("Water does not boil at this temperature (under typical conditions).")
elif opt == "f":
t = input("Enter your temperature in Fahrenheit ");
print("A temperature of " + str(t) + " degrees Fahrenheit is "+ str((float(t)-32)*5/9) +" in Celsius");
if (float(t)-32)*5/9 >= 212:
print ("Water boils at this temperature (under typical conditions).")
else:
print("Water does not boil at this temperature (under typical conditions).")
else:
print("Not a valid answer");
a = input("Would you like to enter another temperature? Y/AnyKey* ")
if a.lower() != "y":
break;
| true
|
69ba50bcd982901a944ae4c5be100dce7ceebe79
|
mrinfosec/cryptopals
|
/c10.py
| 2,265
| 4.15625
| 4
|
#!/usr/bin/python
# Implement CBC mode
# CBC mode is a block cipher mode that allows us to encrypt irregularly-sized
# messages, despite the fact that a block cipher natively only transforms
# individual blocks.
#
# In CBC mode, each ciphertext block is added to the next plaintext block before
# the next call to the cipher core.
#
# The first plaintext block, which has no associated previous ciphertext block, is
# added to a "fake 0th ciphertext block" called the initialization vector, or IV.
#
# Implement CBC mode by hand by taking the ECB function you wrote earlier, making
# it encrypt instead of decrypt (verify this by decrypting whatever you encrypt to
# test), and using your XOR function from the previous exercise to combine them.
#
# The file here is intelligible (somewhat) when CBC decrypted against
# "YELLOW SUBMARINE" with an IV of all ASCII 0 (\x00\x00\x00 &c)
#
# Don't cheat.
# Do not use OpenSSL's CBC code to do CBC mode, even to verify your results.
# What's the point of even doing this stuff if you aren't going to learn from it?
# pseudocode
#
# Encrypt:
# Assign IV vector
# XOR together
# ECB first block
# XOR together
# ECB second block
# repeat until done
# Decrypt:
# Read last block
# ECB decrypt it
# Read previous block
# XOR against plaintext
# Continue until done
from Crypto.Cipher import AES
from base64 import b64decode
aeskey = 'YELLOW SUBMARINE'
ciphertext = b64decode(open('10.txt', 'r').read())
iv = chr(0)*16
if len(ciphertext) % 16 != 0:
raise Exception('String is not a list of 16-byte blocks')
def xor(s1, s2):
result = ''
if len(s1) != len(s2):
raise Exception('Strings to XOR are different lengths')
for i in range(len(s1)):
result += chr(ord(s1[i]) ^ ord(s2[i]))
return result
def blockify(s, blocklen):
return [s[i:i+blocklen] for i in range(0, len(s), blocklen)]
def aescbc_decrypt(iv, s, key):
aesobj = AES.new(key, AES.MODE_ECB)
blocks = blockify(s, 16)
blocks.insert(0,iv)
ret = []
for i in range(1, len(blocks), 1):
a = aesobj.decrypt(blocks[len(blocks)-i])
b = blocks[len(blocks)-i-1]
ret.insert(0,xor(a, b))
return ''.join(ret)
if __name__ == '__main__':
print aescbc_decrypt(iv, ciphertext, aeskey)
| true
|
8be0d2e9a8d67dcad48786a68b37d216bee1b28d
|
cdean00/PyNet
|
/pynetweek4_excersise3.py
| 1,361
| 4.21875
| 4
|
"""
Week 4, Excersise 3
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
III. Create a program that converts the following uptime strings to a time in seconds.
uptime1 = 'twb-sf-881 uptime is 6 weeks, 4 days, 2 hours, 25 minutes'
uptime2 = '3750RJ uptime is 1 hour, 29 minutes'
uptime3 = 'CATS3560 uptime is 8 weeks, 4 days, 18 hours, 16 minutes'
uptime4 = 'rtr1 uptime is 5 years, 18 weeks, 8 hours, 23 minutes'
For each of these strings store the uptime in a dictionary using the device name as the key.
During this conversion process, you will have to convert strings to integers. For these string to integer conversions use try/except to catch any string to integer conversion exceptions.
For example:
int('5') works fine
int('5 years') generates a ValueError exception.
Print the dictionary to standard output.
"""
uptime1 = 'twb-sf-881 uptime is 6 weeks, 4 days, 2 hours, 25 minutes'
uptime2 = '3750RJ uptime is 1 hour, 29 minutes'
uptime3 = 'CATS3560 uptime is 8 weeks, 4 days, 18 hours, 16 minutes'
uptime4 = 'rtr1 uptime is 5 years, 18 weeks, 8 hours, 23 minutes'
uptime1_weeks = uptime1[uptime1.find("weeks")-2]
uptime1_days = uptime1[uptime1.find("days")-2]
| true
|
aa7924e7483d1757d0ebf8e3b8ed6008f143060d
|
nilskingston/String-Jumble
|
/stringjumble.py
| 1,277
| 4.28125
| 4
|
"""
stringjumble.py
Author: Nils Kingston
Credit: Roger
Assignment:
The purpose of this challenge is to gain proficiency with
manipulating lists.
Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:
* With all letters in reverse.
* With words in reverse order, but letters within each word in
the correct order.
* With all words in correct order, but letters reversed within
the words.
Output of your program should look like this:
Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
string = input("Please enter a string of text (the bigger the better): ")
print('You entered "'+string+'". Now jumble it: ')
b = list(string)
b.reverse()
for x in b:
print(x, end="")
print()
words = string.split()
words.reverse()
for y in words:
print(y, end=" ")
print()
swim = string.split()
for w in swim:
f = list(w)
f.reverse()
print(''.join(f), end=" ")
| true
|
a60fd066512a2fe60e465b8556d046b344e94dc3
|
Kalpesh14m/Python-Basics-Code
|
/Basic Python/8 Function.py
| 756
| 4.34375
| 4
|
# The idea of a function is to assign a set of code, and possibly variables, known as parameters, to a single bit of text.
# You can think of it a lot like why you choose to write and save a program, rather than writing out the entire program every time you want to execute it.
#
# To begin a function, the keyword 'def' is used to notify python of the impending function definition, which is what def stands for.
# From there, you type out the name you want to call your function.
# It is important to choose a unique name, and also one that wont conflict with any other functions you might be using.
# For example, you wouldn't want to go calling your function print.
def example():
print('this code will run')
z = 3 + 9
print(z)
example()
| true
|
124765cd61ad7ba8518b3027531cfc5b535ad353
|
Kalpesh14m/Python-Basics-Code
|
/Basic Python/TKinter/33 Tkinter intro.py
| 1,268
| 4.3125
| 4
|
"""
The tkinter module is a wrapper around tk, which is a wrapper around tcl, which is what is used to create windows and graphical user interfaces.
Here, we show how simple it is to create a very basic window in just 8 lines.
We get a window that we can resize, minimize, maximize, and close! The tkinter module's purpose is to generate GUIs.
Python is not very popularly used for this purpose, but it is more than capable of doing it.
"""
"Simple enough, just import everything from tkinter."
from tkinter import *
"""
Here, we are creating our class, Window, and inheriting from the Frame class.
Frame is a class from the tkinter module.
(see Lib/tkinter/__init__)
Then we define the settings upon initialization. This is the master widget."""
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
"""The above is really all we need to do to get a window instance started.
Root window created.
Here, that would be the only window, but you can later have windows within windows.
"""
root = Tk()
"Then we actually create the instance."
app = Window(root)
"Finally, show it and begin the mainloop."
root.mainloop()
"The above code put together should spawn you a window that looks like:"
| true
|
5496f6f9ad1393c9f72bda44bdc0b24129de562b
|
smrmkt/project_euler
|
/problem_009.py
| 1,395
| 4.25
| 4
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
import numpy as np
import timeit
import problem_005
# slow
def loop(n):
for a in range(1, int(n/3)):
for b in range(a, int(n/2)):
c = n - (a + b)
if a + b < c:
continue
elif a**2 + b**2 == c**2:
return a, b, c
return None
# Pythagorean theorem
def pythagorean(n):
if n % 2 != 0: return None # n must be even
for l in range(3, int(n/2)):
if n/2 % l != 0: continue
s = n/(2*l) - l
if s < 0: continue
lf = np.array(problem_005.factorize(l, [0]*n))
sf = np.array(problem_005.factorize(s, [0]*n))
if l > s and (l-s)%2 == 1 and np.dot(lf, sf) == 0: # lf and sf must be coprime
print l, s
return l**2-s**2, 2*l*s, l**2+s**2
return None
if __name__ == '__main__':
print loop(1000)
print pythagorean(1000) # None because 1000 is not consist of primitive pythagorean theorem
print timeit.Timer('problem_009.loop(1000)', 'import problem_009').timeit(10)
print timeit.Timer('problem_009.pythagorean(1000)', 'import problem_009').timeit(10)
| false
|
b4b3bff8bf1922b70e8d3e38af1fbb69e30f318e
|
smrmkt/project_euler
|
/problem_001.py
| 822
| 4.21875
| 4
|
#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
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.
'''
import timeit
# slow
# simple loop
def loop(n):
t = 0
for i in range(1, n+1):
if i % 3 == 0 or i % 5 == 0:
t += i
return t
# fast
# calculate each numbers' sum and subtract common multiplier
def calc(n):
t03 = 3*(n/3)*(n/3+1)/2
t05 = 5*(n/5)*(n/5+1)/2
t15 = 15*(n/15)*(n/15+1)/2
return t03 + t05 - t15
if __name__ == '__main__':
print loop(999)
print calc(999)
print timeit.Timer('problem_001.loop(999)', 'import problem_001').timeit(100)
print timeit.Timer('problem_001.calc(999)', 'import problem_001').timeit(100)
| true
|
262e88040edd2f5724ed93e282e5945b07d52d01
|
ismailasega/Python_Cert_2019
|
/Python Basics/Q2.py
| 267
| 4.28125
| 4
|
#accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically.
str = input("type 7 names, then press enter: \n ")
names = str.split()
names.sort()
print("The names in alphabetic order:")
for name in names:
print(name)
| true
|
833c17c00e98c40643bf0db2a04220a48e77b7a2
|
ismailasega/Python_Cert_2019
|
/Data visualisation/CaseStudy1/Qn1.py
| 616
| 4.34375
| 4
|
# You are given a dataset, which is present in the LMS, containing the number of
# hurricanes occurring in the United States along the coast of the Atlantic. Load the
# data from the dataset into your program and plot a Bar Graph of the data, taking
# the Year as the x-axis and the number of hurricanes occurring as the Y-axis.
import pandas as pd
import matplotlib.pyplot as plt
data_set = pd.read_csv("Hurricanes.csv")
print(data_set)
height = [3, 12, 5, 18, 45]
plt.bar(data_set, height=height)
plt.title(' Hurricanes Bar Graph')
plt.xlabel('Year')
plt.ylabel('The number of hurricanes occurring')
plt.show()
| true
|
177170fd7f050b898cb18642d6e22e9ab45dccad
|
Falsaber/mhs-python
|
/Basics Tutorial #1 - Python.py
| 2,065
| 4.125
| 4
|
#This is a comment.
#Comments are ignored during code activation.
print("The shell will print what is contained within this area.")
var = input("var will now become a variable that can be called upon later. var is now:")
print(var)
#This will print the text in the variable "var" and require a response.
#input asks for a response to the text provided.
if var == "a variable":
print("Correct! Nice job.")
elif var == "why should I care":
print("Now, now, you WANT to pass thic class, right? Right???")
else:
print("Come on, the answer was right there in front of you!")
#This will cause different text to print based on your answer to the input text.
#If you answer correctly, the "if" statement will trigger, if you don't, "else" will trigger.
print("=-" * 30)
#This is a good way to make a divider, which will separate the printed text in the shell between before this point and after this point.
#Now, here's an example of all these components in action!
#Input Section
name = input("Your name:")
color = input("Your favorite color:")
sport = input("Favorite sport, if any:")
hobby = input("Favorite hobby:")
thundurus = input("PokeDex #642:")
#Divider
print("=-" * 60)
#Output
print("Your name is... " + name + "!")
print("Your favorite color is... " + color + "!")
print("Your favorite sport is... " + sport + "!")
print("Your favorite hobby is... " + hobby + "!")
if thundurus == "Thundurus":
print("That's right! Totally didn't use Google, right? =)")
elif thundurus == "Bulbasaur":
print("That's #1. You were close, though, only 641 Pokemon off!")
else:
print("Nope. That's fine, though, I didn't really expect you to know this off the top of your head.")
#Divider
print("=-" * 30)
#When this is used, a fully interactive questionnaire will start, which will ask you about your name, favorite color/sport/hobby, and what #642 in the PokeDex is.
#Try it out if you want!
#With this, you should have a basic understanding of "print", "input", variables and dividers. You should also understand if, elif, and else statements.
| true
|
60db9080ef8cf89aed97749191a024bc2bb50e42
|
jvillega/App-Academy-Practice-Problems-I
|
/SumNums.py
| 456
| 4.4375
| 4
|
#!/usr/bin/env python3
# Write a method that takes in an integer `num` and returns the sum of
# all integers between zero and num, up to and including `num`.
#
# Difficulty: easy.
# Precondition: num is a defined integer
# Postcondition: sum of all integers between zero and num are returned
def sumNums( num ):
total = 0
for x in range( num + 1 ):
total += x
return total
print( sumNums( 6 ) )
print( sumNums( 5 ) )
| true
|
ea70a815fe1af0e4a9d744be5e65716583d905b0
|
shefreyn/Exercise_1-100
|
/Ex_(2).py
| 498
| 4.21875
| 4
|
print('__ Tip Calculator __')
totalBill = input('Total bill amount : ')
totalBill = int(totalBill)
percentage = input('Percentage you would like to tip : ')
percentage = int(percentage)
totalPeople = input('Total no of people you want to split the bill : ')
totalPeople = int(totalPeople)
tip = percentage/totalBill * 100
perPerson = totalBill/totalPeople
totalPerPerson = tip + perPerson
print(f"Each have to pay tip of {tip} and a bill amount of {perPerson} that is : {totalPerPerson}")
| true
|
d37a0503e24a9adc939a88afb84290820d8ca565
|
ClosetcoderJ/python
|
/chapter2/Ex9.py
| 445
| 4.25
| 4
|
oddRange = range(1, 10, 2)
evenRange = range(2, 10, 2)
print(oddRange)
print(evenRange)
print(list(oddRange))
print(list(evenRange))
tenRange = range(1, 11, 1)
tenRange1 = range(10, 0, -1)
# 1 ~ 10 까지 모든 수를 갖고 있는 Range
range1 = range(1, 11, 1) #range라고 변수명 지으면 안됨
range2 = range(1, 11)
# 10 ~ 1 까지 모든 수를 갖고 있는 Range
range3 = range(10, 0, -1)
print(range1 + range2) #오류뜸
| false
|
42daa52bcad63bb4a42ba9f2598423a9d0b8f329
|
umeshraj/MITx-6.00.1x_CS
|
/wk2_ex_isin.py
| 597
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 17 15:10:39 2017
@author: umesh
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
if len(aStr) == 0:
return False
else:
mid = len(aStr)//2
if aStr[mid] == char:
return True
elif char < aStr[mid]:
return isIn(char, aStr[0:mid])
elif char > aStr[mid]:
return isIn(char, aStr[mid+1:])
print(isIn('a', 'apqrstvw'))
| false
|
000a977fa8f8df9751c97dd6d92c8b307ccd8759
|
liaosuwei/learnGit
|
/1.py
| 1,300
| 4.15625
| 4
|
#print('please enter your name:')
#name = input()
#print('hello',name)
#print('中文测试正常')
'''age = 7
if age >=18:
print('your age is',age)
print('adult')
elif 18 > age >= 6:
print('your age is',age)
print('teenager')
else:
print('your age is',age)
print('kid')
height = 1.75
weight = 80.5
bmi = weight/(height*height)
print(bmi)
if bmi < 18.5:
print('过轻')
elif 18.5<= bmi <=25:
print('正常')
elif 25 < bmi <= 28:
print('过重')
elif 28 < bmi <= 32:
print('肥胖')
else:
print('严重肥胖')'''
'''names = ['Bob','july','candy']
for name in names:
print(name)'''
import math
'''def quadratic (a,b,c):
x1 = (-b + math.sqrt(b*b - 4*a*c)/(2*a))
x2 = (-b - math.sqrt(b*b - 4*a*c)/(2*a))
x = [x1,x2]
print(x)
print(quadratic(2,4,1))
print('请输入a,b,c的值:')
a1 = input()
b2 = input()
c3 = input()
d = [a1,b2,c3]
print('a,b,c的值为',d)
print('所求得的解为:',quadratic(a1,b2,c3))'''
#name = ['liujingming','liaosuwei','zhaoxinyi','chenyahan']
#print(name[0:4])
print('请输入不超过五个字符的词汇:')
'''l = ['h','e','l','l','o']
a = input()
alist = a.split(',')
print(alist)
n = -1
for b in alist:
n = n + 1
if b != l[n]:
print('测试失败')
print('测试成功')'''
| false
|
7cf1e38bed3059b0e455ee77a91c394c7307b3d4
|
gitBlackburn/Learn-Python-The-Hard-Way
|
/ex15.py
| 614
| 4.21875
| 4
|
# uses argv from the sys lib
# adds arguments
# from sys import argv
# # two arguments scripts and filename
# script, filename = argv
# # opens the text file and stores it in txt
# txt = open(filename)
# # notifies the user
# print "Here's your file %r:" %filename
# # reads the text file
# print txt.read()
# prompts the user for more action
print "Type the file name again:"
# stores the usrs imput in file_again
file_again = raw_input("> ")
# i think that this makes a references to txt
txt_again = open(file_again)
# shows the users the txt file again
print txt_again.read()
#txt.close
txt_again.close()
| true
|
84252e3008a9d3e59636948801cff89ef25ae676
|
samfrances/coding-challenges
|
/codewars/6kyu/write_number_in_expanded_form.py
| 875
| 4.1875
| 4
|
#!/usr/bin/env python3
"""
Solution to https://www.codewars.com/kata/5842df8ccbd22792a4000245/
You will be given a number and you will need to return it as a string in
Expanded Form. For example:
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0.
"""
def expanded_form(num):
place_values = times10()
face_values = mods(num, 10)
face_with_place = zip(place_values, face_values)
expanded = filter(lambda x: x > 0, (f * p for (f, p) in face_with_place))
return ' + '.join(reversed([str(i) for i in expanded]))
def mods(num, divide_by):
while num != 0:
num, rem = num // divide_by, num % divide_by
yield rem
def times10():
n = 1
while True:
yield n
n *= 10
| true
|
959d90c339a63bc8fe81a2c82cf03d06fed6a3d6
|
samfrances/coding-challenges
|
/codewars/5kyu/calculating_with_functions.py
| 1,685
| 4.40625
| 4
|
#!/usr/bin/env python2
"""
Solution to https://www.codewars.com/kata/525f3eda17c7cd9f9e000b39/
This time we want to write calculations using functions and get the results.
Let's have a look at some examples:
JavaScript:
seven(times(five())); // must return 35
four(plus(nine())); // must return 13
eight(minus(three())); // must return 5
six(dividedBy(two())); // must return 3
Ruby:
seven(times(five)) # must return 35
four(plus(nine)) # must return 13
eight(minus(three)) # must return 5
six(divided_by(two)) # must return 3
Requirements:
There must be a function for each number from 0 ("zero") to 9 ("nine")
There must be a function for each of the following mathematical
operations: plus, minus, times, dividedBy (divided_by in Ruby)
Each calculation consist of exactly one operation and two numbers
The most outer function represents the left operand, the most inner
function represents the right operand
Divison should be integer division,
e.g eight(dividedBy(three()))/eight(divided_by(three))
should return 2, not 2.666666...
"""
from operator import add, mul, floordiv, sub
def _number(n):
def numfunc(operator=None):
if operator:
return operator(n)
return n
return numfunc
def _operator(f):
def op(n):
def op_n(i):
return f(i, n)
return op_n
return op
zero = _number(0)
one = _number(1)
two = _number(2)
three = _number(3)
four = _number(4)
five = _number(5)
six = _number(6)
seven = _number(7)
eight = _number(8)
nine = _number(9)
plus = _operator(add)
minus = _operator(sub)
times = _operator(mul)
divided_by = _operator(floordiv)
| true
|
f688003052f4e3dff5422dc4eb669322434fc3b4
|
Biraja007/Python
|
/Looping-Statements.py
| 1,423
| 4.625
| 5
|
# Looping statements is used to repeatedly perform a block of operations.
# For loop: It is used to iterate over a sequence starting from first value to the last.
Numbers = [1,2,3,4,5]
for number in Numbers:
print (number , end=' ')
print()
print()
# While loop: It is used to repeatedly execute a block of statements as long as the condition mentioned holds true.
length = 1
while length <= 3:
print ("Value of the length is" , length )
length = length + 1
print()
# Nested loop: A loop within another loop is called as Nested loop.
adj = ["red" , "big" , "tasty"]
fruits = ["apple" , "banana" , "cherry"]
for x in adj:
for y in fruits:
print (x , y)
print()
# Break: Break is used to stop a loop from further execution.
length = 1
while length > 0:
if length == 3:
break
print ("Length =" , length)
length = length + 1
print()
# Continue: It is used to skip a particular iteration.
length = 1
while length <= 4:
if length == 2:
length = length + 1
continue
print ("Length =" , length)
length = length + 1
print ()
# Else: The block os statement in else block is executed if the break statement in the loop was executed.
length = 1
while length <= 3:
if length == 5:
break
print ("Length =" , length)
length = length + 1
else:
print ("Break statement was not executed")
| true
|
027f5fd55ea60cddc723d52fd8bcba69789f7f8c
|
bondarum/python-basics
|
/examples/ex19_object_and_classes.py
| 2,575
| 4.375
| 4
|
# class
# Tell Python to make a new type of thing.
# object
# Two meanings: the most basic type of thing, and any instance of some thing.
# instance
# What you get when you tell Python to create a class.
# def
# How you define a function inside a class.
# self
# Inside the functions in a class, self is a variable for the instance/object being accessed.
# inheritance
# The concept that one class can inherit traits from another class, much like you and your parents.
# composition
# The concept that a class can be composed of other classes as parts, much like how a car has wheels.
# attribute
# A property classes have that are from composition and are usually variables.
# is-a
# A phrase to say that something inherits from another, as in a "salmon" is-a "fish."
# has-a
# A phrase to say that something is composed of other things or has a trait, as in "a salmon has-a mouth."
# A class definition can be compared to the recipe to bake a cake. A recipe is needed to bake a cake.
# The main difference between a recipe (class) and a cake (an instance or an object of this class) is obvious.
# A cake can be eaten when it is baked, but you can't eat a recipe, unless you like the taste of printed paper.
# Like baking a cake, an OOP program constructs objects according to the class definitions of the program program.
# A class contains variables and methods. If you bake a cake you need ingredients and instructions to bake the cake.
# Accordingly a class needs variables and methods.
# There are class variables, which have the same value in all methods and there are instance variables,
# which have normally different values for different objects. A class also has to define all the necessary methods,
# which are needed to access the data.
class Animal(object):
pass
class Dog(Animal):
def __init__(self, name):
self.name = name
class Cat(Animal):
def __init__(self, name):
self.name = name
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None
class Employee(Person):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
self.salary = salary
class Fish(object):
pass
class Salmon(Fish):
pass
class Halibut(Fish):
pass
rover = Dog("Rover")
satan = Cat("Satan")
mary = Person("Mary")
mary.pet = satan
frank = Employee("Frank", 120000)
frank.pet = rover
flipper = Fish()
crouse = Salmon()
harry = Halibut()
| true
|
9601c95246f411b410d64ed76bbeb117d2635e31
|
saikiran6666/rama
|
/operators.py
| 1,402
| 4.28125
| 4
|
#addition
x=12
y=2
print(x+y)
#substraction
x=10
y=5
print(x-y)
#multiplication
x=10
y=10
print(x*y)
#division
x=10
y=2
print(x / y)
#modulus
x=6
y=2
print(x%y)
#exponenetiation
x=2
y=3
print(x**y)
#floor division
x=5
y=2
print(x // y)
#assignment operators
# "=" operator
x=10
print(x)
# += operator
x=10
x+=2
print(x)
# (-=) operator
x=10
x-=2
print(x)
# *= operator
x=10
x*=2
print(x)
# /= operator
x=10
x/=2
print(x)
# %= operator
x=10
x%=2
print(x)
# //= operator
x=10
x//=3
print(x)
# **= operator
x=10
x**=3
print(x)
#>>= operator
x=5
x>>=3
print(x)
#comparision operator
# == operator
x=5
y=3
print(x==y)
#!= operator
x=5
y=3
print(x!=y)
#> graterthan operator
x=5
y=3
print(x>y)
#< lessthan operator
x=5
y=3
print(x<y)
#>= graterthan or equal to operator
x=5
y=3
print(x>=y)
#<= graterthan or equal to operator
x=5
y=3
print(x<=y)
#logical oprators
#and operator
x=5
print(x>3 and x<10)
# or operator
x=5
print(x>3 or x<4)
# not operator
x=5
print(not(x>3 or x<10))
# identity operators
# is oprator
x= ["apple , banana"]
y= ["apple , banana"]
z=x
print (x is z)
print(x is y)
print(x==y)
# is not operator
x= ["apple , banana"]
y= ["apple , banana"]
z=x
print (x is not z)
print(x is not y)
print(x==y)
#membership operators
# in operator
x= ["apple","banana"]
print( "apple" in x)
# not in operator
x= ["apple","banana"]
print("pineapple"not in x)
| false
|
2c0499d4e9b9a35f6b5157932fa2d58bcdf5f7d3
|
bnsreenu/python_for_microscopists
|
/052-GMM_image_segmentation.py
| 2,975
| 4.125
| 4
|
#!/usr/bin/env python
__author__ = "Sreenivas Bhattiprolu"
__license__ = "Feel free to copy, I appreciate if you acknowledge Python for Microscopists"
# https://www.youtube.com/watch?v=kkAirywakmk
"""
@author: Sreenivas Bhattiprolu
NOTE: I was alerted by one of the viewers that m.bic part needs more explanation so here it is. Both BIC and AIC are included as built in methods as part of Scikit-Learn's GaussianMixture. Therefore we do not need to import any other libraries to compute these. The way you compute them (for example BIC) is by fitting a GMM model and then calling the method BIC. In the video I tried to achieve multiple things in one single line, compute BIC for each GMM calculated by changing number of components and also to plot them. Let me elaborate...
Instead of changing number of components in a loop let us compute one at a time, for example let us define n = 2. Then fit a gmm model for n=2 and then calculate BIC. The code would look like ...
import numpy as np
import cv2
img = cv2.imread("images/Alloy.jpg")
img2 = img.reshape((-1,3))
from sklearn.mixture import GaussianMixture as GMM
n = 2
gmm_model = GMM(n, covariance_type='tied').fit(img2)
#The above line generates GMM model for n=2
#Now let us call the bic method (or aic if you want).
bic_value = gmm_model.bic(img2) #Remember to call the same model name from above)
print(bic_value) #You should see bic for GMM model generated using n=2.
#Do this exercise for different n values and plot them to find the minimum.
Now, to explain m.bic, here are the lines I used in the video.
n_components = np.arange(1,10)
gmm_models = [GMM(n, covariance_type='tied').fit(img2) for n in n_components]
plt.plot(n_components, [m.bic(img2) for m in gmm_models], label='BIC')
Here, we are computing multiple GMM models each by changing n value from 1 to 10.
Then, for each n value we are computing bic via m.bic(img2) where m is replaced by gmm_models for each of the model generated. Think of this as typing gmm_model.bic(img2) each time you change n and generate a new GMM model.
I hope this explanation helps better understand the video content.
"""
import numpy as np
import cv2
#Use plant cells to demo the GMM on 2 components
#Use BSE_Image to demo it on 4 components
#USe alloy.jpg to demonstrate bic and how 2 is optimal for alloy
img = cv2.imread("images/BSE_Image.jpg")
# Convert MxNx3 image into Kx3 where K=MxN
img2 = img.reshape((-1,3)) #-1 reshape means, in this case MxN
from sklearn.mixture import GaussianMixture as GMM
#covariance choices, full, tied, diag, spherical
gmm_model = GMM(n_components=4, covariance_type='tied').fit(img2) #tied works better than full
gmm_labels = gmm_model.predict(img2)
#Put numbers back to original shape so we can reconstruct segmented image
original_shape = img.shape
segmented = gmm_labels.reshape(original_shape[0], original_shape[1])
cv2.imwrite("images/segmented.jpg", segmented)
| true
|
15acd9528c16d6b48e195e8d34fec459cd356560
|
hossainlab/numpy
|
/book/_build/jupyter_execute/notebooks/07_ChangingShapeOfAnArray.py
| 1,828
| 4.125
| 4
|
#!/usr/bin/env python
# coding: utf-8
# ## Array Shape Manipulation
# In[1]:
import numpy as np
# ### 1. Flattening
# In[2]:
a = np.array([("Germany","France", "Hungary","Austria"),
("Berlin","Paris", "Budapest","Vienna" )])
# In[3]:
a
# In[4]:
a.shape
# #### The ravel() function
# The primary functional difference is that flatten is a method of an ndarray object and hence can only be called for true numpy arrays. In contrast ravel() is a library-level function and hence can be called on any object that can successfully be parsed. For example ravel() will work on a list of ndarrays, while flatten will not.
# In[5]:
a.ravel()
# ##### T gives transpose of an array
# In[6]:
a.T
# In[7]:
a.T.ravel()
# ### 2. Reshaping
# reshape() gives a new shape to an array without changing its data.
# In[8]:
a.shape
# In[9]:
a.reshape(4,2)
# In[10]:
np.arange(15).reshape(3,5)
# In[16]:
np.arange(15).reshape(5,3)
# ##### The reshape() dimensions needs to match the number of values in the array
# Reshaping a 15-element array to an 18-element one will throw an error
# In[11]:
np.arange(15).reshape(3,6)
# #### Specify only one dimension (and infer the others) when reshaping
# Another way we can reshape is by metioning only one dimension, and -1. -1 means that the length in that dimension is inferred
# In[12]:
countries = np.array(["Germany","France", "Hungary","Austria","Italy","Denmark"])
countries
# ##### Here the unspecified value is inferred to be 2
# In[13]:
countries.reshape(-1,3)
# ##### Here the unspecified value is inferred to be 3
# In[14]:
countries.reshape(3,-1)
# ##### If the values of the dimensions are not factors of the number of elements, there will be an error
# In[15]:
countries.reshape(4,-1)
# In[ ]:
| true
|
aa0b0faf17e8610c304726adae4c0ec31b4ecdc4
|
subramario/Data_Structures_Algos_Practice
|
/Sorting/Quicksort.py
| 1,711
| 4.15625
| 4
|
#Classic quicksort - chooses the first element in the array as the pivot point and sorts accordingly
class Solution:
def partition(self, array, start, end):
# [start|low_ _ _ _ _ _high] --> Three pointers
pivot = array[start]
low = start + 1
high = end
while True:
# Continue iterating high and low pointers toward each other until an unsorted value is found or if pointers cross each other
while low <= high and array[low] <= pivot:
low = low + 1
while low <= high and array[high] >= pivot:
high = high - 1
# If both pointers have unsorted values, swap them into correct position, else if they have crossed each other, break
if low <= high:
array[low], array[high] = array[high], array[low]
else:
break
# Sort the pivot value into its respective place by switching with high/low pointer
array[start], array[high] = array[high], array[start]
return high # Note: values are swapped, but pointer locations are the same! Return the location of the now sorted pviot
def quicksort(self,array,start,end):
if start >= end:
return
p = self.partition(array, start, end) #Retrieves the index of the pivot point after each sort
self.quicksort(array, start, p-1) #Recursively sorts array on left side of the pivot
self.quicksort(array, p+1, end) #Recursively sorts array on right side of the pivot
array = [29,99,27,41,66,28,44,78,87,19,31,76,58,88,83,97,12,21,44]
quick = Solution()
quick.quicksort(array, 0, len(array)-1)
print(array)
| true
|
a270bf6c277a23874cd16044fb25e1669d865d56
|
Ronaldo192/meus_codigos
|
/função_P_N.py
| 337
| 4.125
| 4
|
"""
Faça um programa, com uma função que necessite de um argumento. A função retorna o valor de caractere ‘P’,
se seu argumento for positivo, e ‘N’, se seu argumento for zero ou negativo.
"""
def nummero(x):
if x > 0:
print("P")
elif x < 0:
print("N")
else:
print("Zero")
nummero(0)
| false
|
a0e48325dedb2e416c7ac28f68cf33202886cdc5
|
laomao0/Learn-python3
|
/Function/ex20.py
| 876
| 4.125
| 4
|
from sys import argv
script, input_file = argv
def print_all(f):
print(f.read())
# Each time you do f.seek(0) you're moving to the start of the file
# seek(0) moves the file to the 0 byte(first byte) in the file
def rewind(f):
f.seek(0)
# each time you do f.readline() you're reading a line from the file and
# moving the read head to right after the \n that ebds that line.
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
rewind(current_file)
print("Let's print three lines:")
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
| true
|
cfe855ef9cdf7a05a083fd5c3b39ef1b20e16589
|
sushmitaraii1/Python-Datatypes-Fucntions
|
/Function/15.py
| 226
| 4.15625
| 4
|
# 15. Write a Python program to filter a list of integers using Lambda.
lst = [1, 5, 6, 4, 8, 5, 6, 9, 5, 3, 5, 9]
sorted_list = list(filter(lambda x:x%2==0,lst))
print("The even numbers from list are: ")
print(sorted_list)
| true
|
158c692aa383ca6f426cabf70d2dc45db3de20b5
|
sushmitaraii1/Python-Datatypes-Fucntions
|
/Function/16.py
| 319
| 4.25
| 4
|
# 16. Write a Python program to square and cube every number in a given list of
# integers using Lambda.
lst = [1, 5, 6, 4, 8, 5, 6, 9, 5, 3, 5, 9]
print(lst)
print("After squaring items.")
square = list(map(lambda x:x**2,lst))
print(square)
print("After cubing items.")
cube = list(map(lambda x:x**3,lst))
print(cube)
| true
|
f3a5622a1badea10083c9a1990aefbcdef124dfa
|
sushmitaraii1/Python-Datatypes-Fucntions
|
/Datatype/2.py
| 480
| 4.40625
| 4
|
# 2. Write a Python program to get a string made of the first 2 and the last 2 chars
# from a given a string. If the string length is less than 2, return instead of the empty string.
# Sample String : 'Python'
# Expected Result : 'Pyon'
# Sample String : 'Py'
# Expected Result : 'PyPy'
# Sample String : ' w'
# Expected Result : Empty String
sample = input("Enter a string: ")
if len(sample) >= 2:
newchar = sample[:2] + sample[-2:]
print(newchar)
else:
print("")
| true
|
8ccf58ee6e37889d78fff8fdc2a21a5ec99c10e3
|
sushmitaraii1/Python-Datatypes-Fucntions
|
/Function/17.py
| 201
| 4.125
| 4
|
# 17. Write a Python program to find if a given string starts with a given character
# using Lambda.
start = lambda x: True if x.startswith('P') else False
print(start('Python'))
print(start('Java'))
| true
|
ddf9b7911a1853b20a87f6471492991110ff450f
|
Keilo104/faculdade-solucoes
|
/Semestre 1/AP1/exercicios2/exercicio8.py
| 243
| 4.1875
| 4
|
num = int(input("Digite o numerador da divisão: "))
den = int(input("Digite o divisor da divisão: "))
res = num / den
mod = num % den
div = num // den
print("O resultado da divisão é {}, o div é {} e o mod é {}".format(res, div, mod))
| false
|
e089c675631f21a21b35ab49e805bc7016d337f1
|
jingyiZhang123/leetcode_practice
|
/dynamic_programming/62_unique_paths.py
| 824
| 4.1875
| 4
|
"""
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
"""
class Solution(object):
def uniquePaths(self, m, n):
if not m or not n:
return 0
board = [[0 for j in range(n)] for i in range(m)]
for i in range(n):
board[0][i] = 1
for i in range(m):
board[i][0] = 1
for i in range(1, m):
for j in range(1,n):
board[i][j] = board[i-1][j] + board[i][j-1]
return board[m-1][n-1]
print(Solution().uniquePaths(0,1))
| true
|
2b31d4a4790e35c9d384e9c8f3e8c1bd3eb19696
|
jingyiZhang123/leetcode_practice
|
/recursion_and_backtracking/17_letter_combinations_of_a_phone_number.py
| 1,025
| 4.15625
| 4
|
"""
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
2: abc
3: def
4: ghi
5: jkl
6: mno
7: pqrs
8: tuv
9: wxyz
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
"""
mapping = {'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'}
class Solution(object):
def _comb(self, soFar, rest):
if not rest:
if soFar: self.result.append(soFar)
return
for char in mapping[rest[0]]:
next = char
remaining = rest[1:]
self._comb(soFar+next, remaining)
def letterCombinations(self, digits):
self.result = []
self._comb("", digits)
return self.result
print(Solution().letterCombinations(''))
| true
|
830e22e15f52ce5d1d0eb65a39c1ea345caadf5a
|
gokarna123/Gokarna
|
/classwork.py
| 333
| 4.125
| 4
|
from datetime import time
num=[]
x=int(input("Enter the number:"))
for i in range(1,x+1):
value=int(input(" Please Enter the number: "))
num.append(value)
num.sort()
print(num)
num=[]
x=int(input("Enter the number:"))
for i in range(1,x+1):
value=int(input(" Please Enter the number: "))
num.reverse()
print(num)
| true
|
ec327f48426bedaf3bad862a9a0ebe5e6afb366b
|
sleibrock/form-creator
|
/fcl/RectData.py
| 1,483
| 4.125
| 4
|
#!/usr/bin/python
#-*- coding: utf-8 -*-
__author__ = 'Steven'
class Rect(object):
"""
Class to store rectangle information
Stores (x,y,w,h), the type of Rect, the ID of the rect, and now the value of the rect
"""
def __init__(self, x, y, w, h, idtag="", typerect="text", value=""):
self.x, self.y, self.w, self.h = x, y, w, h
self.data = (x, y, w, h)
self.idtag = idtag # name tag of the Rect
self.typerect = typerect # default
self.value = value # used for check/radio boxes
def __iter__(self):
"""
The ability to unpack a rectangle into multiple functions is nice (via *rect)
Normally you would use __iter__ for a collection of data
but the only important data in a rectangle is it's positioning data
"""
return self.data
def __eq__(self, other):
"""
The __eq__ method determines equality of one rect to another
However this could be extended to normal lists/tuples as well if necessary
"""
return self.data == other.data
def collide(self, rect):
"""
Collision code (not used in the main program)
This doesn't take into calculation any offset data so it's not used
Deprecated
"""
x1, y1, w1, h1 = self.data
x2, y2, w2, h2 = rect.data
if all([x1 < x2 + w2, x1+w1 > x2, y1 < y2+h2, y1+h1 > y2]):
return True
return False
#end
| true
|
7ddbf394320fe3b4babc65bba39858c47eaa0482
|
Luquicas5852/Small-projects
|
/easy/PascalTriangle.py
| 392
| 4.15625
| 4
|
"""
This will generate Pascal's triangle.
"""
#Define a factorial using recursion
def f(n):
if n == 0:
return 1
else:
return n*f(n - 1)
rows = int(input('Enter with the amount of rows that you want to generate: '))
row = ""
for i in range(rows):
for j in range(i + 1):
num = f(i)/(f(j)*f(i - j))
row += str(num) + " "
print(row)
row = ""
| true
|
3dc184b82e04ea5d263e6668832e574e3543b985
|
dionboonstra/RecommendationsResit
|
/resitRPI.py
| 2,627
| 4.4375
| 4
|
# import csv in order to be able to read/import csv files into directory
import csv
#Load data using the reader function in python, therefrom create a list including all the information present in the userreviews csv file
file = csv.reader(open("/Users/dionboonstra/Downloads/userReviews all three parts.csv", encoding= 'utf8'), delimiter = ';')
reviews = list(file)
#print(reviews)
#Create a new list which includes all reviews on the movie American-Sniper
reviewers = []
for x in reviews:
if x[0] == 'american-sniper':
#all reviewers with reviews on the american-sniper movie are added to the list
reviewers.append(x)
#print(reviewers)
#Create a new list in which all reviews are included from the reviewers present in the reviewers list.
#In addition, the list is constructed so it only contains reviews from reviewers whom scored american-sniper with a 7 or higher,
#where the other reviews are higher than the one provided for american-sniper, and the reviews can be on the movie american sniper itself
recommendations = list()
for y in reviewers:
for z in reviews:
if y[2] == z[2] and int(y[1]) > 7 and int(z[1]) >= int(y[1]) and z[0] != 'american-sniper':
#absolute and relative increase of the reviewscore in comparison to the american-sniper movie are created
absinc = int(z[1]) - int(y[1])
relinc = (int(z[1]) - int(y[1])) / int(y[1])
#the absolute and relative increases of reviewscore are added to the existing list of rows of the original csv file
totalrec = (z[0], z[1], z[2], z[3], z[4], z[5], z[6], z[7], z[8], z[9], absinc, relinc)
#all rows are added to the recommendations list
recommendations.append(totalrec)
#print(recommendations)
#The recommendations list is sorted descending on the absolute increase of the review score (tup[11])
sortedrec = sorted(recommendations, key=lambda tup: (tup[11]), reverse=True)
#print(sortedrec)
#Headers are added in order to create a clear overview for the new recommendations file
header = ["movieName", "Metascore_w", "Author", "AuthorHref", "Date", "Summary", "InteractionsYesCount", "InteractionsTotalCount", "InteractionsThumbUp", "InteractionsThumbDown", "AbsoluteIncrease", "RelativeIncrease"]
#Create a new csv including the header and sortedrec list, completing the movie recommendations list with american-sniper as favorite movie
with open("MovieRecommendations.csv", "w", newline= '') as ResitRecSys:
writer = csv.writer(ResitRecSys, delimiter=';')
writer.writerow(header)
for row in sortedrec:
writer.writerow(row)
| true
|
5cf2041655940707401f2869a256f14be25d00bc
|
17e23052/Lesson-10
|
/main.py
| 1,463
| 4.34375
| 4
|
price = 0
print("Welcome to the Pizza cost calculator!")
print("Please enter any of the options shown to you with correct spelling,")
print("otherwise this program will not work properly.")
print("Would you like a thin or thick crust?")
crust = input().lower()
if crust == "thin":
price = price + 8
elif crust == "thick":
price = price + 10
print("Would you like an 8, 10, 12, 14, or 18 inch crust?")
size = int(input())
if size == 8 or size == 10:
price = price + 0
elif size == 12 or size == 14 or size == 18:
price = price + 2
print("Would you like cheese on your pizza? Please enter yes or no.")
cheese = input().lower()
if cheese == "yes":
price = price + 0
elif cheese == "no":
price = price - 0.5
print("What type of pizza would you like? You can choose from margarita, vegetable, vegan, Hawaiian or meat feast.")
pizzatype = input().lower()
if pizzatype == "margarita":
price = price + 0
elif pizzatype == "vegetable" or pizzatype == "vegan":
price = price + 1
elif pizzatype == "hawaiian" or pizzatype == "meat feast":
price = price + 2
if size == 18:
print("Do you have a voucher code? Please enter yes or no.")
voucher = input().lower()
if voucher == "yes":
print("Type in your voucher code here:")
code = input()
if code == "FunFriday":
print("Code valid")
price = price - 2
else:
print("Code invalid")
print("The total cost for your pizza is:")
print(price)
print("pounds. Enjoy your pizza!")
| true
|
01e5302a82a73d1b89e4996622ae3a76afa542be
|
TRoyer86/AlgorithmsInPythonExercises
|
/ImplementedDataStructures/queuetest.py
| 973
| 4.25
| 4
|
#!/usr/bin/env python
from queueclass import Queue
if __name__ == '__main__':
myqueue = Queue()
print(myqueue.size())
print(myqueue.isEmpty())
# Add each letter in the name of the cutest soon to be 2 year old
myqueue.enqueue('J')
myqueue.enqueue('O')
myqueue.enqueue('S')
myqueue.enqueue('H')
print(myqueue.size())
# And it returns his name in order
print(myqueue.dequeue())
print(myqueue.dequeue())
print(myqueue.dequeue())
print(myqueue.dequeue())
print(myqueue.size())
print(myqueue.isEmpty())
# Add each letter in the name of the best big brother in the world
myqueue.enqueue('W')
myqueue.enqueue('E')
myqueue.enqueue('S')
print(myqueue.size())
# And again, it dequeues in order
print(myqueue.dequeue())
print(myqueue.dequeue())
print(myqueue.dequeue())
print(myqueue.size())
print(myqueue.isEmpty())
| false
|
ee090bb4302155b486dbfe50f7f500206cf68e30
|
shubhangi2803/More-questions-of-python
|
/Data Types - List/Q 7,8,9.py
| 726
| 4.3125
| 4
|
# 7. Write a Python program to remove duplicates from a list.
# 8. Write a Python program to check a list is empty or not.
# 9. Write a Python program to clone or copy a list.
li_one=list(map(int,input("Enter list elements separated by lists : ").split()))
li_two=[]
print("List 1 : ")
print(li_one)
print("List 2 : ")
print(li_two)
def is_empty(li):
return len(li)==0
print("List 1 : Is Empty ?? {}".format(is_empty(li_one)))
print("List 2 : Is Empty ?? {}".format(is_empty(li_two)))
li_one_clone=li_one
li_two_clone=li_two
print("Copy of list 1 : {}".format(li_one_clone))
print("Copy of list 2 : {}".format(li_two_clone))
li_one_new=set(li_one)
print("After removing duplicates, list 1 : {}".format(li_one_new))
| true
|
044e09d766cc7a3eac7f85577d937ddc3ac5205a
|
shubhangi2803/More-questions-of-python
|
/Lambda functions/Q 6.py
| 304
| 4.21875
| 4
|
# 6. Write a Python program to square and cube every number in a given list of integers using Lambda.
li=list(map(int,input("Enter list of numbers : ").split()))
p=list(map(lambda x: x*x, li))
q=list(map(lambda y: y*y*y, li))
print("List of squares : {}".format(p))
print("List of cubes : {}".format(q))
| true
|
9f9a285d1187ac3b7ff6e85c4b6aaec22c4a21ca
|
vray22/Coursework
|
/cs153/Assignment2.py
| 1,183
| 4.3125
| 4
|
#Name: Victor Lozoya
#Date:2/9/17
#Assignment2
#create string to avoid typing it twice
str = "Twinkle, twinkle, little star,\n"
#use print statements for each line to avoid confusion
print(str)
print("\t How I wonder what you are! \n")
print("\t\t Up above the world so high, \n")
print("\t\t Like a diamond in the sky, \n")
print(str)
print("\t How I wonder what you are\n\n\n\n\n\n\n\n\n ")
#set radius to user input and cast it to float
radius = float(input("Enter radius for circle \n"))
print("The radius is: ")
print(radius)
pie = 3.14
area = pie * radius**2#calculate area
print("\nThe area is: ")
print(area)
#set length to user input and cast to int
length = int(input("\n\n\n\n\n\nEnter length of square\n"))
print("The length is: ")
print (length)
area = length**2#calculate area
print("\nThe area is: ")
print (area)
#set base and height equal to user input and cast both to int
base = int(input("\n\n\n\n\nEnter length of base\n"))
height = int(input("Enter length of heigth\n"))
print("Base: ")
print (base)
print("\nHeight: ")
print(height)
area = base * height#Calculate area for rectangle
print("\nArea: ")
print(area)
| true
|
80b8af95d4df47a9449331f58b3244ef031c6c25
|
njberejan/TIY-Projects
|
/multiples_exercise.py
| 577
| 4.21875
| 4
|
list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def multiple_of_3_or_5(list_of_numbers):
multiples_of_3_or_5_list = []
total = 0
for number in list_of_numbers:
if number % 3 == 0:
multiples_of_3_or_5_list.append(number)
elif number % 5 == 0:
multiples_of_3_or_5_list.append(number)
else:
continue
for number in multiples_of_3_or_5_list:
#print(multiples_of_3_or_5_list)
#print(total)
total += number
return total
print(total)
multiple_of_3_or_5(list_of_numbers)
| true
|
5674214283bf08513493920731e534bf1ee84316
|
VolatileMatter/GHP_Files
|
/sorts.py
| 774
| 4.125
| 4
|
import random
def in_order(a_list):
last_item = None
for item in a_list:
if not last_item:
last_item = item
if item < last_item:
return False
last_item = item
return True
#Insertion Sort
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
return alist
ranList = random.sample(xrange(1, 101), 10)
print "Random list:",ranList
print ""
mylist = [2,5,1,8,3,9]
test1 = [1,2,3,4,5,6,7,8]
test2 = [1,9,3,4,5,6,7,8,2]
test3 = [4,3,2,1,7,9,8]
test4 = [6,9,10,5,2,8]
print "insertion: "
print insertionSort(mylist)
print insertionSort(ranList)
print ""
| true
|
e2cb5ff79e19754a0de1723983ca3e6fbc5ddbc0
|
Arwen0905/Python_Test
|
/TQC_考題練習_第二類/PYD301.py
| 841
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
# 載入 pandas 模組縮寫為 pd
import pandas as pd
# 資料輸入
datas = [[75, 62, 85, 73, 60], [91, 53, 56, 63, 65],
[71, 88, 51, 69, 87], [69, 53, 87, 74, 70]]
indexs = ["小林", "小黃", "小陳", "小美"]
columns = ["國語", "數學", "英文", "自然", "社會"]
df = pd.DataFrame(datas, columns=columns, index=indexs)
print('行標題為科目,列題標為個人的所有學生成績')
print(df)
print()
# 輸出後二位學生的所有成績
print('後二位的成績')
print(df.tail(2))
print()
# 將自然成績做遞減排序輸出
df1 = df.sort_values(by="自然", ascending=False)
print('以自然遞減排序')
print(df1["自然"])
print()
# 僅列小黃的成績,並將其英文成績改為80
df.loc["小黃", "英文"] = 80
print('小黃的成績')
print(df.loc["小黃"])
| false
|
4758c61d8a45c42db805d1ce5dcf6cc7c56fbde4
|
goosebones/spellotron
|
/string_modify.py
| 1,556
| 4.15625
| 4
|
"""
author: Gunther Kroth gdk6217@rit.edu
file: string_modify.py
assignment: CS1 Project
purpose: minipulate words that are being analyzed
"""
def punctuation_strip(word):
""" strips punctuation from the front and back of a word
returns a tuple of word, front, back
:param word: word to strip punctuation from
"""
front = ""
back = ""
# front strip
while word[0].isalpha() == False:
front += word[0]
word = word[1:]
if len(word) == 0:
return word, front, back
# back strip
while word[-1].isalpha() == False:
back += word[-1]
word = word[:len(word)-1]
# reverse back's order
true_back = ""
for ch in back:
true_back = ch + true_back
return word, front, true_back
def lower_case(word):
""" convert first letter to lowercase
uses a list method
:param word: word to convert
"""
letter_list = []
new_word = ""
for ch in word:
letter_list.append(ch)
first = letter_list[0]
lower = first.lower()
letter_list[0] = lower
for element in letter_list:
new_word += element
return new_word
def upper_case(word):
""" convert first letter to uppercase
uses a list method
:param word: word to convert
"""
letter_list = []
new_word = ""
for ch in word:
letter_list.append(ch)
first = letter_list[0]
cap = first.upper()
letter_list[0] = cap
for element in letter_list:
new_word += element
return new_word
| true
|
59407725886e12ac88af7d5a5be9b765f40890b5
|
diksha12p/DSA_Practice_Problems
|
/Palindrome Number.py
| 1,014
| 4.125
| 4
|
"""
LC 9. Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
"""
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x) == str(x)[::-1]
def isPalindrome_alt(self, x: int) -> bool:
if x < 0:
return False
num , rev_num = x, 0
while num:
q, r = divmod(num, 10)
rev_num = rev_num * 10 + r
num = q
return x == rev_num
if __name__ == '__main__':
sol = Solution()
assert sol.isPalindrome(121) is True
assert sol.isPalindrome(-121) is False
assert sol.isPalindrome(10) is False
assert sol.isPalindrome_alt(121) is True
assert sol.isPalindrome_alt(-121) is False
assert sol.isPalindrome(10) is False
| true
|
1ff85b27640580d2df9b5bad1a023d37d0a507e8
|
diksha12p/DSA_Practice_Problems
|
/Letter Combinations of a Phone Number.py
| 1,068
| 4.1875
| 4
|
"""
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could
represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any
letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
"""
from typing import List
class Solution:
def __init__(self):
self.KEYBOARD = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv",
"9": "wxyz"}
def letterCombinations(self, digits: str) -> List[str]:
if not digits: return []
result = []
self.dfs(digits, 0, "", result)
return result
def dfs(self, digits, idx, path, result):
if len(path) == len(digits):
result.append(path)
return
for char in self.KEYBOARD[digits[idx]]:
self.dfs(digits, idx + 1, path + char, result)
if __name__ == '__main__':
sol = Solution()
print(sol.letterCombinations('23'))
| true
|
678696e563fd889705b32dfdffc578f5b575415c
|
diksha12p/DSA_Practice_Problems
|
/Binary Tree Right Side View.py
| 1,666
| 4.28125
| 4
|
"""
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see
ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# IDEA 1: Level Order Traversal and append the ele at index = -1 to the final answer
def rightSideView(self, root: TreeNode) -> List[int]:
if not root: return []
# queue: List(TreeNode)
result, queue = list(), [root]
while queue:
level = []
result.append(queue[-1].val)
for node in queue:
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
queue = level
return result
# IDEA 2: Obtain the right side views for the left and right child of the root. (view_right, view_left)
# Depending upon the length of view_right, append view_left[len(view_right) : ]
def rightSideView_alt(self, root: TreeNode) -> List[int]:
if not root: return []
view_right = self.rightSideView_alt(root.right)
view_left = self.rightSideView_alt(root.left)
if len(view_left) < len(view_right):
return [root.val] + view_right
else:
return [root.val] + view_right + view_left[len(view_right):]
| true
|
9cd96360b3da0bb90a3f98d9486cb9137714b0a3
|
lcongdon/tiny_python_projects
|
/07_gashlycrumb/addressbook.py
| 1,069
| 4.125
| 4
|
#!/usr/bin/env python3
"""
Author : Lee A. Congdon <lee@lcongdon.com>
Date : 2021-07-14
Purpose: Tiny Python Exercises: addressbook
"""
import argparse
import json
def get_args():
"""Parse arguments"""
parser = argparse.ArgumentParser(
description="Print line(s) from file specified by parameters",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-f",
"--file",
default="addressbook.json",
type=argparse.FileType("rt"),
help="Input file in json format",
metavar="FILE",
)
parser.add_argument("entry", help="Name of person", metavar="entry")
return parser.parse_args()
def main():
"""Main program"""
args = get_args()
addresses = json.load(args.file)
if args.entry in addresses:
print(
addresses[args.entry]["emailAddress"]
+ "\n"
+ addresses[args.entry]["phoneNumber"]
)
else:
print(f'I do not have an entry for "{args.entry}".')
if __name__ == "__main__":
main()
| true
|
53f80b39a9af33f5d1cde67c3ad9848e534dca74
|
joshuasewhee/practice_python
|
/OddOrEven.py
| 460
| 4.21875
| 4
|
# Joshua Sew-Hee
# 6/14/18
# Odd Or Even
number = int(input("Enter a number to check: "))
check = int(input("Enter a number to divide: "))
if (number % 2 == 0):
print("%d is even." %number)
elif (number % 2 != 0):
print("%d is odd." %number)
if (number % 4 == 0):
print("%d is a multiple of 4." % number)
if (number % check == 0):
print("%d divides evenly in %d" %(number,check))
else:
print("%d does not divide evenly in %d." %(number,check))
| true
|
d61bc138d85bce329077a818754b7ac9dd15dede
|
GeraldoFBraga/Urion
|
/problema_1847.py
| 1,798
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A entrada consiste apenas de três inteiros, A, B e C (-100 ≤ A, B, C ≤ 100), os quais representam respectivamente as
temperaturas registradas no 1º, no 2º e no 3º dias."""
wert = input()
A,B,C = wert.split()
a = int(A)
b = int(B)
c = int(C)
if a > b < c:
'''Se a temperatura desceu do 1º para o 2º dia, mas subiu ou permaneceu constante do 2º para o 3º, as pessoas ficam
felizes (primeira figura).'''
if (a - b) > (b - c):
'''Se a temperatura subiu do 1º para o 2º dia e do 2º para o 3º, mas subiu do 2º para o 3º menos do que subira
do 1º para o 2º, as pessoas ficam tristes (terceira figura).'''
print(":(")
elif (a - b) == (b - c):
'''Se a temperatura subiu do 1º para o 2º dia e do 2º para o 3º, mas subiu do 2º para o 3º no mínimo o tanto que
subira do 1º para o 2º, as pessoas ficam felizes (quarta figura)'''
print(':)')
else:
print(":)")
elif a < b >= c:
'''Se a temperatura subiu do 1º para o 2º dia, mas desceu ou permaneceu constante do 2º para o 3º, as pessoas ficam
tristes (segunda figura).'''
print(':)')
print(':(')
elif a < b < c:
if (a - b) > (b - c):
'''Se a temperatura desceu do 1º para o 2º dia e do 2º para o 3º, mas desceu do 2º para o 3º menos do que
descera do 1º para o 2º, as pessoas ficam felizes (quinta figura).'''
print(':)')
elif (a - b) >= (b - c):
'''Se a temperatura desceu do 1º para o 2º dia e do 2º para o 3º, mas desceu do 2º para o 3º no mínimo o tanto que
descera do 1º para o 2º, as pessoas ficam tristes (sexta figura).'''
print(':)')
else:
print(':(')
else:
print(":(")
| false
|
e1b80889e822b256ac44f915be4d3d3d414bd042
|
Neanra/EPAM-Python-hometasks
|
/xhlhdehh-python_online_task_4_exercise_1/task_4_ex_1.py
| 486
| 4.1875
| 4
|
"""04 Task 1.1
Implement a function which receives a string and replaces all " symbols with ' and vise versa. The
function should return modified string.
Usage of any replacing string functions is prohibited.
"""
def swap_quotes(string: str) -> str:
str_list = []
for char in string:
if char == "'":
str_list.append('"')
elif char == '"':
str_list.append("'")
else:
str_list.append(char)
return ''.join(str_list)
| true
|
98418b93761efe90361044257d2ccb8821814a84
|
smohapatra1/scripting
|
/python/practice/start_again/2023/08122023/daily_tempratures.py
| 1,293
| 4.28125
| 4
|
# 739. Daily Temperatures
# Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
# Example 1:
# Input: temperatures = [73,74,75,71,69,72,76,73]
# Output: [1,1,4,2,1,1,0,0]
# Example 2:
# Input: temperatures = [30,40,50,60]
# Output: [1,1,1,0]
# Example 3:
# Input: temperatures = [30,60,90]
# Output: [1,1,0]
# Approach :-
# Iterate through each day, check if the current day can resolve the most recently unresolved day.
# If it can then resolve the day, and continue checking and resolving until it finds a day it cannot resolve
# Add current day to unresolved days (stack)
def DailyTemp(tempratures):
stack=[] # All Indices that are still unsettled
res=[0] * len(tempratures) # Add new days to our stacks
for i, t in enumerate(tempratures):
while (stack and tempratures[stack[-1]] < t):
cur = stack.pop()
res[cur] = i - cur
stack.append(i)
return res
if __name__ == "__main__":
tempratures=[73,74,75,71,69,72,76,73]
print ("Results are {}".format(DailyTemp(tempratures)))
| true
|
828c58ffd48d16e2fa9521c5142d3cbc08dbf781
|
smohapatra1/scripting
|
/python/practice/start_again/2021/01202021/leap_year.py
| 757
| 4.3125
| 4
|
#Python Program to Check Leap Year
#Write a Python Program to Check Leap Year
#or Not by using the If Statement, Nested If Statement, and Elif Statement in Python with example.
#Logic :-
# 366 days
# must be divisible by 4
# Century year - ends with 00, 1200,2400, 2500 - If divisible by 400 ( leap year), if not then not a leap year
def leap(year):
if year % 4 == 0:
print ("{} is a leap year".format(year))
elif ( year % 400 == 0 ):
print ("{} is a leap year".format(year))
elif ( year % 100 != 0):
print ("{} is NOT a leap year".format(year))
else:
print ("{} is NOT a leap year".format(year))
def main():
year = int(input("Enter the year: "))
leap(year)
if __name__ == "__main__":
main()
| false
|
b6e7a07afee721eaf42e989702f4e783ec895e52
|
smohapatra1/scripting
|
/python/practice/start_again/2021/04242021/Day9_1_Grading_Program.py
| 1,547
| 4.46875
| 4
|
#Grading Program
#Instructions
#You have access to a database of student_scores in the format of a dictionary. The keys in student_scores are the names of the students and the values are their exam scores.
#Write a program that converts their scores to grades. By the end of your program, you should have a new dictionary called student_grades that should contain student names for keys and their grades for values. The final version of the student_grades dictionary will be checked.
#DO NOT modify lines 1-7 to change the existing student_scores dictionary.
#DO NOT write any print statements.
#This is the scoring criteria:
#Scores 91 - 100: Grade = "Outstanding"
#Scores 81 - 90: Grade = "Exceeds Expectations"
#Scores 71 - 80: Grade = "Acceptable"
#Scores 70 or lower: Grade = "Fail"
#Expected Output
#'{'Harry': 'Exceeds Expectations', 'Ron': 'Acceptable', 'Hermione': 'Outstanding', 'Draco': 'Acceptable', 'Neville': 'Fail'}'
student_scores = {
"sam" : 90,
"jon" : 50,
"tom" : 88,
"harry" : 60,
}
student_grades = {}
for student in student_scores:
score = student_scores[student]
#print (student)
if score >= 90 :
student_grades[student] = "Outstanding"
print (f"{student} - {student_grades[student]} - {score} ")
elif score > 70:
student_grades[student] = "Exceeds Expectations"
print (f"{student} - {student_grades[student]} - {score} ")
else:
student_grades[student] = "Fail"
print (f"{student} - {student_grades[student]} - {score} ")
| true
|
bcff2a824797cb88f04d621f495d065e21061c2b
|
smohapatra1/scripting
|
/python/practice/start_again/2021/01312021/Arithmetic_Progression_Series.py
| 1,113
| 4.1875
| 4
|
#Python Program to find Sum of Arithmetic Progression Series
#Write a Python Program to find the Sum of Arithmetic Progression Series (A.P. Series) with a practical example.
#Arithmetic Series is a sequence of terms in which the next item obtained by adding a common difference to the previous item.
# Or A.P. series is a series of numbers in which the difference of any two consecutive numbers is always the same.
# This difference called a common difference.
#In Mathematical behind calculating Arithmetic Progression Series
#Sum of A.P. Series : Sn = n/2(2a + (n – 1) d)
#Tn term of A.P. Series: Tn = a + (n – 1) d
def main():
a = int(input("Enter the first number: "))
n = int(input("Enter the how many numbers you want: "))
d = int(input("Enter the difference : "))
total = (n * (2 * a + (n-1) * d) /2)
tn = a + (n-1)* d
i = a
print ("A.P series : " , end=" ")
while ( i <= tn):
if i != tn:
print ("%d" %i , end=" ")
else:
print ( "%d = %d " %(i, total))
i = i + d
print ("\n")
if __name__ == "__main__":
main()
| true
|
9473d9df78d57dbf279956c0fc491cfdaa674e8a
|
smohapatra1/scripting
|
/python/practice/start_again/2022/01112022/function03.py
| 211
| 4.125
| 4
|
# Define a function named say_my_name that asks user to enter his/her name
# This functon would print as : "Hi [ username ] "
def say_my_name(n):
print (f' Hi {n} ')
say_my_name(input("Enter your name : "))
| false
|
d00e756205cde1f47268c1ea0e676d1d34def6bc
|
smohapatra1/scripting
|
/python/practice/start_again/2022/03162022/square_of_stars_with_while.py
| 294
| 4.28125
| 4
|
#Draw a square of stars with while
def square_of_stars_with_while(n):
i=0
while i < n:
stars=" "
j=0
while j < n:
stars+="* "
j +=1
print (stars)
i +=1
square_of_stars_with_while(int(input("Enter the number of stars ")))
| false
|
7e01c666f5165874a1c7a19b71006f19781ef8bd
|
smohapatra1/scripting
|
/python/practice/start_again/2021/04192021/Day5.4-Fizbuzz_Exercise.py
| 893
| 4.53125
| 5
|
# Fizzbuzz exercise
#FizzBuzz
#Instructions
#You are going to write a program that automatically prints the solution to the FizzBuzz game.
#Your program should print each number from 1 to 100 in turn.
#When the number is divisible by 3 then instead of printing the number it should print "Fizz".
#`When the number is divisible by 5, then instead of printing the number it should print "Buzz".`
#`And if the number is divisible by both 3 and 5 e.g. 15 then instead of the number it should print "FizzBuzz"`
#e.g. it might start off like this:
#`1
#2
#Fizz
#4
#Buzz
#Fizz
#7
#8
#Fizz
#Buzz
#11
#Fizz
#13
#14
#FizzBuzz`
for num in range (1,10):
if num % 3 == 0 and num % 5 == 0 :
print (f"FizzBuzz - {num}")
elif num % 3 == 0:
print (f"Fizz - {num}")
elif num % 5 == 0 :
print (f"Buzz - {num}")
else:
print (f" {num} Not divisible by 3 or 5")
| true
|
557e3ada7a2d31cacb69c92e24adcd9cabc203b8
|
smohapatra1/scripting
|
/python/practice/start_again/2021/02032021/sum_of_odd_even.py
| 533
| 4.375
| 4
|
#Python Program to Calculate Sum of Odd Numbers
#Write a Python Program to Calculate Sum of Odd Numbers from 1 to N using While Loop, and For Loop with an example.
# Sum of even numbers as well
def main():
n = int(input("Enter the N numbers you want : "))
even = 0
odd = 0
for i in range (1, n+1):
#EVEN
if i % 2 == 0 :
even = even + i
else:
odd = odd + i
print ("Sum of ODD = % d AND Sum of Even = %d " % ( odd, even ))
if __name__ == "__main__":
main()
| true
|
afaab750d64902af88baf0e0f775bbf9e7e8e3b0
|
smohapatra1/scripting
|
/python/practice/start_again/2023/07202023/topk_frequent_elements.py
| 986
| 4.1875
| 4
|
# 347. Top K Frequent Elements
# Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
#Ref https://interviewing.io/questions/top-k-frequent-elements
# Example 1:
# Input: nums = [1,1,1,2,2,3], k = 2
# Output: [1,2]
# Approach :-
# Accept the array of integers
# Loop through the integers
# Use counters
#BFM
def top_k(nums,k):
counts={}
for num in nums:
if num not in counts:
counts[num] = 1
else:
counts[num] +=1
# Sort in descending order based on the counts
counts_list=sorted(counts.items(), key=lambda x:x[1], reverse=True)
sorted_counts=dict(counts_list[:k])
return [num for num in sorted_counts]
if __name__ == "__main__":
nums=[1,2,3,4,5,1,2,4,4,4,4]
k=5 # Highest number of repeated numbers to show
print("Current numbers {}".format(nums))
print("Most frequent number is {}".format(top_k(nums,k)))
| true
|
70102efaa0cb459776deb46145e3ea97dd87d796
|
smohapatra1/scripting
|
/python/practice/start_again/2021/04252021/Day9.2_Calculator.py
| 926
| 4.25
| 4
|
#Design a calculator
def add (n1, n2):
return n1 + n2
def sub (n1, n2):
return n1 - n2
def mul (n1, n2):
return n1 * n2
def div (n1, n2):
return n1 / n2
operations = {
"+" : add,
"-" : sub,
"*" : mul,
"/" : div,
}
def calculator():
num1=float(input("Enter the first number : "))
for operators in operations:
print (operators)
dead_end=False
while dead_end == False:
action=input("Pick the operations from line abobe: ")
num2=float(input("Enter the 2nd number: "))
calculation_function=operations[action]
answers=calculation_function(num1, num2)
print (f" {num1} {action} {num2} = {answers}")
ask=input("Enter 'y' to continue or 'n' to exit: ")
if ask == "y":
num1 = answers
else:
print ("Exit the calculation ")
dead_end=True
calculator()
calculator()
| true
|
2a223dffa17d46d91db72e500c1a87f93f3a9f04
|
smohapatra1/scripting
|
/python/practice/start_again/2023/07182023/valid_anagram.py
| 1,311
| 4.3125
| 4
|
# #Given two strings s and t, return true if t is an anagram of s, and false otherwise.
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
# Example 1:
# Input: s = "anagram", t = "nagaram"
# Output: true
# Example 2:
# Input: s = "rat", t = "car"
# Output: false
#Solution
# 1. Validate and make sure these are strings
# 2. First we have to convert these strings into lower case
# 3. Make sure len of each string is equal, else false
# 4. Sort those string and if they are equal , return True , else False
# 5. If they matches then its a valid anagram
# 6. Else it's not a valid anagram
import os
def find_anagram(string1, string2 ):
a=len(string1)
b=len(string2)
if a != b :
return False
elif (sorted(string1) == sorted(string2)):
return True
else:
return False
if __name__ == "__main__":
string1=input("Enter the first String1: ".lower())
string2=input("Enter the first String2: ".lower())
if find_anagram(string1, string2):
#print ("The" , string1, string2 , "are anagram" )
print ("The {} and {} are anagram" .format(string1, string2))
else:
print ("The {} and {} are not anagram" .format(string1, string2) )
| true
|
cd9f44ea5f2845dcbd9d2483658a21b34ec17773
|
smohapatra1/scripting
|
/python/practice/start_again/2023/07192023/two_sum.py
| 1,032
| 4.21875
| 4
|
#Two Sum :-
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# You can return the answer in any order.
# Steps
# Define the array of integers - nums
# Define another integer - target
# Get the two integers
# Added the two integers
# Go until its end and return the Sum of two integers
#BFM
def twoSum(nums,target):
n=len(nums)
required={}
for i in range(n):
for j in range(i+1, n ):
if nums[j] == target - nums[i]:
return [i, j]
#print ("The fields are {},{} and values are {} + {} = {}".format(i , j, nums[i], nums[j],target))
return False
if __name__ == "__main__":
nums=[1,2,3,5,8,10]
target=3
print ("The nums are {} & Target is {}".format(nums, target))
print ("The Number positions for the target are {}".format(twoSum(nums,target)))
| true
|
68ce09d3a1a0f6ab6630400048a6298dab9f0e3f
|
smohapatra1/scripting
|
/python/practice/start_again/2022/01232022/Odd_even.py
| 253
| 4.375
| 4
|
#Ask an user to enter a number. Find out if this number is Odd or Even
def odd_even(n):
if n > 0:
if n %2 == 0 :
print (f'{n} is even')
else:
print (f'{n} is odd')
odd_even (int(input("Enter the number : ")))
| true
|
6a5481244b5254a8fb1b1a2c529021559e5b7e42
|
smohapatra1/scripting
|
/python/practice/start_again/2020/11232020/return_unique_way2.py
| 364
| 4.15625
| 4
|
#Write a Python function that takes a list and returns a new list with unique elements of the first list.
#Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]
#Unique List : [1, 2, 3, 4, 5]
def uniq(x):
uNumber = []
for nums in x:
#print (nums)
if nums not in uNumber:
uNumber.append(nums)
print (uNumber)
uniq([1,1,1,1,2,2,3,3,3,3,4,5])
| true
|
276855e33856f3c06ffb785c92368e084a2cbcdd
|
smohapatra1/scripting
|
/python/practice/day28/while_loop_factorial.py
| 464
| 4.3125
| 4
|
#/usr/bin/python
#Write a program using while loop, which asks the user to type a positive integer, n, and then prints the factorial of n. A factorial is defined as the product of all the numbers from 1 to n (1 and n inclusive). For example factorial of 4 is equal to 24. (because 1*2*3*4=24)
a = int(input("Enter a number "))
f = 1
count = 1
while f <= a :
count = f * count
f +=1
#count +=1
print ("v : % d and c %d " % (f, count))
print (count)
| true
|
24e90f48c6eb41aef70079751e3637e3bfae7a9a
|
smohapatra1/scripting
|
/python/practice/day54/inverted_pyramid.py
| 243
| 4.375
| 4
|
#Example 3: Program to print inverted half pyramid using an asterisk (star)
def triag(x):
for i in range(x,0,-1):
for j in range(1, i - 1):
print("*", end=" ")
print("\r")
triag(int(input("Enter a value : ")))
| true
|
7908fb2010308508274fe772a706bdb847b8c547
|
smohapatra1/scripting
|
/python/practice/day57/merge_k_sorted_list.py
| 625
| 4.15625
| 4
|
'''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
'''
class Solution:
def k_list(self, lists):
res =[]
for i in range(len(k_list)) :
item=lists[i]
while item != None:
res.append(item.val)
item = item.next
res = sorted(res)
return res
#k_list(input("Enter lists with space: "),input("Enter lists with space: "), input("Enter lists with space: "))
lists(input("Enter lists with space: "))
| true
|
a8e64901300abcb4c2605b7631d0e6580bc44723
|
smohapatra1/scripting
|
/python/practice/start_again/2020/10212020/print_format.py
| 558
| 4.1875
| 4
|
#Use print Format
string="Hello"
print('Hello {} {}' .format('Samar' ,' , How are you?'))
# Another format of replacing indexes/formats
print('Hello {1} {0}' .format('Samar' ,' , How are you?'))
#Using key value pairs
print ('Hello {a} {b}'.format(a='Samar,', b='How are you?'))
result = 100/777
print ('Your result is {r}'.format(r=result))
#Format values - "value:width.percision f""
print ('Your result is {r:1.3f}'.format(r=result))
#Formatted string
name="samar"
print(f'My name is {name}')
print('Python {} {} {}'.format('rules!', 'and', 'rocks'))
| true
|
6a2dd722f1b305bbf17ac97b270637cb14187954
|
smohapatra1/scripting
|
/python/practice/start_again/2020/12022020/bank_withdrawal.py
| 1,221
| 4.1875
| 4
|
#For this challenge, create a bank account class that has two attributes:
#owner
#balance
#and two methods:
#deposit
#withdraw
#As an added requirement, withdrawals may not exceed the available balance.
class bank():
def __init__(self,owner,balance):
self.owner = owner
self.balance = balance
#print ("{} is owner".format(self.owner))
def get_deposit(self,deposit):
self.balance += deposit
print ("{} is deposited".format(deposit))
print ("{} is new balance".format(self.balance))
def get_withdraw(self,withdraw):
if withdraw >= self.balance :
print ("Balance unavailable")
else:
self.balance -= withdraw
print ("Your new balance is {}".format(self.balance))
def __str__(self):
return "Owner : {self.owner} \n Balance : {self.balance}"
#withdrawal = 1000
#deposit = 300
myaccount = bank("Sam", 100)
print ("{} is only owner".format(myaccount.owner))
print ("{} Initial Balance".format(myaccount.balance))
myaccount.get_deposit(300)
myaccount.get_withdraw(1000)
#print ("I have {} in balance".format(self.balance)
#print ("I have total {} new in balance".format(self.balance))
| true
|
e7ac2a2569c2a6f6fedbcf050a7c47324aab22f0
|
smohapatra1/scripting
|
/python/practice/start_again/2021/05192021/Day19.3_Turtle_Race.py
| 1,068
| 4.125
| 4
|
from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500, height=400)
user_bet= screen.textinput(title="Make your bet", prompt="While turtle will win")
color = ["red", "orange", "blue", "purple", "yellow", "green"]
y_position = [-70, -40, -10, 20, 50, 80 ]
all_turtle = []
for turtle_index in range(0,6):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.color(color[turtle_index])
new_turtle.goto(x=-230, y=y_position[turtle_index])
all_turtle.append(new_turtle)
is_race_on=False
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtle:
if turtle.xcor() > 230:
is_race_on = False
winning_color = turtle.pencolor()
if winning_color == user_bet:
print (f"You have own. The winning color {winning_color}")
else:
print (f"You have lost. The winning color {winning_color}")
random_distance = random.randint(0,10)
turtle.forward(random_distance)
screen.exitonclick()
| true
|
9bc20c7bd49c75ad4fa1f7f14bdaf53b067c2765
|
smohapatra1/scripting
|
/python/practice/day22/4.if_else_elsif.py
| 454
| 4.34375
| 4
|
#!/usr/bin/python
#Write a program which asks the user to type an integer.
#If the number is 2 then the program should print "two",
#If the number is 3 then the program should print "three",
#If the number is 5 then the program should print "five",
#Otherwise it should print "other".
a = int(raw_input("Enter an integer : "))
if a == 2 :
print ('two')
elif a == 3 :
print ('three')
elif a == 5 :
print ('five')
else:
print ('other')
| true
|
9e3497c111907de60e9c65126ccb0392bb226cb8
|
smohapatra1/scripting
|
/python/practice/start_again/2023/07282023/valid_palindrome.py
| 1,570
| 4.21875
| 4
|
# 125. Valid Palindrome
# A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward.
# Alphanumeric characters include letters and numbers.
# Given a string s, return true if it is a palindrome, or false otherwise.
# Example 1:
# Input: s = "A man, a plan, a canal: Panama"
# Output: true
# Explanation: "amanaplanacanalpanama" is a palindrome.
# Example 2:
# Input: s = "race a car"
# Output: false
# Explanation: "raceacar" is not a palindrome.
# Solution
# Remove the spaces and punctuation
# Convert them into lowercase using link comprehension
# Join them into a new string
# Find the string with Start and End indices
# Now look for first and last letters of the string, if they matches it's good, Go to next letter
# Keep doing that check until it runs out of letters to check
# If it doesn't find a pair, return false
# The process continues until either the indices cross each other or a mismatch found
# OR
# Using built in functions
def palindrome( word: str) -> bool:
# word1=""
# for i in word:
# if i.isalpha():word1 +=i.lower()
# if i.isnumeric():word1 +=i
# return word1 == word1[::-1]
word=[char.lower() for char in word if word.isalnum()]
return word == word[::-1]
if __name__ == "__main__":
word="A man, a plan, a canal: Panama"
print ("The word is : {}".format(word))
print ("The '{}' is Palindrome: {}".format(word, palindrome(word)))
| true
|
9824a4b453375626bcb9f8aa7b44a1918bb9aefc
|
smohapatra1/scripting
|
/python/practice/start_again/2021/01282021/multiplication_table.py
| 522
| 4.34375
| 4
|
#Python Program to Print Multiplication Table
#Write a Python Program to Print Multiplication Table using For Loop and While Loop with an example.
#https://www.tutorialgateway.org/python-program-to-print-multiplication-table/
def main():
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
for i in range (a,b):
for j in range (1, b+1):
print ("{} * {} = {}".format(i,j,i*j))
print ("==================")
if __name__ == "__main__":
main()
| true
|
dc525f721a46294ad9480e2f048e11f60db7bfc2
|
smohapatra1/scripting
|
/python/practice/start_again/2020/11032020/Assesment1.py
| 396
| 4.4375
| 4
|
#Use for, .split(), and if to create a Statement that will print out words that start with 's':
#st = 'Print only the words that start with s in this sentence'
st = 'Sam Print only the words that start with s in this sentence'
#print (st.split())
for w in st.split():
if w[0] == 's' or w[0] == 'S':
print (w)
#Method2
for w in st.split():
if w[0].lower() == 's':
print (w)
| false
|
20c8b64f6be8db91cba68f554d3e3ae05419dd91
|
smohapatra1/scripting
|
/python/practice/start_again/2020/11192020/exercise1_volume_sphere.py
| 246
| 4.59375
| 5
|
#Write a function that computes the volume of a sphere given its radius.
#Volume = 4/3 * pi * r**2
from math import pi
def volume(x):
v = ( (4/3) * pi * (x**3))
print ("The volume is {}".format(v))
volume(input("Enter the the radius : "))
| true
|
46498d3f88a2b0fc51b346c66a97e5fda3a0062e
|
smohapatra1/scripting
|
/python/practice/start_again/2022/01112022/function_strip_and_lower.py
| 377
| 4.125
| 4
|
#Define a fucntion strip and lower
#This function should remove space at the begining and at the end of the string
# this it will convert the string into lower case
import string
import os
def strip_lower(a):
remove_space=a.strip()
print (f'{remove_space}')
lower_text=remove_space.lower()
#return lower_text
print (f'{lower_text}')
strip_lower(" Samar Mohapatra ")
| true
|
dabf1a922d38efaf401cf0965010f9cf573ea5e6
|
smohapatra1/scripting
|
/python/practice/start_again/2022/01232022/Seasonal_dress.py
| 595
| 4.3125
| 4
|
# Define a function that decides what to wear, according to the month and number of the day.
# It should ask for month and day number
# Seasons and Garments :
# Sprint - Shirt
# Summer : T-Shirt
# Autumn : Sweater
# Winter : Coat
def what_to_wear (m, d ):
if m == "March" and d < 15 or d > 20:
print (f'In {m}, day {d} Wear - Shirt ')
elif m == "June" and d < 15 :
print (f'In {m}, day {d} wear : Shirt')
elif m == "Decemember" and d < 15 :
print (f'In {m}, day {d} wear - Coat')
what_to_wear (str(input("Enter Month: ")), int(input("Enter day: ")))
| true
|
abafe23702ae19b7226190cf0d257696b2b37246
|
smohapatra1/scripting
|
/python/practice/start_again/2023/07202023/group_anagrams.py
| 1,268
| 4.375
| 4
|
# Given an array of strings strs, group the anagrams together. You can return the answer in any order.
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
# Example 1:
# Input: strs = ["eat","tea","tan","ate","nat","bat"]
# Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
# Idea
# Enter the arrays
# Create a dictionary
# Loop through each word
# Break the words and sort them with Join
# If word exists, append the word to the value list of the corresponding keys
# if key doesn't exist create a new key with sorted word
# After iterating through all the words, return the values of the dictionary as a list of lists with groups
def groupAnagram(words):
anagram_dict={}
for word in words:
sorted_word=''.join(sorted(word))
if sorted_word in anagram_dict:
anagram_dict[sorted_word].append(word)
else:
anagram_dict[sorted_word]=[word]
return list(anagram_dict.values())
if __name__ == "__main__":
words=["eat","tea","tan","ate","nat","bat"]
n=len(words)
print("The original list {}".format(words))
print("The formatted list {}".format(groupAnagram(words)))
| true
|
831b36909f6487ea728f372718dc5dbf2c5f982b
|
smohapatra1/scripting
|
/python/practice/start_again/2022/03212022/isosceles_stars.py
| 335
| 4.21875
| 4
|
#Print ISOSCELES stars
def isosceles_for(n):
for i in range(n):
stars=""
for j in range(i+1):
stars+="* "
print (stars)
for i in range(n,0,-1):
stars=""
for j in range(i):
stars+="* "
print (stars)
isosceles_for(int(input("Enter the number of stars: ")))
| false
|
6dde775a5d0c80f11e01a71098f64c47bc20d618
|
smohapatra1/scripting
|
/python/practice/start_again/2022/09112022/Reverse_array.py
| 334
| 4.21875
| 4
|
#Reverse array
def reversearray(array):
n=len(array)
lowindex=0
highindex=n-1
while highindex > lowindex:
array[lowindex], array[highindex] = array[highindex], array[lowindex]
lowindex+=1
highindex-=1
if __name__ == '__main__':
array=[1,2,3,4,5]
reversearray(array)
print (array)
| true
|
f87568f78e5811a171fd3a48a693fbabad90f562
|
smohapatra1/scripting
|
/python/practice/day8/loop_until_your_age.py
| 243
| 4.34375
| 4
|
#!/usr/bin/python
#Create a loop that prints out either even numbers, or odd numbers all the way up till your age. Ex: 2,4,6,....,14
age = int(raw_input("Enter your age: "))
for i in range(0,age, 2):
print ("%d is a even number") % i
| true
|
16dd759bfb679b455f370364a9113c3d1bdc3979
|
cristearadu/CodeWars--Python
|
/valid parentheses.py
| 966
| 4.25
| 4
|
#Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function
#should return true if the string is valid, and false if it's invalid.
#0 <= input.length <= 100
def valid_parentheses(string):
if not string:
return True
ret_val = 0
for ch in string:
if ch == "(":
ret_val += 1
elif ch == ")":
ret_val -= 1
if ret_val < 0:
return False
return True if ret_val == 0 else False
return (True if dict_parentheses["("] == dict_parentheses[")"] else False)
#print(valid_parentheses("("))#False
#print(valid_parentheses(" ("))#False
#print(valid_parentheses("()"))#True
#print(valid_parentheses("(())((()())())"))#True
print(valid_parentheses(")test"))#False
print(valid_parentheses("hi(hi)()"))#True
print(valid_parentheses(""))#True
print(valid_parentheses(")("))
| true
|
d22ddd5a6b3f4bd42aefe3384054ceea2fef38db
|
OMAsphyxiate/python-intro
|
/dictionaries.py
| 1,084
| 4.9375
| 5
|
# Dictionaries allow you to pair data together using key:value setup
# For example, a phone book would have a name(key):phone number (value)
# dict[key] --> value
# Stored using {}
phone_book1 = {'qazi':'123-456-7890', 'bob':'222-222-2222', 'cat':'333-333-3333'}
# This can be created this way to make the code more readable
# Also makes it easier to add addtional values based on the keys
phone_book = {
'qazi':['123-456-7890', 'qazi@qazi.com'],
'bob':['222-222-2222', 'bob@bob.com'],
'cat':['333-333-3333', 'cat@cat.com']
}
# Now we have a dictionary that contains three keys (qazi, bob, cat)
# And each key contains a list of elements
# And each list contains two elements
# Now that we've stored a few key:value pairs, we can tap into the values using the keys
print(phone_book1['qazi']) #will print out the value of the key 123-456-7890
print(phone_book['qazi']) #will print out the list of values phone and email
# If we only want a single item in the list of values
print(phone_book['qazi'][1]) #Will index the 2nd value (0, 1) from the list
# resulting in printing his email qazi@qazi.com
| true
|
55d6cf63e7d64239137d5156afbeae90b661c6e5
|
whuang67/algorithm_dataStructure
|
/Part6_Search_Sort/SequentialSearch.py
| 1,278
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 03 20:40:39 2018
@author: whuang67
"""
###### Sequential Search ######
def search(arr, item, sort=False):
## Unordered
def seq_search(arr, item):
pos = 0
found = False
while pos < len(arr) and not found:
print(pos)
if arr[pos] == item:
found = True
else:
pos += 1
return found
## Ordered
def ordered_seq_search(arr, item):
pos = 0
found = False
stopped = False
while pos < len(arr) and not found and not stopped:
print(pos)
if arr[pos] == item:
found = True
elif arr[pos] > item:
stopped = True
else:
pos += 1
return found
## If unknown, unordered is the default.
if sort:
return ordered_seq_search(arr, item)
else:
return seq_search(arr, item)
if __name__ == "__main__":
arr = [1,2,3,4,5,6,7]
arr2 = [7,6,5,4,3,2,1]
print(search(arr, 5, True))
print(search(arr, 10, True))
print(search(arr2, 1))
print(search(arr2, 10))
| true
|
e3e3d68b5af0809f5bd6adc8d191a50158b63535
|
drfoland/test-repo
|
/week_3/weekly-exercises/insertionSort.py
| 662
| 4.1875
| 4
|
### This is my own insertionSort code completed as an eLearning exercise.
"""
main() function is used to demonstrate the sort() function
using a randomly generated list.
"""
def main():
### List Initialization
from numpy import random
LENGTH = 6
list = []
for num in range(LENGTH):
list.append(random.randint(100))
print("Unsorted List:")
print(list)
print()
list = sort(list)
print("Sorted List:")
print(list)
"""
sort() is the implementation of a basic insertion sort
algorithm.
"""
def sort(list):
### Beginning of Selection Sort Algorithm
"""
NEEDS TO BE UPDATED
"""
return list
if __name__ == "__main__":
main()
| true
|
39e1e460c3ddf9293efa189a46e30f58c3222481
|
Fili95160/Final1.PCBS
|
/exp.py
| 2,903
| 4.125
| 4
|
"""A series of trials where a Circle is presented and the participant must press a key as quickly as possible.
"""
import random
from expyriment import design, control, misc, stimuli
########## ******************* PART 1.Experiment settings ******************* ####################
NTRIALS = 5
ITI = 1000 # inter trial interval
exp = design.Experiment(name="Side Detection")
control.initialize(exp)
blankscreen = stimuli.BlankScreen()
instructions = stimuli.TextScreen("Instructions",
f"""From time to time, a Circle will appear at the center of screen.
Your task is to press the space bar key as quickly as possible when you see it (We measure your reaction-time).
There will be {3*NTRIALS} trials in total.
Press the space bar to start.""")
###### 1.A --> Definition of the only two possible trials made up of two stimuli "Blue/Red"
#Stimulus red
visual_trial_red = design.Trial()
visual_trial_red.add_stimulus(stimuli.Circle(radius=100, colour=(255,0,0)))
#Stimulus blue
visual_trial_blue = design.Trial()
visual_trial_blue.add_stimulus(stimuli.Circle(radius=100, colour= (0,0,255)))
###### 1.B --> Definition of Associated Blocks "Blue/Red"
visual_block_red = design.Block("red")
# Buidlding red block with 5 stimuli
for i in range(NTRIALS):
visual_block_red.add_trial(visual_trial_red)
exp.add_block(visual_block_red) # Adding red block to experiment
# Building blue block with 5 stimuli
visual_block_blue = design.Block("blue")
for i in range(NTRIALS):
visual_block_blue.add_trial(visual_trial_blue)
exp.add_block(visual_block_blue) # Adding blue block to experiment
exp.add_data_variable_names([ 'block' , 'key' , 'time' ]) # Implementing data frame's columns name to study after experiment
visual_block_random = design.Block('random')
L=["red" , "blue"]
for i in range(NTRIALS):
rand = random.choice(L)
visual_block_random.name == rand
if(random == "red"):
visual_block_random.add_trial(visual_trial_red)
else:
visual_block_random.add_trial(visual_trial_blue)
exp.add_block(visual_block_random)
########## ******************* PART 2.Experiment ******************* ####################
control.start(skip_ready_screen=True) #begining experiment
instructions.present()
exp.keyboard.wait()
exp.clock.wait( 3000 )
for b in exp.blocks: # moving through each block
for t in b.trials: # iterating over stimuli inside each code
blankscreen.present()
exp.clock.wait( ITI ) # Fixed time between each stimulus.
exp.clock.wait( random.randint(1000, 2000) ) # Random time between 1 and 3 sec. between each stimulus.
t.stimuli[0].present() # Printing stimulus.
key, rt = exp.keyboard.wait(misc.constants.K_SPACE) # monitoring time
exp.data.add( [ b.name, key, rt ] ) #Adding data to our database
control.end() # ending experiment
| true
|
881b990daf1d7e913a1d67e1001b3b861dfa706e
|
douzhenjun/python_work
|
/random_walk.py
| 1,083
| 4.28125
| 4
|
#coding: utf-8
from random import choice
class RandomWalk():
'''a class which generate random walking data'''
def __init__(self, num_points=20):
'''initial the attribute of random walking'''
self.num_points = num_points
#random walking origins from (0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
'''calculate all points belong to random walking'''
#random walking continually, until list up to the given length
while len(self.x_values) < self.num_points:
#the direction and the distance along this direction
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
#do not walking on the spot
if x_step == 0 and y_step == 0:
continue
#calculate the next point's x and y values
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
| true
|
8e09b0b74fcfd1c9fab28dfc8cc0104feee6dea6
|
justinminsk/Python_Files
|
/Intro_To_Python/X_Junk_From_Before_Midterm/SuperFloatPow.py
| 338
| 4.125
| 4
|
def SuperFloatPow(num, num2, num3) :
"""(number, number, number) -> float
Takes three numbers inculding float and the first number is taken to the
second numbers power then divided by the third and the answer is the remainder
>>>SuperFloatPow(4.5, 6.4, 8.9)
7.344729065655461
"""
return((num**num2)% num3)
| true
|
6555a2c4680eff23807d266a903c229bc506abe6
|
justinminsk/Python_Files
|
/Intro_To_Python/HW11/rewrite.py
| 1,505
| 4.3125
| 4
|
import os.path
def rewrite(writefile):
while os.path.isfile(writefile): # sees if the file exsits
overwrite = input('The file exists. Do you want to overwrite it (1), give it a new name (2), or cancel(3).')
# menu
if overwrite == '1':
print('I will overwrite the ' + writefile + ' file.')
with open(writefile, 'w') as file: # write over the file
newtext = input('Enter you new text') # get new text to put in the file
file.write(newtext) # write the new text into file
break # end loop
elif overwrite == '2':
print('I will now change the name of ' + writefile + ' file')
newtitle = input('Enter new file name with .txt') # get new title
with open(writefile, 'r') as file: # read the old file
with open(newtitle, 'w') as title: # write the new file
for text in file: # read all of the text
text = text # save the text as a variable
title.write(text) # write the new file
break # end loop
elif overwrite == '3':
return 'Canceling' # ends the rewrite
else:
print('Invalid key pressed') # print to let user know what they did wrong
continue # restart loop
if __name__ == '__main__': # Run the rewrite
rewrite('test.txt') # run using test.txt
# test.txt has:
# this is a text
# doc
| true
|
8914809ff2f8fa02fc8368e032fd3faaa2c4aa8f
|
justinminsk/Python_Files
|
/Intro_To_Python/HW15/find_min_max.py
| 689
| 4.1875
| 4
|
def find_min_max(values):
"""(list of numbers) -> NoneType
Print the minimum and maximum value from values.
"""
min = values[0] # start at the first number
max = values[0] # start at the first number
for value in values:
if value > max:
max = value
if value < min:
min = value
print('The minimum value is {0}'.format(min))
print('The maximum value is {0}'.format(max))
if __name__ == '__main__':
find_min_max([0, 1, 3, 4, 0, 2, -1])
# None type screws up the list and produces an error
# change line 6 and 7 to the first item on the list. This still does not help with mixed lists (string and num).
| true
|
90b152be2880ea265c2a05924a4be0b526179a5e
|
Yet-sun/python_mylab
|
/Lab_projects/lab5/Lab5_04_f1.py
| 1,281
| 4.34375
| 4
|
'''
需求:改进Person类,在满足之前要求不变的情况下,
将姓名(name)、年龄(age)、性别(sex)变为私有属性
(注意私有属性的定义要求),并使用@property装饰器。
要求使用两种方法
(提示:另一种方法可以直接使用property()函数)。
'''
class Person4:
def __init__(self, name='任我行', age='60', sex='男'):
self.__name = name
self.__age = age
self.__sex = sex
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@property
def sex(self):
return self.__sex
@name.setter
def name(self, value):
self.__name = value
@age.setter
def age(self, value):
self.__age = value
@sex.setter
def sex(self, value):
self.__sex = value
def main():
p1 = Person4()
p1.name = '令狐冲' #实际转化为p1.set_name('令狐冲')
p1.age = 18 #实际转化为p1.set_age(18)
print(p1.name, p1.age, p1.sex)
p2 = Person4('东方不败')
p2.age=22
print(p2.name, p2.age, p2.sex)
p3=Person4()
print(p3.name, p3.age, p3.sex)
p4=Person4('任盈盈')
p4.age=18
p4.sex='女'
print(p4.name, p4.age, p4.sex)
main()
| false
|
94237377d8e3c8a64d9dff094a2c3dfdab823484
|
Yet-sun/python_mylab
|
/Lab_projects/lab5/Lab5_02.py
| 761
| 4.15625
| 4
|
'''
需求:改进Person类,增加构造函数,
要求对于姓名(name)、年龄(age)、性别(sex)三个实例属性,
可以传递任意一个或任意两个参数实例化对象(提示:默认值)。
接着,请编写测试代码测试你的类定义符合题目要求。
'''
class Person2:
def __init__(self, name='杜甫', age='20', sex='男'):
self.name = name
self.age = age
self.sex = sex
def prin_info(self):
print('name:' + self.name)
print('age:' + self.age)
print('sex:' + self.sex)
def main():
p1 = Person2('李白')
p2 = Person2('李清照', '19', '女')
p3 = Person2(age='21')
p1.prin_info()
p2.prin_info()
p3.prin_info()
main()
| false
|
756d1d6de3d815162d40bdbe71d7cf5b35dbdf30
|
marinehero/Capital-construction-project
|
/Projects/BlogWebSite/框架/find().py
| 268
| 4.25
| 4
|
str = "this is really a string example....wow!!!"
substr = "is"
print (str.rfind(substr)) # 从str字符串右开始 匹配到is 位置从左边0的索引开始 为5
print (str.find(substr)) # 从str字符串左开始 匹配到is 位置从左边0的索引开始 为2
| false
|
8e80963193c11d414b5d73adbacb1cf3b952b6f6
|
mshellik/python-beginner
|
/working_with_variable_inputs.py
| 503
| 4.34375
| 4
|
#this is to understand the variables with input and how we can define them and use them
YourFirstName=input("Please enter Your First Name: ") # Input will always take variable as string
YourLastName=input("Please enter your Last Name: ")
print(f'Your First Name is {YourFirstName} and the Last Name is {YourLastName}')
print("This is to EVAL with INPUT")
yourINPUT=eval(input("Please Enter either Num/float/Text in quotes :" ))
print(f'The type of input you have entered is {type(yourINPUT)}')
| true
|
0aeffedd3cf8073d2e6bdd291ec17485d5e3aefd
|
kai-ca/Kai-Python-works
|
/LAB08/dicelab/dice.py
| 1,442
| 4.15625
| 4
|
""" Dice rolls. We roll dice. One die or a
pair of dice. The dice usually have six
sides
numbered 1 thru 6, but we also allow
dice with any nsides. See the test files
for details.
Copyright (c)2015 Ulf Wostner
<wostner@cyberprof.com>. All rights
reserved. """
import random
def roll(nsides=6):
"""Roll a die with nsides. Returns an
int from 1 to nsides."""
return random.randint(1, nsides)
def rollpair(nsides=6):
"""Roll a pair of nsided dice. Returns
rolls as tuples, like (3, 6)."""
return (roll(nsides), roll(nsides))
def rolls(ntimes=10, nsides=6):
"""Roll an nsided die ntimes. Returns a list.
>>> import random; random.seed('downtown')
>>> rolls()
[2, 5, 4, 5, 4, 1, 6, 6, 2, 2]
"""
rollList = []
for i in range(ntimes):
rollList.append(roll(nsides))
return rollList
def rollpairs(ntimes=10, nsides=6):
"""Roll a pair of nsided die ntimes.
Returns a list.
>>> import random; random.seed('pythonistas')
>>> rollpairs()
[(2, 6), (6, 2), (6, 4), (5, 5), (6,
3), (2, 4), (1, 3), (3, 4), (5, 6), (4,
5)]
"""
pairList = []
for i in range(ntimes):
pairList.append(rollpair(nsides))
return pairList
def dice_sum(pair):
""""Returns the sum of the values on
the dice pair.
>>> pair = (6, 1)
>>> dice_sum(pair)
7
"""
return sum(pair)
if __name__ == '__main__':
import doctest
doctest.testmod()
| true
|
b0d5a5d7747c0071fab9d13962963dbca0b44157
|
kai-ca/Kai-Python-works
|
/LAB09/datastructlab/queuemodule.py
| 1,198
| 4.5
| 4
|
"""We implement a Queue data structure.
Queue is a FIFO = First In First Out data structure, like people in line at a ticket office.
We create a class named Queue.
Then we can make instances of that class.
>>> myqueue = Queue()
>>> isinstance(myqueue, Queue)
True
>>> myqueue.push('Alice')
>>> myqueue.push('Eve')
Who is first in line?
>>> myqueue.peek()
'Alice'
Remove them in order (remember FIFO).
>>> myqueue.pop()
'Alice'
>>> myqueue.pop()
'Eve'
"""
class Queue:
"""Queue data structure.
"""
def __init__(self):
self.data = []
def push(self, item):
"Push item onto the Queue"
self.data.append(item)
def pop(self):
"""Remove the "top item" (the biggest item) from the Queue. """
return self.data.pop(0)
def is_empty(self):
"""Returns True if the Queue is empty."""
return self.data == []
def peek(self):
"""Return the item at "the front" of the Queue. Do not remove that item."""
return self.data[0]
def __str__(self):
return "<Queue: {} items>".format(len(self.data))
if __name__ == '__main__':
import doctest
doctest.testmod()
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.