blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c75d93e681c3249f20724da3ac8f6719b683021f | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_332.py | 743 | 4.125 | 4 | def main():
temp = float(input("What is the temperature in degrees? "))
scale = input("What is the scale: Celsius (C) or Kelvin (K)? ")
if scale == "C":
if temp <= 0:
print("At this temperature, water is a solid.")
elif (temp > 0) and (temp < 100):
print("At this temperature, water is a liquid.")
elif temp >= 100:
print("At this temperature, water is a gas.")
if scale == "K":
if temp <= 273.16:
print("At this temperature, water is a solid.")
if (temp > 273.16) and (temp < 373.16):
print("At this temperature, water is a liquid.")
if temp >= 373.16:
print("At this temperature, water is a gas.")
main()
| true |
0eb4be20b6512b4652c20a39b17e828f3659b886 | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_329.py | 842 | 4.25 | 4 | def main():
temperature = float(input("Please enter the temperature:"))
units = input("Please enter 'C' for Celcius or 'K' for Kelvin:")
if units == "K":
ctemp = temperature - 273.2
if ctemp <= 0:
print ("At this temperature, water is a (frozen) solid.")
elif ctemp > 0 and ctemp < 100:
print ("At this temperature, water is a liquid.")
else:
print ("At this temperature, water is a gas.")
elif units == "C":
ctemp = temperature
if ctemp <= 0:
print ("At this temperature, water is a (frozen) solid.")
elif ctemp > 0 and ctemp < 100:
print ("At this temperature, water is a liquid.")
else:
print ("At this temperature, water is a gas.")
else:
print ("Choose 'C' or 'K'")
main()
| true |
299a71e6e3a87d14fbc031789b76b0907d2bfcf5 | sabias-del/TrainBrainPython | /list_comprehension.py | 456 | 4.25 | 4 | # Генераторы списков
listone = [2, 3, 4]
listtwo = [2 * i for i in listone if i > 2]
print(listtwo)
# Передача кортежей и словарей в функции
def powersum(power, *args):
"""Возвращает сумму аргументов, возведённых в указанную степень."""
total = 0
for i in args:
total += pow(i, power)
return total
print(powersum(2, 3, 3))
| false |
f8ce16390e17c424df40e7612d2d166037abe398 | AndyLee0310/108-1_Programming | /HW026.py | 591 | 4.34375 | 4 | """
計算出最小公倍數
輸入說明:
兩個正整數
輸出說明:
這兩個正整數的最小公倍數。
Sample input:
2
3
Sample output:
6
((維基百科,最小公倍數:
https://zh.wikipedia.org/wiki/%E6%9C%80%E5%B0%8F%E5%85%AC%E5%80%8D%E6%95%B8
"""
def number(x,y):
if x > y :
maxnum = x
else:
maxnum = y
while(True):
if ((maxnum % x == 0) and (maxnum % y == 0)):
lcm = maxnum
break
maxnum += 1
print(lcm)
x = int(input())
y = int(input())
number(x,y) | false |
9bf77702fe2c812f96a6e4adbb3d3061dabfff40 | AndyLee0310/108-1_Programming | /HW018.py | 1,791 | 4.125 | 4 | """
請使用 while loop或for loop
第一個輸入意義為選擇三種圖形:
1 三角形方尖方面向右邊
2 三角形方尖方面向左邊
3 菱形
第二個輸入意義為畫幾行
(奇數,範圍為 3,5,7,9,....,21)
input
1 (第一種圖形,三角形尖方面向右邊)
9 (共 9 行)
--------------------------
output
*
**
***
****
*****
****
***
**
*
---------------------------
input
2 (第二種圖形,三角形尖方面向左邊)
5 (共 5 行)
---------------------------
output
..*
.**
***
.**
..*
--------------------------
input
3 (第三種圖形: 菱形 )
3 (共 3 行數)
輸出
.*
***
.*
"""
def draw(a,t):
newt = int(t / 2)
if a == 1:
for v in range(newt+1):
for i in range(v+1):#根據外層行號,透過加1可以剛好等於星數
print('*',end='')
print('\n',end='')
for v in range(newt):
for i in range(newt-v):
print('*',end='')
print('\n',end='')
elif a == 2:
for v in range(newt):
for j in range(newt-v):
print('.',end='')
for i in range(v+1):#根據外層行號,透過加1可以剛好等於星數
print('*',end='')
print('\n',end='')
print('*'*(newt+1))
for v in range(newt):
for i in range(v+1):
print('.',end='')
for j in range(newt-v) :
print('*',end='')
print('\n',end='')
elif a == 3:
for i in range(1,newt + 2):
print('.'*(newt-i+1)+'*'*i+'*'*(i - 1))
for i in range(newt,0,-1):
print('.'*(newt-i+1)+'*'*i+'*'*(i - 1))
draw(int(input()),int(input())) | false |
e57a1246ce35b0a2bad2cd2002c18995ddd7d640 | GMwang550146647/network | /0.leetcode/0.基本数据结构/4.散列/4.2.解决散列冲突:数据项链chaining.py | 947 | 4.125 | 4 | #例如python的字典结构
'''
1.解决冲突hash函数实现示例):
问题:在数列【26,77,93,17,31,54】数列中查找是否存在某个数
解决:利用hashfunc= num%11的方法把数放在十一个槽中,每个槽都是一个数组
'''
class hashTable:
def __init__(self,arr,volumn=11):
self.hashTable=[[] for i in range(11)]
self.volumn=volumn
self.initHashtable()
print(self.hashTable)
'''1.1.存储算法'''
def initHashtable(self):
for num in arr:
index=num%self.volumn
self.hashTable[index].append(num)
'''1.2.查找算法'''
def findnum(self,num):
index=num%self.volumn
for i in range(len(self.hashTable[index])):
if num==self.hashTable[index][i]:
return True
return False
arr=[26,77,93,17,31,54,44,55]
ht=hashTable(arr)
print(ht.findnum(93))
print(ht.findnum(94))
| false |
8b61c267e2e4b0da7c2d3565709cdd0dce617ddb | GMwang550146647/network | /python基本语法/1.基本方法/1.0基本语法/9.闭包.py | 913 | 4.1875 | 4 | '''
闭包:
1.函数中定义的函数
2.外部函数把内部函数返回
3.这内部函数引用外部函数的值
作用:
1.保存并返回闭包时的状态(外层函数变量)
实现原理:
由于函数还没去除引用,所以其对应的内存尚未被消掉
'''
'''1.调用外层函数的值'''
def outterfunc(c):
a=100
def inner_func():
b=99
print(a,b,c)
print(locals())
return inner_func
x=outterfunc(10)
x()
'''2.调用同级函数'''
def outfun(c):
a=100
def innerfun1():
print(a,c)
def innerfun2():
print("innerfunc2:")
innerfun1()
return innerfun2
func=outfun(1000)
func()
'''3.闭包应用:计数器'''
def generateCounter():
counter=[0]
def add_one():
counter[0]+=1
print('第%d次访问'%counter[0])
return add_one
counter=generateCounter()
for i in range(5):
counter() | false |
4f63d8015f9941746f8d00760d7de222308dd31a | GMwang550146647/network | /1.networkProgramming/2.parallelProgramming/3.coroutines/2.pythonCoroutines/2.Awaitables.py | 2,275 | 4.15625 | 4 | """
三种 Awaitable Objects
1.Coroutines
2.Tasks
3.Futures
"""
import asyncio
import concurrent.futures
"""
1.Coroutines
async 包装的函数都会转换成一个Coroutines函数,如果没有await,函数不会调用,会返回Coroutines对象
"""
def coroutines():
"""用于直接运行的任务"""
async def nested():
return 42
async def main():
# Nothing happens if we just call "nested()".
# A coroutine object is created but not awaited,
# so it *won't run at all*.
print(nested())
# Let's do it differently now and await it:
print(await nested()) # will print "42".
asyncio.run(main())
"""
2.Tasks
用于automatically schedule的任务
"""
def tasks():
async def nested():
return 42
async def main():
# Schedule nested() to run soon concurrently
# with "main()".
task = asyncio.create_task(nested())
# "task" can now be used to cancel "nested()", or
# can simply be awaited to wait until it is complete:
await task
asyncio.run(main())
"""
3.Futures
"""
def blocking_io():
# File operations (such as logging) can block the
# event loop: run them in a thread pool.
with open('/dev/urandom', 'rb') as f:
return f.read(100)
def cpu_bound():
# CPU-bound operations will block the event loop:
# in general it is preferable to run them in a
# process pool.
return sum(i * i for i in range(10 ** 7))
async def main():
loop = asyncio.get_running_loop()
## Options:
# 1. Run in the default loop's executor:
result = await loop.run_in_executor(
None, blocking_io)
print('default thread pool', result)
# 2. Run in a custom thread pool:
with concurrent.futures.ThreadPoolExecutor() as pool:
result = await loop.run_in_executor(
pool, blocking_io)
print('custom thread pool', result)
# 3. Run in a custom process pool:
with concurrent.futures.ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(
pool, cpu_bound)
print('custom process pool', result)
asyncio.run(main())
if __name__ == '__main__':
# coroutines()
# tasks()
# futures()
pass
| true |
9c93463506fcd2ddf6ba8b205ab3a7f27ebaf944 | Azure-Whale/Kazuo-Leetcode | /Array/238. Product of Array Except Self.py | 2,176 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File : 238. Product of Array Except Self.py
@Time : 10/21/2020 10:37 PM
@Author : Kazuo
@Email : azurewhale1127@gmail.com
@Software: PyCharm
'''
class Solution:
"""
The solution is to create two lists within same length as the given array, since each product consist of ele[:i]
and ele[i+1:], store left product part and right product part into two created lists respectively, then using these
two array, you build you a new list as your answer
"""
def productExceptSelf(self, nums: List[int]) -> List[int]:
# The length of the input array
length = len(nums)
# The left and right arrays as described in the algorithm
L, R, answer = [0] * length, [0] * length, [0] * length
# L[i] contains the product of all the elements to the left
# Note: for the element at index '0', there are no elements to the left,
# so the L[0] would be 1
L[0] = 1
for i in range(1, length):
# L[i - 1] already contains the product of elements to the left of 'i - 1'
# Simply multiplying it with nums[i - 1] would give the product of all
# elements to the left of index 'i'
L[i] = nums[i - 1] * L[i - 1]
# R[i] contains the product of all the elements to the right
# Note: for the element at index 'length - 1', there are no elements to the right,
# so the R[length - 1] would be 1
R[length - 1] = 1
for i in reversed(range(length - 1)):
# R[i + 1] already contains the product of elements to the right of 'i + 1'
# Simply multiplying it with nums[i + 1] would give the product of all
# elements to the right of index 'i'
R[i] = nums[i + 1] * R[i + 1]
# Constructing the answer array
for i in range(length):
# For the first element, R[i] would be product except self
# For the last element of the array, product except self would be L[i]
# Else, multiple product of all elements to the left and to the right
answer[i] = L[i] * R[i]
return answer | true |
9944355759d50508317cfbe562587bf93c874357 | Smoearn/katas | /python/kt7/short_word.py | 663 | 4.1875 | 4 | # def find_short(s):
# container = s.split(' ')
# max_lengt = len(s)
# for i in container:
# if len(i) < max_lengt:
# max_lengt = len(i)
# return max_lengt # l: shortest word length
def find_short(s):
return min([len(x) for x in s.split(' ')])
print(find_short("bitcoin take over the world maybe who knows perhaps"), 3)
print(find_short("turns out random test cases are easier than writing out basic ones"), 3)
print(find_short("lets talk about javascript the best language"), 3)
print(find_short("i want to travel the world writing code one day"), 1)
print(find_short("Lets all go on holiday somewhere very cold"), 2) | false |
ad4e5783ab8452552b9e606143057fab8bfcdf84 | Hunters422/Basic-Python-Coding-Projects | /python_if.py | 290 | 4.25 | 4 | num1 = 12
key = True
if num1 == 12:
if key:
print('Num1 is equal to Twelve and they have the key!')
else: print('Num1 is equal to Twelve and they do no have the key!')
elif num1 < 12:
print('Num1 is less than Twelve!')
else:
print('Num1 is not eqaul to Twelve!')
| true |
f1b18f3fc959db741f9d42643a149d175dd1f162 | zeejaykay/Python_BootCamp | /calculator.py | 1,753 | 4.34375 | 4 |
# using while loop to continuously run the calculator till the user wants to exit
while(True):
print("\n Zaeem\'s Basic Calculator\n")
print("Please enter two numbers on which you wish to perform calculation's and the operand\n") # displaying instructions
num_1 = input("Please enter the 1st number:\n") # taking input from user
# error checking for invalid number entry
try:
num_1 = int (num_1)
except:
print("Invalid number entered")
continue
num_2 = input("please enter the 2nd number: \n")
try:
num_2 = int (num_2)
except:
print("Invalid number entered")
continue
operator = input("Please enter the operator: \n")
if operator != '+' and operator != '*' and operator != '-' and operator != '/': # error checking for invalid entry in operator
print("Invalid operator")
continue
# Calculating for each operation and displaying only the operation requested by the user
if operator == "+":
result = num_1 + num_2
print("your calculation result is:", result, "\n")
elif operator == "-":
result = num_1 - num_2
print("your calculation result is: %d \n" % result)
elif operator == "*":
result = num_1 * num_2
print("your calculation result is: %d \n" % result)
elif operator == "/":
result = num_1 / num_2
print("your calculation result is %d \n" %(result))
# Asking user whether he wants to continue using calculator
con=input("if you wish to continue press Y, or press N to end program:\n")
if con == 'Y':
continue # returns to top of loop starts calculating again
else:
break # Ending the program
print("\n end of program")
| true |
88e69cba39a474480bfb14b421a2e600392199b9 | TrendingTechnology/rnpfind | /website/scripts/picklify.py | 1,863 | 4.25 | 4 | """
Picklify is a function that works similar to memoization; it is meant for
functions that return a dictionary. Often, such functions will parse a file to
generate a dictionary that maps certain keys to values. To save on such overhead
costs, we "picklify" them the first time they are called (save the dictionary in
a pickle file), and then simply load the dictionary from the saved pickle files
the next time around.
"""
import pickle
def picklify(dict_generator, *args, **kwargs):
"""
Given a function that returns an object such as a dictionary (only dict
fully supported), returns the dictionary generated by the function. The
function is only called if it has not been "picklified" (passed as an
argument to this function) before. Otherwise, its cached dictionary is
returned instead. Thus getting the dicttionary by wrapping this function
speeds up the dictionary creation overall.
Note that this function should not be called by two different functions with
the same name.
:param dict_generator: the function which generates a dictionary.
:param *args: Any args to pass to the dictionary
:param **kwargs: Any keyword args to pass to the dictionary.
:returns: dictionary returned by dict_generator().
"""
# Danger! Never call picklify with functions that have the same name!
pickle_path = (
"./website/output-data/pickles/" + dict_generator.__name__ + ".pickle"
)
try:
with open(pickle_path, 'rb') as pickle_handle:
dict_to_return = pickle.load(pickle_handle)
except FileNotFoundError:
dict_to_return = dict_generator(*args, **kwargs)
with open(pickle_path, 'wb') as pickle_handle:
pickle.dump(
dict_to_return, pickle_handle, protocol=pickle.HIGHEST_PROTOCOL
)
return dict_to_return
| true |
03ce63b031ca790b622d518b4b8813642fdf46b6 | Gafficus/Delta-Fall-Semester-2014 | /CST-186-14FA(Intro Game Prog)/N.G.Chapter5/N.G.Project2.py | 954 | 4.53125 | 5 | #Created by: Nathan Gaffney
#21-Sep-2014
#Chapter 5 Project 1
#This program tell the user where they would go.
directions = {"north" : "Going north leads to the kitchen.",
"south" : "GOing south leads to the dining room.",
"east" : "Going east leads to the entry.",
"west" : "Going west leads to the living room."}
whereToGo = raw_input("Enter a direction \'north\', \'south\', \'east\'," +
"\'west\',\'exit\'(To quit): ")
while whereToGo!= "exit":
if whereToGo == "north":
print directions.get("north")
elif whereToGo == "south":
print directions.get("south")
elif whereToGo == "west":
print directions.get("west")
elif whereToGo == "east":
print directions.get("east")
else:
print ("Invalid data.")
whereToGo = raw_input("Enter a direction \'north\', \'sout\', \'east\'," +
"\'west\',\'exit\'(To quit): ")
| true |
4fc3b1c621eeaf45191631dd72e5f2a34251efc3 | odora/CodesNotes | /Python_100_examples/example1.py | 1,947 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/1/26 16:45
@Author : cai
examples come from http://www.runoob.com/python/python-exercise-example1.html
"""
# ============== Example 1 ======================================
# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
# ===============================================================
def create_three_digits(number_start=1, number_end=4):
'''
给定指定数字范围(比如1到4),求可以组成多少个无重复的三位数
:param number_start: 起始数字
:param number_end: 结束数字
:return: 返回数量,以及可能的三位数的列表
'''
count = 0
result_list = list()
for i in range(number_start, number_end + 1):
for j in range(number_start, number_end + 1):
for k in range(number_start, number_end + 1):
if (i != j) and (i != k) and (j != k):
count += 1
result_list.append(str(i) + str(j) + str(k))
return count, result_list
def create_three_digits2(number_start=1, number_end=4):
'''
采用列表推导式实现
:param number_start:
:param number_end:
:return:
'''
return [str(i) + str(j) + str(k) for i in range(number_start, number_end + 1) for j in
range(number_start, number_end + 1) for k in
range(number_start, number_end + 1) if (i != j) and (i != k) and (j != k)]
if __name__ == '__main__':
count, result_list = create_three_digits(number_start=1, number_end=4)
print('valid count={}, and they are:'.format(count))
for result in result_list:
print(result)
result2 = create_three_digits2(number_start=1, number_end=4)
print('numbers:', len(result2))
for result in result2:
print(''.join(str(result[:])))
| false |
64f04193517dea19c5cced41fbceb9093f5f229a | javabyranjith/python | /py-core/string/string-fn.py | 295 | 4.15625 | 4 | name = 'Ranjith'
print(len(name))
print(name.count('a'))
print(name.upper()) # original string won't be modified
print(name.lower())
print(name.find('j'))
print(name.find('H')) # find returns index
print(name.find('an'))
print(name.replace('ji', 'gi'))
print('jith' in name) # checks contains
| false |
dc04fb45db7a16bae44deaebf0e4c7729f46c6ca | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 10 Tuples/Code/Lab 10.6 Tuples are Comparable.py | 488 | 4.125 | 4 | __author__ = 'Kevin'
# 08/04/2015
# Tuples are Comparable
# The comparison operators work with tuples and other sequences. If the first item is equal, Python goes on to the
# next element, and so on, until it finds elements that differ.
print (0, 1, 2) < (5, 1, 2)
# True
print (0, 1, 2000000) < (0, 3, 4)
# True
print ( 'Jones', 'Sally' ) < ('Jones', 'Sam')
# True
print ( 'Jones', 'Sally') > ('Adams', 'Sam')
# True
print ( 'Jones', 'Sally') < ('Adams', 'Sam')
# False
True
False | true |
3a7ecaea275e0022dc6bb928872e6d9a11360ef7 | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 9 Dictionaries/Code/Lab 9.10 Two Iteration Variables.py | 844 | 4.28125 | 4 | __author__ = 'Kevin'
# 06/04/2015
# We loop through the key-value pairs in a dictionary using *two* iteration variables.
# Each iteration, the first variable is the key and the second variable is the corresponding value for the key.
jjj = {'chuck': 1, 'fred': 42, 'jan': 100}
for aaa,bbb in jjj.items():
print aaa, bbb
# jan 100
# chuck 1
# fred 42
# find the most common word in a text file.
# /Users/Kevin/Desktop/Programming for Everybody/Week 8/Data/romeo.txt
name = raw_input('Enter file:')
handle = open(name)
text = handle.read()
words = text.split()
counts = dict()
for word in words:
counts[word] = counts.get(word,0) + 1
print counts
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print bigword, bigcount | true |
b9516444d75abd0141d923136db6dfe47c7ad99d | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 8 Lists/Code/Lab 8.10 Building a list from scratch.py | 448 | 4.4375 | 4 | __author__ = 'Kevin'
# 05/04/2015
# BUILDING A LIST FROM SCRATCH
# We can create an empty list and then add elements using the append method
stuff = list()
print stuff
stuff.append("book")
print stuff
other_stuff = []
print other_stuff
other_stuff.append("other book")
print other_stuff
# The list stays in order and new elements are added at the end of the list
stuff.append("more")
other_stuff.append("junk")
print stuff
print other_stuff | true |
18a316129cc590ba81d98d033617cd7776154603 | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 7 Files/Code/Lab 7.1 Opening a File.py | 849 | 4.125 | 4 | __author__ = 'Kevin'
# 24/03/2015
# Opening a File
# Before we can read the contents of the file, we must tell Python which file we are going to work with and what we will
# be doing with the file
# This is done with the open() function
# open() returns a 'file handle' - a variable used to perform operations on the file
# Similar to 'File -> Open' in a Word Processor
# Using open()
# handle = open(filename, mode)
# returns a handle use to manipulate the file
# filename is a string
# mode is optional and should be 'r' if we are planning to read the file and 'w' if we are going to write to the file
# What is a Handle?
fhand = open("/Users/Kevin/Desktop/Programming for Everybody/Week 7/Data/mbox-short.txt", "r") # r is read access
print fhand
# below will not work
test = open("mbox-short.txt", "r") # r is read access
print test
| true |
51ce3c640601771132427ca633d37b66e0d86302 | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 3 Conditional/Week 3.3 Try and Except.py | 340 | 4.25 | 4 | # You surround a dangerous section of code with try and except
# If the code in the try works - the except is skipped
# If the code in the try fails - it jumps to the except section
astr = 'Hello Bob'
try:
istr = int(astr)
except:
istr = -1
print "First",istr
astr = '123'
try:
istr = int(astr)
except:
istr = -1
print 'Secomd',istr | true |
1c323c793a58d3736ccbec00ffbccb447f7ca21c | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 9 Dictionaries/Code/Lab 9.8 Definite Loops and Dictionaries.py | 376 | 4.4375 | 4 | __author__ = 'Kevin'
# 06/04/2015
# Even though dictionaries are not stored in order, we can write a for loop that goes through all the entries in a
# dictionary - actually it goes through all of the keys in the dictionary and looks up the values
counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
for key in counts:
print key, counts[key]
# jan 100
# chuck 1
# fred 42
| true |
44df3f26086799bea3f88ec4e814ee785fba53ef | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 8 Lists/Code/Lab 8.1 Lists Introduction.py | 1,057 | 4.1875 | 4 | __author__ = 'Kevin'
# 01/04/2015
# A List is a kind of Collection
# - A collection allows us to put many values in a single "variable"
# - A collection is nice because we can carry all many values around in one convenient package.
friends = ['Joseph', 'Glenn', 'Sally']
carryon = ['socks', 'shirt', 'perfume']
print friends
print carryon
# WHAT IS NOT A COLLECTION
# Generally variables have one value in them, when we put a new value in them the olc one is overwritten
# Example
x = 2
x = 4
print x
# LIST CONSTANTS
# List constants are surrounded by square brackets and the elements in the list are separated by commas
print [1, 24, 76]
print ['red', 'yellow', 'blue']
# A list element can be any Python object - even another list
print [1, [5, 6], 7]
# A list can be empty
print []
# EXAMPLE USING LISTS ALREADY
for i in [1,2,3,4,5]:
print i
print "i dont care"
# LISTS AND DEFINITE LOOPS WORK QUITE WELL TOGETHER
friends = ["lads", "college", "work"]
for friend in friends:
print "Great bunch of lads", friend
print "well done"
| true |
151748740604378d807b3bc5fd24e1be09c73350 | kevmct90/PythonProjects | /Python-Programming for Everybody/Week 6 Strings/Code/Lab 6.15 Making everythin UPPERCASE.py | 350 | 4.21875 | 4 | __author__ = 'Kevin'
# 23/03/2015
# You can make a copy of a string in lower case or upper case.
# Often when we are searching for a string using find() - we first convert the string to lower case
# so we can search a string regardless of case.
greet = 'Hello Bob'
nnn = greet.upper()
print nnn
# HELLO BOB
www = greet.lower()
print www
# hello bob
| true |
4ff057f5206a6d6509d5de02f88c51b495ae9bda | ScoJoCode/ProjectEuler | /problem19/main.py | 881 | 4.15625 | 4 | import time
start = time.time()
def isLastDay(day,year,month):
if day==31 and (month==1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
return True
if day==30 and (month ==4 or month == 6 or month == 9 or month == 11):
return True
if month == 2 and day==28:
if year%4!=0 or (year%4==0 and year%100==0 and year%400!=0):
return True
if month == 2 and day==29:
return True
return False
sum = 0
year = 1900
weekday = 2
monthDay = 1
month = 1
while year<2001:
if monthDay==1 and weekday==1 and year >1900:
sum+=1
#if monthDay>27
if isLastDay(monthDay,year,month):
if month==12:
month = 1
year+=1
else:
month+=1
monthDay=1
else:
monthDay+=1
if weekday==7:
weekday=1
else:
weekday+=1
end = time.time()
print sum
print 'time elapsed: ' + str(end-start)
| true |
ce602fd6526a830a0bab118951cb9a16c21efd8e | shivam0071/exploringPython | /Python_2018/Customizing_String_Formatting.py | 1,024 | 4.28125 | 4 | # Customizing String Formatting
_formats = {
'ymd' : '{d.year}-{d.month}-{d.day}',
'mdy' : '{d.month}/{d.day}/{d.year}',
'dmy' : '{d.day}/{d.month}/{d.year}'
}
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, code):
if code == '':
code = 'ymd'
fmt = _formats[code]
return fmt.format(d=self)
if __name__ == '__main__':
p = Date(2017, 12, 15)
# print(p.__format__('dmy'))
print(format(p))
print(format(p, 'dmy'))
# >>> d = Date(2012, 12, 21)
# >>> format(d)
# '2012-12-21'
# >>> format(d, 'mdy')
# '12/21/2012'
# >>> 'The date is {:ymd}'.format(d)
# 'The date is 2012-12-21'
# >>> 'The date is {:mdy}'.format(d)
# 'The date is 12/21/2012'
# The __format__() method provides a hook into Python’s string formatting functionality.
# It’s important to emphasize that the interpretation of format codes is entirely up
# to the class itself
# GITHUB CHECK PYCHARM
| false |
3d698dbd2f2e42af6f8abdd40e96d43c5bcf409a | LiawKC/CS-Challenges | /GC08.py | 627 | 4.21875 | 4 | weight = float(input("What is your weight"))
height = float(input("What is your height in m"))
BMI = weight / height**2
print(BMI)
if BMI < 18.5:
print("Bro head to mcdonalds have a big mac or 2 you're probably anorexic")
if BMI < 25 and BMI > 18.5:
print("Ok, you're average but don't get fat or we will have an obesity problem and we don't need more of that")
if BMI < 30 and BMI > 25:
print("Bro chill you're pretty fat lay off the big macs bro get a salad")
if BMI > 30:
print("BRO HEAD TO THE HOSPITAL! BRO CHILL! CHILL!!! GET A DOCTOR! GET SOME OXYGEN BRO YOU HAVE TYPE 2 DIABETES")
| true |
ed224eb604a4783850d5dbecb0b25f0c582fcdc8 | sgetme/python_turtle | /turtle_star.py | 1,104 | 4.1875 | 4 |
# first we need to import modules
import turtle
from turtle import *
from random import randint
# Drawing shape
# I prefer doing this with a function
def main():
# set background color of turtle
bgcolor('black')
# create a variable called H
H = 1
# set speed of turtle
speed(0)
# I prefer hiding turtle during drawing
hideturtle()
# NOw I have to use while loop
while H < 350:
# set up random rgb color to your drawing
r = randint(0,255)
g = randint(0,255)
b = randint(0,255)
# set pen color
colormode(255)
pencolor(r,g,b)
# now pen up your turtle
penup()
forward(H)
right(95)
# pendown()
forward(H)
dot()
H = H + 1
done()
# call main test
main()
# now run your code using terminal or and other IDE
# Look if we change the line style to dot()
# Lets is change the turning angle
'''
Thank you for watching !
Please subscribe my Channel
'''
| true |
980e284b513a95820bae35101c10120b4dd1e208 | MohamedNour95/Py-task1 | /problem9.py | 240 | 4.5 | 4 | PI = 3.14
radius = float(input('Please enter the radius of the circle:'))
circumference = 2 * PI * radius
area = PI * radius * radius
print("Circumference Of the Circle = "+ str(circumference))
print("Area Of the Circle = "+ str(area)) | true |
4ec65a6426dfa1e36d68db08cdeb274fca9840d3 | miliart/ITC110 | /nth_fibonacci_ch8.py | 1,116 | 4.25 | 4 | # A program to calculate the nth spot in the Fibonacci
# Per assignment in the book we start at 1 instead of which is the result of 0 plus 1
# by Gabriela Milillo
def main():
n= int(input("Enter a a spot in the Fibonacci sequence: "))#variable n is the user input
#per the book Fibonacci sequence starts at 1, otherwise it'll be num1=0
num1=1 #first spot in the seq
num2=1 #second spot in the seq
#run the loop n times, n is the spot in the Fibonacci sequence
for i in range(2,n): #the second spot
#print for testing
print("num1 = " + str(num1))
print("num2 = " + str(num2))
#assigning the sum of the next spot in the sequence
sum = num1 + num2
print("sum = " + str(sum))
#the new num1 now equals num2 in the Fibonacci sequence
num1=num2
print()
#the new num2 now equals the sum of num1 + num2 in the Fibonacci sequence
num2=sum
print()
#output of what the number in that spot in the Fibonacci sequence is
print("the "+ str(n)+"th/nth spot in the seq. is "+ str(num2))
main()
| true |
4a430ff5e8d1f8fdea9d8cad3f5656a39211ced9 | mdhatmaker/Misc-python | /interview-prep/geeks_for_geeks/stack_and_queue/queue_using_two_stacks.py | 1,372 | 4.15625 | 4 | import sys
# https://practice.geeksforgeeks.org/problems/queue-using-two-stacks/1
# Implement a Queue using 2 stacks s1 and s2.
###############################################################################
class Stack:
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append(x)
def pop(self):
return self.stack.pop()
def clear(self):
self.stack.clear()
s1 = Stack()
s2 = Stack()
q = []
def enq(x):
q.append(x)
return
def deq():
if len(q) == 0:
return -1
else:
return q.pop(0)
def process_queue_commands(arr):
s1.clear()
s2.clear()
q.clear()
values = []
i = 0
while i < len(arr):
if arr[i] == 1:
i += 1
enq(arr[i])
elif arr[i] == 2:
x = deq()
values.append(x)
i += 1
return values
###############################################################################
if __name__ == "__main__":
test_inputs = []
test_inputs.append( ("1 2 1 3 2 1 4 2", "2 3") )
test_inputs.append( ("1 2 2 2 1 4", "2 -1") )
""" Run process on sample inputs
"""
for inputs, results in test_inputs:
arr = [int(s) for s in inputs.split()]
print(f'{arr}')
rv = process_queue_commands(arr)
print(f"{rv} expected: {results}\n")
| false |
10fdb82b732b524a4a9526758e8579e468f9aae0 | mdhatmaker/Misc-python | /interview-prep/geeks_for_geeks/bit_magic/rotate_bits.py | 1,506 | 4.40625 | 4 | import sys
# https://practice.geeksforgeeks.org/problems/rotate-bits/0
# https://wiki.python.org/moin/BitwiseOperators
# Given an integer N and an integer D, you are required to write a program to
# rotate the binary representation of the integer N by D digits to the left as well
# as right and print the results in decimal values after each of the rotation.
# Note: Integer N is stored using 16 bits. i.e. 12 will be stored as 0000.....001100.
###############################################################################
# Print integer as binary digits (string)
def bits(n):
print("{0:b}".format(n))
# Assume 16-bit values when performing rotation
def rotate_bits(n, d):
mask = (1 << d) - 1
lowbits = n & mask
mask = ((1 << (16)) - 1) ^ ((1 << 16-d) - 1)
hibits = n & mask
hibits = hibits >> (16-d)
mask = lowbits << 16-d
shift_right = (n >> d) | mask
shift_left = (n << d) & 0xFFFF | hibits
return (shift_left, shift_right)
###############################################################################
if __name__ == "__main__":
test_inputs = []
test_inputs.append( (229, 3, (1832, 40988)) )
test_inputs.append( (28, 2, (112, 7)) )
test_inputs.append( (50000, 4, (13580, 3125)) )
""" Run process on sample inputs
"""
for n, d, results in test_inputs:
#arr = [int(s) for s in inputs.split()]
print(f'{n}, {d}')
rotated = rotate_bits(n, d)
print(f"{rotated} expected: {results}\n")
| true |
9dcbb78a4064439289522558200e106eb204d665 | mdhatmaker/Misc-python | /interview-prep/geeks_for_geeks/divide_and_conquer/binary_search.py | 1,507 | 4.1875 | 4 | import sys
# https://practice.geeksforgeeks.org/problems/binary-search/1
# Given a sorted array A[](0 based index) and a key "k" you need to complete
# the function bin_search to determine the position of the key if the key
# is present in the array. If the key is not present then you have to return -1.
# The arguments left and right denotes the left most index and right most index
# of the array A[]. There are multiple test cases. For each test case, this function
# will be called individually.
###############################################################################
def binary_search(arr, k, l, r):
if l > r:
return -1
mid = int((l + r) / 2)
if k < arr[mid]:
return binary_search(arr, k, l, mid)
elif k > arr[mid]:
return binary_search(arr, k, mid+1, r)
else: #k == arr[mid]:
return mid
# Function to call the binary search functio with the correct left (l) and right (r) parameters
def search_for(arr, k):
return binary_search(arr, k, 0, len(arr)-1)
###############################################################################
if __name__ == "__main__":
test_inputs = []
test_inputs.append( (4, "1 2 3 4 5", 3) )
test_inputs.append( (445, "11 22 33 44 55", -1) )
""" Run process on sample inputs
"""
for k, inputs, results in test_inputs:
arr = [int(s) for s in inputs.split()]
print(f'{k}, {arr}')
ix = search_for(arr, k)
print(f"{ix} expected: {results}\n")
| true |
52fa21fa353bc13fb7439569009b710fa37b6a46 | mdhatmaker/Misc-python | /interview-prep/geeks_for_geeks/tree_and_bst/print_bottom_view.py | 2,329 | 4.34375 | 4 | import sys
from BinaryTree import BinaryNode, BinaryTree
from StackAndQueue import Stack, Queue
# https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1
# Given a binary tree, print the bottom view from left to right.
# A node is included in bottom view if it can be seen when we look at the tree from bottom.
#
# 20
# / \
# 8 22
# / \ \
# 5 3 25
# / \
# 10 14
#
# For the above tree, the bottom view is 5 10 3 14 25.
# If there are multiple bottom-most nodes for a horizontal distance from root, then
# print the later one in level traversal. For example, in the below diagram, 3 and 4
# are both the bottommost nodes at horizontal distance 0, we need to print 4.
#
# 20
# / \
# 8 22
# / \ / \
# 5 3 4 25
# / \
# 10 14
#
# For the above tree the output should be 5 10 4 14 25.
###############################################################################
def traverse(node, hd = 0, hd_dict = {}):
if not node: return
#print(node.data, hd, end=' ')
hd_dict[hd] = node
traverse(node.left, hd-1, hd_dict)
traverse(node.right, hd+1, hd_dict)
return [n for n in hd_dict.values()]
def print_bottom_view(root_node):
if not root_node: return
#BinaryTree.print_bt(root_node)
hds = traverse(root_node)
print(hds)
return
###############################################################################
if __name__ == "__main__":
test_inputs = []
test_inputs.append( ("1 2 R 1 3 L", "3 1 2") )
test_inputs.append( ("10 20 L 10 30 R 20 40 L 20 60 R", "40 20 60 30") )
test_inputs.append( ("20 8 L 20 22 R 8 5 L 8 3 R 3 10 L 3 14 R 22 25 R", "5 10 3 14 25") )
test_inputs.append( ("20 8 L 20 22 R 8 5 L 8 3 R 3 10 L 3 14 R 22 4 L 22 25 R", "5 10 4 14 25") )
""" Run process on sample inputs
"""
for inputs, results in test_inputs:
#arr = [s for s in inputs.split()]
print(f'{inputs}')
tree = BinaryTree.make_tree(inputs)
print_bottom_view(tree)
print(f" expected: {results}\n")
| true |
5c29aa549d09b85456b9ee25e5895d9aefd369dd | pi-bansal/studious-happiness | /DP_Practice/Tabulation/how_sum.py | 887 | 4.125 | 4 | def how_sum(target_sum, numbers):
# Expected return is an array of integers that add up to target_sum
if target_sum == 0:
# Zero using empty array
return []
# Init the table with null values
sum_table = [None] * (target_sum + 1)
# Seed value for 0
sum_table[0] = []
for index in range(target_sum):
if sum_table[index] is not None:
for num in numbers:
result = num + index
if result == target_sum:
return sum_table[index] + [num]
try:
sum_table[result] = sum_table[index] + [num]
except IndexError:
#print('Index out of range')
pass
return sum_table[target_sum]
print(how_sum(7, [3, 5, 4]))
print(how_sum(100, [99, 3]))
print(how_sum(100, [1, 2, 5, 25]))
| true |
d25cbf0e3769be7d5e4e4a71d2b4deaebd721052 | pi-bansal/studious-happiness | /DP_Practice/memoization/how_sum_basic.py | 645 | 4.125 | 4 | def how_sum(target_sum, numbers):
"""Function that return a subset of numbers that adds up to the target_sum"""
if target_sum == 0:
return []
if target_sum < 0:
return False
for num in numbers:
remainder = target_sum - num
return_val = how_sum(remainder, numbers)
if return_val != False:
return_val.append(num)
return return_val
return False
print(how_sum(7,[3,4,5]))
print(how_sum(7,[2,4,5]))
print(how_sum(300,[7, 14]))
# import timeit
# print(timeit.timeit('[how_sum(*args) for args in [(7,[3,4,5]),(97,[3,4,5]),(300,[7,14])]]', globals=globals())) | true |
3c4a36e49bff8e952264bf32b54f59a734ef7535 | vv1nn1/dsp | /python/q8_parsing.py | 1,679 | 4.625 | 5 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
def read_data(filename):
"""Returns a list of lists representing the rows of the csv file data.
Arguments: filename is the name of a csv file (as a string)
Returns: list of lists of strings, where every line is split into a list of values.
ex: ['Arsenal', 38, 26, 9, 3, 79, 36, 87]
"""
with open(filename,'r') as f:
data = [row for row in csv.reader(f.read().splitlines())]
return data
def get_index_with_min_abs_score_difference(goals):
"""Returns the index of the team with the smallest difference
between 'for' and 'against' goals, in terms of absolute value.
Arguments: parsed_data is a list of lists of cleaned strings
Returns: integer row index
"""
goals.pop(0)
goal = [x[5] for x in goals]
allow = [x[6] for x in goals]
diff = [abs(float(x)-float(y)) for x,y in zip(goal,allow)]
return diff.index(min(diff))
def get_team(index_value, parsed_data):
"""Returns the team name at a given index.
Arguments: index_value is an integer row index
parsed_data is the output of `read_data` above
Returns: the team name
"""
teams = [x[0] for x in parsed_data]
return teams[index_value]
| true |
d92f3b6c81eff37101c26324694e872272f8762c | leerobert/python-nltk-intro | /code/process.py | 1,022 | 4.125 | 4 | # Sample code for processing a file containing lines of raw text
import nltk
raw = open("reviews.txt").read() # read in the entire file as a single raw string
tokens = nltk.word_tokenize(raw) # tokenizes the raw string
text = nltk.Text(tokens) # generate the text object
# Cleaning the text of punctuation
import re
clean_text = ["".join(re.split("[.,;:!?'`-]", word)) for word in text]
# Generating the list of stopwords
from nltk.corpus import stopwords
stopwords = stopwords.words("english")
important_words = [word for word in clean_text if word.lower() not in stopwords]
# Adding to the list of stop words our own "black-list"
more_stopwords = ["", "nt", "cyberdyne"]
for word in stopwords:
more_stopwords.append(word)
important_words = [word for word in clean_text if word.lower() not in more_stopwords]
# Lastly, we can normalize the text by lowercasing all the words
lower_important_words = [word.lower() for word in important_words]
# Print the list to standard out
print lower_important_words
| true |
e8b0861e65e8dde5a5eeb13f52763988cb0ac317 | szhao13/interview_prep | /stack.py | 498 | 4.125 | 4 | class Stack(object):
def __init__(self):
"""Initialize an empty stack"""
self.items = []
def push(self, item):
"""Push new item to stack"""
self.items.append(item)
def pop(self):
"""Remove and return last item"""
# If the stack is empty, return None
# (it would also be reasonable to throw an exception)
if not self.items:
return None
return self.items.pop()
def peek(self):
"""See what the last item is"""
if not self.items:
return None
return self.items[-1] | true |
2c5569c99d54e1fa5aa523b6071862f237bc6334 | DemondLove/Python-Programming | /CodeFights/28. alphabetShift.py | 951 | 4.3125 | 4 | '''
Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a).
Example
For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz".
Input/Output
[execution time limit] 4 seconds (py3)
[input] string inputString
A non-empty string consisting of lowercase English characters.
Guaranteed constraints:
1 ≤ inputString.length ≤ 1000.
[output] string
The resulting string after replacing each of its characters.
'''
import string
def alphabeticShift(inputString):
alphabet = [x for x in string.ascii_lowercase]
inputString = [x for x in inputString]
for i in range(len(inputString)):
alpha = alphabet.index(inputString[i])
if alpha == 25:
inputString[i] = 'a'
else:
inputString[i] = alphabet[alpha+1]
return ''.join(inputString)
| true |
fc2a2ca8d11b1c90f35118263132230e1b544ebb | DemondLove/Python-Programming | /CodeFights/42. Bishop and Pawn.py | 1,450 | 4.125 | 4 | '''
Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move.
The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move:
Example
For bishop = "a1" and pawn = "c3", the output should be
bishopAndPawn(bishop, pawn) = true.
For bishop = "h1" and pawn = "h3", the output should be
bishopAndPawn(bishop, pawn) = false.
Input/Output
[execution time limit] 4 seconds (py3)
[input] string bishop
Coordinates of the white bishop in the chess notation.
Guaranteed constraints:
bishop.length = 2,
'a' ≤ bishop[0] ≤ 'h',
1 ≤ bishop[1] ≤ 8.
[input] string pawn
Coordinates of the black pawn in the same notation.
Guaranteed constraints:
pawn.length = 2,
'a' ≤ pawn[0] ≤ 'h',
1 ≤ pawn[1] ≤ 8.
[output] boolean
true if the bishop can capture the pawn, false otherwise.
'''
def bishopAndPawn(bishop, pawn):
dictRange = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}
bishopLi, pawnLi = list(bishop), list(pawn)
firstValMax = max(dictRange[bishopLi[0]],dictRange[pawnLi[0]])
firstValMin = min(dictRange[bishopLi[0]],dictRange[pawnLi[0]])
secondValMax = max(int(bishopLi[1]),int(pawnLi[1]))
secondValMin = min(int(bishopLi[1]),int(pawnLi[1]))
return firstValMax-firstValMin == secondValMax-secondValMin
| true |
ce389515649fc3224a7175abeb1ed89ff8b5743e | makassigithub/core-python | /Book/chapter6.py | 2,867 | 4.25 | 4 | #6.1 Écrivez un programme qui convertisse en mètres par seconde et en km/h une vitesse fournie
#par l’utilisateur en miles/heure. (Rappel : 1 mile = 1609 mètres)
#mp = float(input("enter speed :\n"))
#print("the equivalent in km/h is: ", (mp*1609)/1000)
#print("the equivalent in m/ is: ", ((mp*1609)/1000)*1000/3600)
#######################################################################
def isPremier(n):
'''
Cette fonction permet de verifier si le nombre est premier. Elle est aussi performante car
elle imprime True quand elle trouve le premier diviseur de n
:param n: doit etre te type in, la valeur à passer a la fonction
:return: la fonction ne retourne un boolean
'''
for i in range(2,n):
print(i) # affiche les valeurs successives de position
if n % i == 0:
return False # return False pour la premiere valeur qui divise n
return True # si auncune valeur n'est trouvé entre 2 et n-1, on quitte la boucle et return True
#######################################################################
def isPremier2(n):
'''
Cette fonction permet de verifier si le nombre est premier. Elle est aussi performante car
elle imprime True quand elle trouve le premier diviseur de n
:param n:
:return:
'''
position = 2
while position <= n-1:
print(position) # affiche les valeurs successives de position
if n % position == 0:
return False
position = position+1
return True
#######################################################################
def isPremier3(n):
'''
Retrouver la premiere valeur qui divise n
cette fonction optimise la recherche de notre de premier
:param n: doit etre te type in, la valeur à passer a la fonction
:return: la fonction ne retourne rien elle doit juste imprimer le resultat
'''
premier = True
position = 1 # nous incrementons position avant le traitememt qui commence a 2
while position <= n-2 and premier: # le boucle doit s'arreter a n-1, puisque nous incrementons position # avant la verification, nous allons à n-2
position = position+1 # affiche les valeurs successives de position
print(position)
premier = n % position != 0
if position == n-1: # si n est premier la valeur maximale de position sera n-1
return True
else:
return False
print('isPremier(99)',isPremier(99))
print('isPremier(137)',isPremier(137))
print('isPremier2(99)',isPremier3(99))
print('isPremier2(137)',isPremier3(137))
print('isPremier3(99)',isPremier3(99))
print('isPremier3(137)',isPremier3(137))
| false |
08cc42adae9c5077db60e1f49607b7a8c0fb9ddf | jaredscarr/data-structures | /linked_list.py | 2,235 | 4.125 | 4 | # -*- coding: utf-8 -*-
class Node(object):
"""Construct Node object."""
def __init__(self, val):
"""Initialize node object."""
self.val = val
self.next = None
class LinkedList(object):
"""Handle creation of a linked list."""
def __init__(self, iterable=None):
"""Init linked list object with optioanl itterable."""
self.head = None
self.iterable = iterable
if iterable is not None:
try:
for i in iterable:
self.insert(i)
except TypeError:
print('value is not an interable')
def insert(self, val):
"""Insert new node at head of list."""
new_node = Node(val)
new_node.next = self.head
self.head = new_node
def search(self, val):
"""Search for value and return node."""
current = self.head
found = False
while current and not found:
if current.val == val:
found = True
return current
current = current.next
return None
def pop(self):
"""Remove node at head and returns the value."""
current = self.head
new_head = current.next
self.head = new_head
return current.val
def remove(self, val):
"""Remove specific val."""
current = self.head
if current.val == val:
self.head = current.next
else:
while current.next.val != val:
try:
current = current.next
except AttributeError:
print('That node is not in the list.')
current.next = current.next.next
def size(self):
"""Return length of list."""
current = self.head
counter = 0
while current is not None:
counter += 1
current = current.next
return counter
def display(self):
"""Print list as tuple."""
container = []
current = self.head
while current is not None:
container.append(current.val)
current = current.next
print(tuple(container))
return tuple(container)
| true |
e3c870a1069eee7c09d0d2c66f7e1d7a04f8127c | jiangyu718/pythonstudy | /base/integrative.py | 509 | 4.15625 | 4 | listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)
def powersum(power, *args):
'''Return the sum of each argument raised to specified power.'''
total = 0
for i in args:
total += pow(i, power)
return total
exec('print(powersum(2,3,4))')
exec('print(powersum(2,10))')
eval('2+3*3') #去掉字符串的引号
mylist = ['item']
assert len(mylist) >= 1
mylist.pop()
#assert len(mylist) >= 1
i=[]
i.append('item')
print(i)
print(repr(i))
print(2*3) | true |
3ceab3ad04a845fcf81f46c24b4b612c7d7e3dc9 | booji/Exercism | /python/prime-factors/prime_factors.py | 707 | 4.28125 | 4 | import math
def prime_factors(natural_number):
factors = []
i = 2
# Find all prime '2' the remainder will be odd.
while natural_number%i == 0:
natural_number = natural_number // i
factors.append(i)
# Go up to sqrt(natural_number) as prime*prime cannot be greater then
# natural_number. Increment by 2 as no more even number remaining
for i in range(3,int(math.sqrt(natural_number))+1,2):
while natural_number%i == 0:
natural_number = natural_number // i
factors.append(i)
# add last value which will be prime if greater than 2
if natural_number > 2:
factors.append(natural_number)
return factors
| true |
790d11daed36af486c57a4cb4a017798b1a9dcc4 | SimonCCooke/CodeWars | /SmallestInteger.py | 446 | 4.1875 | 4 | """Given an array of integers your solution should find the smallest integer.
For example:
Given [34, 15, 88, 2] your solution will return 2
Given [34, -345, -1, 100] your solution will return -345
You can assume, for the purpose of this kata, that the supplied array will not be empty."""
def findSmallestInt(arr):
answer = arr[0]
for i in range(0,len(arr)):
if(answer > arr[i]):
answer = arr[i]
return answer
| true |
38f7f4defa13ac0cc35d78a54b90d7764f9e6116 | kwaper/iti0102-2018 | /pr08_testing/shortest_way_back.py | 1,586 | 4.25 | 4 | """Find the shortest way back in a taxicab geometry."""
def shortest_way_back(path: str) -> str:
"""
Find the shortest way back in a taxicab geometry.
:param path: string of moves, where moves are encoded as follows:.
N - north - (1, 0)
S - south - (-1, 0)
E - east - (0, 1)
W - west - (0, -1)
(first coordinate indicates steps towards north,
second coordinate indicates steps towards east)
:return: the shortest way back encoded the same way as :param path:.
"""
d = {"N": (1, 0),
"S": (-1, 0),
"E": (0, 1),
"W": (0, -1)}
pos = (0, 0)
back = ""
for direct in path:
pos = (pos[0] + d[direct][0], pos[1] + d[direct][1])
print(pos)
while pos != (0, 0):
if pos[0] != 0:
while pos[0] > 0:
pos = (pos[0] - 1, pos[1])
back += "S"
while pos[0] < 0:
pos = (pos[0] + 1, pos[1])
back += "N"
if pos[1] != 0:
while pos[1] > 0:
pos = (pos[0], pos[1] - 1)
back += "W"
while pos[1] < 0:
pos = (pos[0], pos[1] + 1)
back += "E"
return back
if __name__ == '__main__':
assert shortest_way_back("NNN") == "SSS"
assert shortest_way_back("SS") == "NN"
assert shortest_way_back("E") == "W"
assert shortest_way_back("WWWW") == "EEEE"
assert shortest_way_back("") == ""
assert shortest_way_back("NESW") == ""
assert shortest_way_back("NNEESEW") in ["SWW", "WSW", "WWS"]
| true |
04ec308573556b4c9e216035cc5f2d65a9eaeb97 | SaifAlsaad/simplecalculator | /My-first-simple-calculator.py | 1,036 | 4.46875 | 4 | print("Welcome to Saif's calculator")
num1=input("Enter any number: ")
op=input("Choose any symbole + - * ** / % // == != < > <= >= = : ")
num2=input("last step to see the results: ")
num1=float(num1)
num2=float(num2)
if op=="+":
pls=num1 + num2
print(pls)
elif op=="-":
sub=num1-num2
print(sub)
elif op=="*":
multi=num1*num2
print(multi)
elif op=="**":
power=num1**num2
print(power)
elif op=="/":
divide=num1/num2
print(divide)
elif op=="%":
Modulus=num1%num2
print(Modulus)
elif op=="//":
Floor_Division=num1//num2
print(Floor_Division)
elif op=="==":
equal=num1==num2
print(equal)
elif op==">":
left_op=num1>num2
print(left_op)
elif op=="<":
Right_op=num1<num2
print(Right_op)
elif op=="<=":
left_eq=num1<=num2
print(left_eq)
elif op==">=":
right_eq=num1>=num2
print(right_eq)
elif op=="!=":
EQ_OP=num1!=num2
print(EQ_OP)
elif op=="=":
EQ=num1=num2
print(EQ)
else:
print("use + - / * ** % // == < > <= >= != = only")
| false |
17f70272ddf81483bcf5b5c36377659a43174a8d | amiraHag/Python-Basic | /basic datatypes/variables.py | 584 | 4.4375 | 4 | #print any text using print function
print("Hello World!")
"""store value in variables"""
x=5
y=6
z= x+y
print(z)
""" know the type of the variable by using type()"""
print(type(z))
#make operations on numbers
x= 3+4*5
print(x)
# arithmatic operators four basic - + * /
# ** power ()parenthesis- use to identify which operation will applied first
x= (3 +4)*5
print(x)
# the order of the arithmatic operators () , ** , * / , + - , if in the same level it will do left to write
x = 4 / (2*1) -1 *5 +6
# x= 4/2 -1*5 +6
#x=2 -5 +6 = 3
print(x)
x = ((3+5) *2) **2/16 -1
print(x)
| true |
d2fd5afd38c0191cdc657af4e99e62da817b7f0f | theshevon/A2-COMP30024 | /adam/decision_engine.py | 2,458 | 4.1875 | 4 | from math import sqrt
from random import randint
class DecisionEngine():
"""
Represents the agents 'brain' and so, decides which node to move to next.
"""
EXIT = (999, 999)
colour = None
exit_nodes = None
open_node_combs = None
init_node_comb = None
closed_node_combs = None
open_node_combs_queue = None
states = None
def __init__(self, colour, board):
self.colour = colour
self.exit_nodes = board.get_exit_nodes(colour)
print("EXITS:", self.exit_nodes)
def get_next_move(self, board):
"""
Returns a random move out of the list of valid moves.
"""
nodes = board.get_piece_nodes(self.colour)
# generate all possible moves
possible_successors = self.get_all_possible_moves(board, nodes)
# no moves possible
if len(possible_successors) == 0:
return ("PASS", None)
# pick a random move
action = possible_successors[randint(0, len(possible_successors) - 1)]
if action[1] == self.EXIT:
return ("EXIT", action[0])
else:
if board.get_dist(action[0], action[1]) <= sqrt(2):
return ("MOVE", action)
return ("JUMP", action)
def get_all_possible_moves(self, board, nodes):
"""
Returns a list of all the possible nodes that can be moved to. An exit
is denoted by (999, 999).
"""
possible_moves = []
occupied_nodes = board.get_all_piece_nodes()
for node in nodes:
# check if an exit is one of the possible moves
if node in self.exit_nodes:
possible_moves.append((node, self.EXIT))
# add neighbouring nodes to list
for neighbouring_node in board.get_neighbouring_nodes(node):
# if neighbouring node is occupied, look for landing spots
if neighbouring_node in occupied_nodes:
landing_node = board.get_landing_node(node, neighbouring_node, occupied_nodes)
if (landing_node):
possible_moves.append((node, landing_node))
else:
possible_moves.append((node, neighbouring_node))
return possible_moves
| true |
8273da9ef7fb33ab57d238d677465cebd66a07b0 | narokiasamy/internship1 | /06-20-19/temperatureConverter.py | 548 | 4.25 | 4 | # temperature must be typed with corresponding temperature scale unit! (ex: 32F or 68C)
temperature = str(input("temperature reading: "))
# temperature conversions
if "C" in temperature:
removeLetter = int(temperature.rstrip("C"))
fahrenheitCalculation = (int((removeLetter * 1.8) + 32))
print (str(fahrenheitCalculation) + "F")
print (temperature)
elif "F" in temperature:
removeLetter = int(temperature.rstrip("F"))
celsiusCalculation = (int((removeLetter - 32) / 1.8))
print (str(celsiusCalculation) + "C")
print (temperature)
| true |
a220c8cf2ae254f3a399cdfe17542ca9f508780d | sucman/Python100 | /11-20/14.py | 1,419 | 4.125 | 4 | # -*- coding:utf-8 -*-
'''
将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。
'''
a = int(raw_input("请输入数字:"))
print "{} = ".format(a),
while a not in [1]: # 循环保证递归
for index in xrange(2, a + 1):
if a % index == 0:
a = a / index
if a == 1:
print index
else: # index 一定是素数
print "{} *".format(index),
break
'''
def test(a):
print "{} = ".format(a),
if not isinstance(a,int) or a <= 0:
print "请输入正确数字。"
exit(0)
elif a in [1]:
print "{} = ".format(a)
while a not in [1]:# 循环保证递归
for index in xrange(2, a +1):
if a % index == 0:
a = a / index
if a == 1:
print index
else:# index 一定是素数
print "{} *".format(index),
break
test(123)
'''
| false |
260ebcd387e66bf0a17576468d5e6e1c3b6cee61 | manerain/savy | /proj02/proj02_02.py | 598 | 4.4375 | 4 | # Name:
# Date:
# proj02_02: Fibonaci Sequence
"""
Asks a user how many Fibonacci numbers to generate and generates them. The Fibonacci
sequence is a sequence of numbers where the next number in the sequence is the sum of the
previous two numbers in the sequence. The sequence looks like this:
1, 1, 2, 3, 5, 8, 13..."""
counter = 0
counter3 = 0
cntr2 = 1
fib = raw_input('How many fibonacci numbers do you want to generate:')
fib = int(fib)
while counter < fib:
seq = counter3 + cntr2
seq = int(seq)
print cntr2
counter3 = cntr2
cntr2 = seq
counter = counter + 1
| true |
0baa5692dce09d548d9ad6f39460dd38de1dc809 | tainaracamila/PizzaPricePredictions | /main.py | 1,408 | 4.40625 | 4 | """
Prevendo o Preço da Pizza
Suponha que você queira prever o preço da pizza.
Para isso, vamos criar um modelo de regressão linear para prever o preço da pizza, baseado em um atributo da pizza
que podemos observar. Vamos modelar a relação entre o tamanho (diâmetro) de uma pizza e seu preço.
Escreveremos então um programa com sckit-learn, que prevê o preço da pizza dado seu tamanho.
"""
import numpy as np
import pandas as pd
from data_visualization import Graph
from sklearn.linear_model import LinearRegression
if __name__ == '__main__':
gp = Graph()
model = LinearRegression()
# Getting data
data = pd.read_csv('dados.csv', delimiter=';')
diameter = list(data['Diametro'])
price = list(data['Preco'])
# Visualizing data through a graph
# gp.graphic(diameter, price)
# Transforming data
x = [[x] for x in diameter]
y = [[x] for x in price]
# Training model
model.fit(x, y)
# Diameters to predict
pizza_20cm = 20
pizza_50cm = 50
# Results
print("A pizza with 20cm should cost: R$%.2f." % model.predict([[pizza_20cm]]))
print("A pizza with 50cm should cost: R$%.2f." % model.predict([[pizza_50cm]]))
print('\nCoefficient: %f' % model.coef_)
print('Mean square error: %.2f' % np.mean((model.predict(x) - y) ** 2))
print('Variation score: %.2f' % model.score(x, y))
#gp.scatter(model, x, y) | false |
11f2fae0b317c7ce7e83c410dd210aa747e2b2a0 | NgyAnthony/python-course | /Chapter 3/Exercises/3.2-4.py | 283 | 4.15625 | 4 | words = ["Hello", "my", "same", "is", "Anthony", "Okayy", "Heyyy"]
def count_words():
count = 0
for word in words:
if word.count(str()) == 6:
count +=1
print(word, "is 5 str long.")
print(count, "words with 5 in length.")
count_words() | false |
c3b48b91fdaea9a19a2ae641fef982b5fcf19eec | xleon/CursoCiudadRealPython | /7_listas.py | 544 | 4.4375 | 4 | """
Ejemplos para trabajar con listas
"""
LIST = [1, 2, 3, 4, 5, 'seis', 'otra cosa']
print(LIST)
print(LIST[0])
print(LIST[4])
print(LIST[2:5])
print(LIST[:3])
print(LIST[2:])
SIZE = len(LIST)
print('tamaño de la lista:', SIZE)
del LIST[2]
print(LIST)
LIST[2] = 'TRES'
print(LIST)
# concatenar dos listas
LIST += ['ocho', 9, True, False]
print(LIST)
# añadir elemento a una lista
LIST.append('elemento nuevo')
print(LIST)
LIST.remove(False)
print(LIST)
LIST.reverse()
print(LIST)
LIST.reverse()
LIST.insert(3, 'cuatro')
print(LIST) | false |
795b38a4447f17041c48356e241316673a205584 | xleon/CursoCiudadRealPython | /16_herencia.py | 891 | 4.375 | 4 | """ Herencia de clases """
class Vehicle:
def __init__(self):
self.wheels = 0
self.name = self.__class__.__name__
print('Constructor de', self.name)
def move(self):
return 'moving'
class Car(Vehicle):
def __init__(self):
super().__init__()
self.wheels = 4
def move(self):
return 'moving on the road'
class Plane(Vehicle):
def __init__(self):
super().__init__()
self.wheels = 4
def move(self):
return 'flying'
VEHICLES = (Vehicle(), Car(), Plane())
for v in VEHICLES:
print('{} tiene {} ruedas y se mueve así: {}'.format(v.name, v.wheels, v.move()))
# herencia múltiple
class A:
def fly(self):
print('flying')
class B:
def run(self):
print('running')
class C(A, B):
def eat(self):
print('eating')
c = C()
c.eat()
c.fly()
c.run()
| false |
756807939ce427d376446b51d12d229acc3099cc | rajunrosco/PythonExperiments | /CollectionFunctions/CollectionFunctions.py | 2,174 | 4.125 | 4 | import os
import sys
from functools import reduce
def FilterTest():
keylist = ["a","a|ps4","b","b|ps4","b|win64","c","c|win64"]
# filter list with lambda function that returns all strings that contain "ps4"
# filter() takes a function evaluates to "true", items that you want in the list
# in the case below, the function is a lambda that takes and argument 'x' and returns
# true if "ps4" is found in 'x'.
# so, the below filter takes keylist and returns all items that are true for the lambda function
myfilter = filter(lambda x : x.find("ps4")>=0, keylist)
print(myfilter)
# since the above returns a filter object instead of a list, make a list out of
filterlist = list(filter(lambda x : x.find("ps4")>=0, keylist))
# another way to write the lambda this time looking for "win64"
filterlist = list(filter(lambda y : "win64" in y, keylist))
print(filterlist)
# map applies the function in the first argument to all items in the collection of the second argument.
# the below lambda function takes an argument and returns the first item in a list after splitting on '|'
# else it returns None
keybaselist = list( map(lambda x: x.split('|')[0] if len(x.split('|'))==2 else None, keylist ))
# now the list is littered with None types so filter them out
keybaselist = list(filter(lambda x : x is not None, keybaselist))
# reduces a list by taking a 2 parameter function an then applying it to the list over each element
# think first pair as ([0],[1]) and the second pair as ( (0,1) and (2) ) ....
concatlist = reduce(lambda x,y : x +','+ y, keylist)
# the lambda below has to check if the current item is a str to get len(str) or if it has already been
# converted and return the number to be added to the next number.
countallchars = reduce( lambda x,y : len(x) if type(x) is str else x + len(y) if type(y) is str else y, keylist)
stop = 1
def Main(argv):
FilterTest()
# If module is executed by name using python.exe, enter script through Main() method. If it is imported as a module, Main() is never executed at it is used as a library
if __name__ == "__main__":
Main(sys.argv)
| true |
f2a5dc0eb57b10d0ccc0acc17c6b5bf3b060c585 | anuragdogra2192/Data_structures_with_python3 | /arrays/TwoSumII_unique_pairs.py | 1,839 | 4.21875 | 4 | '''
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order,
find two numbers such that they add up to a specific target number.
Let these two numbers be numbers[index1] and numbers[index2]
where 1 <= first < second <= numbers.length.
Return the indices of the two numbers,
index1 and index2, as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution.
You may not use the same element twice.
Example 1:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
Example 2:
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3.
Example 3:
Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2.
Constraints:
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers is sorted in non-decreasing order.
-1000 <= target <= 1000
The tests are generated such that there is exactly one solution.
'''
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
index1 = 0;
index2 = len(numbers)-1;
while index1 < index2:
if numbers[index1] + numbers[index2] > target:
index2-=1
elif numbers[index1] + numbers[index2] < target:
index1+=1
else:
return [index1+1, index2+1]
Sol = Solution();
L = [2,7,11,15]
T = 9
print(Sol.twoSum(L, T))
L1 = [2,3,4]
T1 = 6
print(Sol.twoSum(L1, T1))
L2 = [-1,0]
T2 = -1
print(Sol.twoSum(L2, T2))
| true |
c529568c0c22bc9cbee2c64265c8c32147c310e8 | anuragdogra2192/Data_structures_with_python3 | /arrays/ReturnAnArrayOfPrimes/Return_array_of_primes.py | 870 | 4.34375 | 4 | """
Write a program that takes an integer argument and
returns all the primes between 1 and that integer.
For example, if the input is 18, you should return [2, 3, 5, 7, 11, 13, 17]
Hint: Exclude the multiples of primes.
"""
#Given n, return all primes up to and including n.
def generate_primes(n):
primes = []
# is_prime[p] represents if p is prime or not.
# Initially, set each to 'true', expecting 0 and 1. Then use sieving to eliminate nonprimes.
is_prime = [False, False] + [True] * (n-1)
for p in range(2, n+1):
if is_prime[p]:
primes.append(p)
# Sieve p's multiples.
for i in range(p * 2, n + 1, p):
is_prime[i] = False
return primes
print("Input the integer: ")
n = int(input())
print("The array of primes: ", generate_primes(n))
#O(nloglogn) | true |
20099604968983eb02c4ec2b0f9c67600afcf002 | anuragdogra2192/Data_structures_with_python3 | /strings/integer_to_string.py | 899 | 4.28125 | 4 | """
Integer to string
Built-in functions used in the code
1) ord()
The ord() function returns an integer representing the Unicode character.
ord('0') - 48
ord('1') - 49
:
:
ord('9') - 57
2) chr()
Python chr() function takes integer argument and return the string representing a character at that code point.
chr(48) - '0'
chr(49) - '1'
:
:
chr(57) - '9'
"""
def int_to_string(x):
is_negative = False
if x < 0:
x, is_negative = -x, True
s = []
while True:
s.append(chr(ord('0') + x % 10))
x //= 10
if x == 0:
break
# Adds the negative sign back if is_negative
return('-' if is_negative else '') + ''.join(reversed(s))
x = int(input("Enter the integer number to convert to string: "))
s = int_to_string(x)
print("The string after the conversion: ", s, "and its type: ", type(s)) | true |
66ca2398e71e7faf0042e69596658d19d25a9409 | anuragdogra2192/Data_structures_with_python3 | /LargeAssociationItems.py | 2,558 | 4.28125 | 4 | """
My approach: DFS
Question:
In order to improve customer experience, Amazon has developed a system to provide recommendations to the customer
regarding the item they can purchase. Based on historical customer purchase information, an item association can be defined
as - If an item A is ordered by a customer, then item B is also likely to be ordered by the same customer (e.g. Book 1 is frequently orderered with Book 2).
All items that are linked together by an item association can be considered to be in the same group.
An item without any association to any other item can be considered to be in its own item association group of size 1.
Given a list of item association relationships(i.e. group of items likely to be ordered together), write an algorithm that outputs the largest item association group.
If two groups have the same number of items then select the group which contains the item that appears first in lexicographic order.
Input
The itput to the function/method consists of an argument - itemAssociation, a list containing paris of string representing the items that are ordered together.
Output
Return a list of strings representing the largest association group sorted lexicographically.
Example
Input:
itemAssociation: [
[Item1, Item2],
[Item3, Item4],
[Item4, Item5]
]
Output:
[Item3, Item4, Item5]
Explanation:
There are two item association groups:
group1: [Item1, Item2]
group2: [Item3,Item4,Item5]
In the available associations, group2 has the largest association. So, the output is [Item3, Item4, Item5].
"""
L = [["Item1", "Item2"],["Item3", "Item4"],["Item4", "Item5"]]
itemDict = {}
for i in range(len(L)):
if L[i][0] in itemDict:
itemDict[L[i][0]].append(L[i][1])
if L[i][1] not in itemDict:
itemDict[L[i][1]] = []
else:
itemDict[L[i][0]] = [L[i][1]]
itemDict[L[i][1]] = []
print(itemDict)
def dfs(visited, graph, node):
if node not in visited:
#print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
LargestItemAssociation = []
for i in itemDict:
visited = set()
#print(i)
dfs(visited, itemDict, i)
visited = sorted(visited)
#print(type(visited))
if len(LargestItemAssociation) < len(visited):
LargestItemAssociation = visited
elif(len(LargestItemAssociation) == len(visited)):
if(LargestItemAssociation[0] < visited[0]):
LargestItemAssociation = visited
#print(visited)
print(LargestItemAssociation)
| true |
1bb0230e9ca9ae6404d40e7fd5a6091f4cbdb503 | 600rrchris/Python-control-flow-lab | /exercise-2.py | 490 | 4.3125 | 4 | # exercise-02 Length of Phrase
# Write the code that:
# 1. Prompts the user to enter a phrase:
# Please enter a word or phrase:
# 2. Print the following message:
# - What you entered is xx characters long
# 3. Return to step 1, unless the word 'quit' was entered.
word = input('Enter "Please enter a word or phrase"')
error = ('quit')
x = len(word)
if word in error:
input('Enter "Please enter a word or phrase"')
else:
print(f'What you entered is {x} characters long')
| true |
525fa36066c159ccd4a5f921f006ad71dbc47777 | saurav-singh/CS260-DataStructures | /Assignment 3/floyd.py | 1,718 | 4.375 | 4 | #!usr/bin/env python
#
# Group project: Floyd's algorithm
# Date: 03/13/2019
#
# It should be noted that this implementation follows the one in the textbook
"""{Shortest Paths Program: shortest takes an nXn matric C of arc costs and produces nXn matrix A of lengths of shortst paths and an nXn matrix P giving a point in the "middle" of each shortest path}"""
def shortest(A,C,P):
n = len(A)
for i in range(n):
for j in range(n):
A[i][j] = C[i][j]
P[i][j] = 0
for i in range(n):
A[i][i] = 0
for k in range(n):
for i in range(n):
for j in range(n):
if (A[i][k] + A[k][j]) < A[i][j]:
A[i][j] = A[i][k] + A[k][j]
P[i][j] = k
#Procedure to print shortest path.
def path(i,j,P):
k = P[i][j]
if k == 0:
return
path(i,k,P)
print(k)
path(k,j,P)
#Problem 6 of review 2
test = float("inf")
n = 6
C = [[test for x in range(n)] for x in range(n)]
#It should be noted that compared to the review problem, the index for
#everything starts at 0
C[0][1] = 4
C[0][2] = 1
C[0][3] = 5
C[0][4] = 8
C[0][5] = 10
C[2][1] = 2
C[3][4] = 2
C[4][5] = 1
A = [[test for x in range(n)] for x in range(n)]
P = [[test for x in range(n)] for x in range(n)]
print("\n")
print("Initial Matrix C:")
for node in C:
print(node)
shortest(A,C,P)
print("\n")
print("Matrix P:")
for node in P:
print(node)
print("\n")
print("Matrix A:")
for node in A:
print(node)
print("\n")
print("Resulting shortest Paths:")
print("0->1")
path(0,1,P)
print("\n")
print("0->2")
path(0,2,P)
print("\n")
print("0->3")
path(0,3,P)
print("\n")
print("0->4")
path(0,4,P)
print("\n")
print("0->5")
path(0,5,P)
| true |
7d52d970e8a6ff398aa99e553afb9b0afc0e1592 | dimDamyanov/Py-Fundamentals | /02. EXCERCISE - Basic Syntax, Conditional Statements and Loops/03.py | 280 | 4.15625 | 4 | year = int(input())
if year == 88:
print('Leo finally won the Oscar! Leo is happy')
elif year == 86:
print('Not even for Wolf of Wall Street?!')
elif year != 86 and year < 88:
print('When will you give Leo an Oscar?')
elif year > 88:
print('Leo got one already!')
| false |
0725be1066a074d73d764b67b8fe589b41b33cd7 | rosewambui/NBO-Bootcamp16 | /fizzbuzz.py | 278 | 4.1875 | 4 | """function that checks the divisibility of 3, 5 or both"""
"""a number divisible by both 3 and 5 id a divisor 15, divisibility rule"""
def fizz_buzz(num):
if num%15==0:
return "FizzBuzz"
elif num%5==0:
return "Buzz"
elif (num%3==0):
return "Fizz"
else:
return num
| true |
6b596be7dbe7be8359e78e6bec3dba581d1762c7 | mhorist/FunctionPractice | /FunkyPractice06.py | 246 | 4.3125 | 4 | # Write a Python program to reverse a string.
def strRevers(charString):
rstr = ''
index = len(charString)
while index > 0:
rstr += charString[index - 1]
index = index - 1
print(rstr)
strRevers("abc def ghi jkl") | true |
2db7e00677625efb1119dab3fd48a6de2c3d1567 | eflagg/dictionary-restaurant-ratings | /restaurant-ratings.py | 1,861 | 4.40625 | 4 | # your code goes here
import random
def alphabetize(filename):
"""Alphabetizes list of restaurants and ratings
Takes text file and turns it into dictionary in order to print restaurant_name with
its rating in alphabetical order
"""
username = raw_input("Hi, what's your name? ")
print "Hi %s!" % (username)
open_file = open(filename)
restaurants = {}
# loops through textfile, strips any hanging spaces, splits into a list based on ':'
# Inserts restaurant name and rating into the dictionary
for line in open_file:
line = line.rstrip()
line_as_list = line.split(":")
restaurants[line_as_list[0]] = line_as_list[1]
#Generates a random restaurant, asks user for rating and changes rating within the
#dictionary. Does this until user types 'q' or 'Q'
while True:
random_restaurant_key = random.choice(restaurants.keys())
print "Let's look at a sample restaurant!"
print random_restaurant_key + ": " + restaurants[random_restaurant_key]
new_rating = raw_input("What should the new rating be? ")
if new_rating in ['q','Q']:
break
else:
restaurants[random_restaurant_key] = new_rating
print "Success! You successfully changed the restaurant rating!"
#Asks user to input another restaurant with a rating and adds to dictionary
new_restaurant = raw_input("Another restaurant name? ")
new_score = int(raw_input("Restaurant's rating? "))
restaurants[new_restaurant] = new_score
# loops through the dictionary and sorts it based on restaurant_name and prints out
# restaurant name and rating as a string
for restaurant_name, rating in sorted(restaurants.iteritems()):
print "%s is rated at %s." % (restaurant_name, rating)
alphabetize('scores.txt') | true |
f9668b8dd8c559e8a2338449fee23c5c60ad30da | ProjectOnePM/ProjectOneEjercicios | /Unidad 2 - IF/TP2_Ejer03.py | 358 | 4.21875 | 4 | print "-Calculo ascendente de 3 numeros-"
N1=input("ingrese 1 numero")
N2=input("ingrese 1 numero")
N3=input("ingrese 1 numero")
if (N1<N2<N3):
print N1,"<",N2,"<",N3
elif(N1<N3<N2):
print N1,"<",N3,"<",N2
elif(N2<N1<N3):
print N2,"<",N1,"<",N3
elif(N2<N3<N1):
print N2,"<",N3,"<",N1
elif(N3<N1<N2):
print N3,"<",N1,"<",N2
else:
print N3,"<",N2,"<",N1
| false |
cc4760ce06911c819e85c5d2b5ea941de649f0d4 | princecoker/codelagos-Python-Class-Assignment-1.0 | /out of school assignment 2.py | 801 | 4.3125 | 4 | #this calculator tells what year you will be 100 years
#algorithm
#get name and age
#calculate birthyear
#add 100 to year of birth
#display year in 100 years time
name = str(input('what is your name: '))
age = int(input('How old are you: '))
birthyear = 2018 - age
futuredate = int(birthyear + 100)
print (name,'you will be 100 years in the year',futuredate)
print ('\n', '\n', 'same program different approach below', '\n \n')
#this calculator tells what year you will be 100 years
#algorithm
#get name and year of birth
#add 100 to year of birth
#display year in 100 years time
name = str(input('what is your name: '))
yearofbirth = int(input ('what year were you born: '))
futuredate = int(yearofbirth + 100)
print (name,'you will be 100 years in the year',futuredate)
| false |
8629533b3301fd37e7cd41c4cfaecbf9677efe92 | boxa72/Code_In_Place | /khansoleAcademy.py | 1,414 | 4.25 | 4 | """
Prints out a randomly generated addition problem
and checks if the user answers correctly.
"""
import random
MIN_RANDOM = 10 # smallest random number to be generated
MAX_RANDOM = 99 # largest random number to be generated
THREE_CORRECT = 3 # constant for the loop
def main():
math_test()
def math_test():
""" function that holds the whole game """
num_correct = 0
while num_correct != THREE_CORRECT:
num1 = random.randint(MIN_RANDOM, MAX_RANDOM)
num2 = random.randint(MIN_RANDOM, MAX_RANDOM)
print("What is " + str(num1) + ' + ' + str(num2) + '? ')
user_input = int(input())
print("Your answer: " + str(user_input))
correct_answer = num1 + num2
if user_input == correct_answer:
num_correct += 1
if num_correct == 1:
print("Correct! You've gotten " + str(num_correct) + " correct in a row.")
elif num_correct == 2:
print("Correct! You've gotten " + str(num_correct) + " correct in a row.")
elif num_correct == 3:
print("Correct! You've gotten " + str(num_correct) + " correct in a row.")
print("Congratulations! You mastered addition.")
else:
print("Incorrect. The expected answer is " + str(correct_answer))
num_correct = 0
if __name__ == '__main__':
main() | true |
c6f84ddc221e0d4df3f237cc47647eb567aae0c4 | neutron-L/PycharmProjects | /IntroductionToPragrammingUsingPython/ch03/Ex19.py | 526 | 4.125 | 4 | import turtle
import math
x1, y1, x2, y2 = eval(input("Enter the coordinates of point1 and point2 like x1, y1, x2, y2: "))
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
turtle.write("("+ str(x1) + ", " + str(y1) + ")")
# degree = math.degrees(math.asin((y2-y1)/math.sqrt((x2-x1)**2 + (y2-y1)**2)))
# print(degree)
# turtle.left(degree)
# # turtle.left(45)
# turtle.forward(math.sqrt((x2-x1)**2 + (y2-y1)**2))
turtle.goto(x2, y2)
turtle.hideturtle()
turtle.write("(" + str(x2) + ", "+ str(y2) + ")")
turtle.done()
| false |
30c32e1a5cd8c9468a7d3583f77524de86885683 | JessicaGarson/Deduplicate_playtime | /dedupe.py | 1,373 | 4.40625 | 4 | # Challenge level: Beginner
# Scenario: You have two files containing a list of email addresses of people who attended your events.
# File 1: People who attended your Film Screening event
# https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/film_screening_attendees.txt
#
# File 2: People who attended your Happy hour
# https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/happy_hour_attendees.txt
# Goal 1: You want to get a de-duplicated list of all of the people who have come to your events.
#creating the function
def deduplicate(list1, list2):
return list(set(list1+list2))
#open up the files
with open("film_screening_attendees.txt", "r") as film_people:
film = film_people.read().split('\n')
with open("happy_hour_attendees.txt", "r") as happy_hour_people:
happy_hour = happy_hour_people.read().split('\n')
#who attended
print "Peeps who attended one of the events:"
#print the people who attend stuff
for person in deduplicate(film, happy_hour):
print person
print "\n"
# Goal 2: Who came to *both* your Film Screening and your Happy hour?
#instead of + I can use & to get both
def intersect(list1, list2):
return list(set(list1) & set(list2))
print "Peeps who attended both:"
for person in intersect(film, happy_hour):
print person
print "\n"
| true |
3634e3d694a98a2dd178c9f431874a53ffe8cc20 | 0xlich/python-cracking-codes-examples | /caesar.py | 1,178 | 4.25 | 4 | # Caesar Cypher
import pyperclip
#The string to be encrypted
#print ('Please enter the message: ')
#message = input()
message = 'fVDaOPZDPZDHTHgPUNDKVVN'
# The encryption key
key = 7
#Wheter the program encrypts or decrypts:
mode = 'decrypt' # Set to either 'encrypt' or 'decrypt'
#Every possible symbol
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
#Store the encrypted message
translated = ''
for symbol in message:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
#Perform encryption/decryption of message
if mode == 'encrypt':
translatedIndex = symbolIndex + key
elif mode == 'decrypt':
translatedIndex = symbolIndex - key
#Handle wraparound
if translatedIndex >= len(SYMBOLS):
translatedIndex -= len(SYMBOLS)
elif translatedIndex < 0:
translatedIndex += len(SYMBOLS)
translated = translated + SYMBOLS[translatedIndex]
else:
# Append the symbol without encrypting/decrypting
translated = translated + symbol
#Output the translated string:
print(translated)
pyperclip.copy(translated)
| true |
d566fbf02375e2a53983be614c73f58cfec61951 | gitbrian/lpthw | /ex15.py | 569 | 4.21875 | 4 | #imports the argv module
from sys import argv
#assigns variables to the arguments in argv
# script, filename = argv
# print "The script running this is named %r." % script
#assigns the open file to the variable 'txt'
# txt = open(filename)
# prints the filename of the text file
# print "Here's your file %r:" % filename
# prints the contents of the file
# print txt.read()
print "Type the filename again:"
#gets the file info from the user this time while the program is running
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.close()
| true |
70814dacb3ee3278d6eb848f1395d81ac80b04cb | SyedIbtahajAhmed/Python-Basic | /LCM And HCF Calculator.py | 1,285 | 4.15625 | 4 | #========================
#========================
def gcd(a,b):
"Calculates GCD Of Two Numbers"
if(b==0):
return a
return gcd(b, a%b)
#========================
#========================
def lcm(a,b):
"Calculates LCM Of Two Numbers"
y = (a*b)/gcd(a,b)
return(y)
#========================
#========================
def hcf(a,b):
"Calculates HCF Of Two Numbers"
y = a*b/lcm(a,b)
return(y)
#========================
#========================
def opr():
"Operations"
print("1. H.C.F(Highest Common Factor)")
print("2. L.C.M(Least Common Multiple)")
print("3. G.C.D(Greatest Common Divisor)")
#========================
#========================
print(opr())
p = str(input("Press Y To Enter Values Of Two Numbers Or Press Q To Quit The Program"))
while(p=="y" or p=="Y"):
x = float(input("Enter First Number :"))
y = float(input("Enter Second Number :"))
print("\n* Highest Common Factor (H.C.F) is ",hcf(x,y))
print("\n* Least Common Multiple (L.C.M) is ",lcm(x,y))
print("\n* Greatest Common Divisor (G.C.D) is ",gcd(x,y))
p = str(input("Press Y To Enter Values Of Two Numbers Or Press Q To Quit The Program"))
print("THANKS FOR USING!","\nGOOD BYE")
| false |
53fe312095c05dc9d24e255d4062b24862c2e27c | ejudd72/beginner-python | /notes/numbers.py | 807 | 4.1875 | 4 | from math import *
print(2)
# parenthesis for order of operation
print(3 * (4 + 5))
# division
print(3/1)
# modulus operator
print(10 % 3)
# numbers inside variables
my_num = 5
print(20 % my_num)
# convert number to string (you need to do this to concatenate strings and numbers)
my_num = 6
print("I have " + str(my_num) + " dogs")
# common python number functions
# absolute value
my_neg_num = -32
print(abs(my_neg_num))
# powers, with first param number, second param is the power of
print(pow(3, 2))
# print larger of two numbers
print(max(my_num, my_neg_num))
# round a number
print(round(4.55))
# using math functions, you need to import them e.g. in line 1
# rounds to lower integer
print(floor(4.3))
# round to higher integer
print(ceil(4.3))
# gives square root
print(floor(sqrt(36)))
| true |
88acce823bf11faaf330eccb89f8a8e0f66fbbfa | Areeba-Seher04/Python-OOP | /2 INHERITANCE/2 Inheritance.py | 1,036 | 4.28125 | 4 | #class Person(object):
class Person: #Parent class
def __init__(self,name,age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
class Employee(Person): #Child class
'''
**Child class of Person Class
**can access all functions and variables of Parent class
'''
pass
def main():
Person_object=Person("Areeba",100)
print("My name is {} and I am {} years old".format(Person_object.get_name(),Person_object.get_age()))
Employee_object=Employee("Employee",200) #can access all functions and variables of Parent Class
print("My name is {} and I am {} years old".format(Employee_object.get_name(),Employee_object.get_age()))
print(issubclass(Employee,Person)) #is Employee ,the subclass (child) of person?
print(issubclass(Employee,object)) #every class in python is the subclass of object
print(issubclass(Employee,object))
main()
| true |
ec1451e3c75e5c1726a49298cc43beaee0ab23a8 | Areeba-Seher04/Python-OOP | /3 FUNCTIONS arg,kwarg/3.arg in function call.py | 421 | 4.28125 | 4 | #ARG IN FUNCTION CALL
#We can also use *args and **kwargs to pass arguments into functions.
def some_args(arg_1, arg_2, arg_3):
print("arg_1:", arg_1)
print("arg_2:", arg_2)
print("arg_3:", arg_3)
args = ("Sammy", "Casey", "Alex") #args is a tuple
some_args(*args) #pass all arguments in a function
args = ("sara","yusra")
some_args("Areeba",*args)
args = [1,2] #we can also pass list
some_args(3,*args) | true |
f495dd4e59b615d52f4ecc260c5075466f2c1f8a | UrduVA/Learn-Python | /while_Infi.py | 206 | 4.1875 | 4 | x = 0
while x != 5:
print(x)
x = int(input("Enter a value or 5 to quit: "))
##0
##Enter a value or 5 to quit: 1
##1
##Enter a value or 5 to quit: 2
##2
##Enter a value or 5 to quit: 5
| true |
8d6bcffee5cdace0ddc5e79be117999ad094c349 | hanchettbm/Pythonprograms | /Lab12 updated.py | 2,590 | 4.4375 | 4 | # 1. Name:
# -Baden Hanchett-
# 2. Assignment Name:
# Lab 12: Prime Numbers
# 3. Assignment Description:
# -This program will display all the prime numbers at
# or below a value given by the user. It will prompt the
# user for an integer. If the integer is less than 2,
# then the program will prompt the user again.
# The program will then compute all the prime numbers below
# (and including) the given number. When finished, the program
# will display the list of prime numbers.-
# 4. What was the hardest part? Be as specific as possible.
# -This assignment was the most difficult for me, I had the most
# troubble understanding the solution that crosssed out values with
# another array of true false values. I had a sloution that worked,
# but I had to reformat it to work with the lab design. The harderst
# part of that was the multiple loop. I had to spend some time understanding
# the range, that mutiple had to start at factor * 2 and then increase by
# factor. Once I understood the range needed I was able to use it to set
# the true false values correctly.-
# 5. How long did it take for you to complete the assignment?
# -total time in hours including reading the assignment and submitting the program was 4 Hours.-
import math
# Set variables and prompt user for a number, that's greater than 1.
number = 0
while number < 2:
number = int(input ("This program will find all the prime numbers at or below N. Select that N: "))
assert(number > 1) # Make sure code above worked and number is greater than 1.
primes = []
# Fill numbers array with True values up to number.
numbers = [True for index in range(number + 1 )]
numbers[0] = False
numbers[1] = False
assert(len(numbers) == number + 1) # Check length of the array, make sure it's full.
# Check each value up until the square root of the number
# because nothing above that will be prime.
for factor in range(2, int(math.sqrt(number)) + 1):
if numbers[factor]:
# Rule out every mutiple of the factor becuase mutiples are never prime.
for multiple in range((factor * 2), (number + 1), factor):
numbers[multiple] = False
multiple = (factor * 2)
assert(type(multiple) == int) # Check multpiple type.
# Use the numbers array to add values to primes array.
for index in range(2, (number + 1)):
if numbers[index]:
primes.append(index)
print("The prime numbers at or below", number, "are", primes) | true |
4d5ab2cd112c035e56366aa849c49822cb8c279e | Nick-Cora/Compiti_Vacanze | /compiti sistemi/highScore.py | 652 | 4.125 | 4 | def highScore(lis):
last = lis[-1]
max_score = max(lis)
if len(lis) < 3:
raise Exception("not enough list items")
else:
three_max = []
while len(three_max) < 3:
three_max.append(max(lis))
lis.remove(max(lis))
return (f"Last score: {last} \nMax score: {max_score} \nTop 3 max score: {three_max}")
def main():
lista=[]
x = int(input("Enter score, enter '-1' to finish... "))
while x != -1:
lista.append(x)
x = int(input("Enter score, enter '-1' to finish... "))
print(highScore(lista))
if __name__ == "__main__":
main() | false |
bdb0b23ae85a83b6499fb2aa7d9274af9bbc6d00 | ramutalari/python | /src/test/forloop_Example.py | 272 | 4.4375 | 4 | #Example 1:
x = ['India','UK','Europe','Australia']
for i in x:
print(i)
#Example-2
for i in range(1,21):
print(i)
#Example-3
for i in [1,50,'london']:
print(i)
for j in ('INDIA',2,5,6):
print(j)
for k in {'Glasgow','Edinburg','Leeds'}:
print(k)
| false |
20290067dda6e0cc8d3d4661ecaaa73428186d19 | guozhaoxin/mygame | /common/common.py | 2,043 | 4.21875 | 4 | #encoding:utf8
__author__ = 'gold'
# import win32api,win32con
import tkinter as tk
from tkinter import filedialog,messagebox
import pygame
import sys
def chooseFile():
'''
this method is used to let the player choose a file to continue a saved game
:return: str,represent a file's absolute path the player chooses,else None
'''
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
if file_path != '':
return file_path
return
def exitGame():
'''
when the game is closed,execute pygame.quit and sys.exit
:return:
'''
pygame.quit()
sys.exit()
def chooseExit():
return messagebox.askyesno('exit the game','exit?')
def saveGame(data,method):
'''
let the player decide if save the game or not.
:param data: the game current data to save
:param method: a function object to indicate how to save the game.
:return: None
'''
choice = messagebox.askyesno('save the game','save?')
if choice:
method(data)
messagebox.Message(title = "save",message = "save success").show()
def importGameData(readMethod):
'''
let the player decide if import a saved game's data or not
:param readMethod: a function object,used to indicate how to load a saved game data,the function accept on parameter to indicate the data's path.
:return: data,the saved game data.
'''
data = None
while True:
choice = messagebox.askyesno('choose','choose an old game?')
if choice:
file = chooseFile()
if not file:
messagebox.showerror('error','file error!')
continue
data = readMethod(file)
if not data:
messagebox.showerror('error','file error!')
else:
break
else:
break
return data
def init():
'''
this method is used to execute some initial for every game at the beginning.
:return:
'''
pygame.init()
tk.Tk().withdraw() | true |
e82f7506d994eb1c852647d29b58c459979a04d4 | ndminh4497/python | /Exercises 33.py | 237 | 4.15625 | 4 | def sum_of_three(a,b,c):
if (a == b or a == c or b == c):
sum = 0
return sum
else:
sum = a + b + c
return sum
print(sum_of_three(2, 1, 2))
print(sum_of_three(3, 2, 2))
print(sum_of_three(2, 2, 2))
print(sum_of_three(1, 2, 3)) | false |
05c93e469cffe38bc2c5541ac53874c69a60463e | carolinapbf/Cursos | /Introducao a python/Metodo.py | 853 | 4.3125 | 4 | a= "Ana"
b= "Carolina"
Nome= a+" " +b
print(Nome.lower())#AS letras da string ficam todoas em minusculo
print(Nome.upper())#AS letras da string ficam todoas em maiusculo
print(Nome)
#\n da uma quebra de linha ja para retirar o caracter especial usa-se o metodo .strip()
# usando o metodo string=string.metodo()
#converção de string, vai fazer uma quebra na string
minha_string="o rato roeu a roupa do rei de Roma"
minha_lista= minha_string.split("r")
print(minha_lista)
#busca de substring
minha_string="o rato roeu a roupa do rei de Roma"
busca= minha_string.find("rei")
print(busca)
print(minha_string[busca:])# imprime a parte da busca no casao ate o fim da frase:
#substitui partes de uma string .replace
minha_string="o rato roeu a roupa do rei de Roma"
minha_string=minha_string.replace("o rei","a rainha")
print(minha_string)
| false |
05e60dc3c9487cb3911731ec5aefa2c02f43f7d5 | carolinapbf/Cursos | /Curso Completo Python/DeclaracoesAlinhadas e escopo.py | 631 | 4.21875 | 4 | x = 25
def printer():
x = 50
return x
print(x) # aparece 25, pois não chamei a função
print(printer())#vai retorna 50 pois chamei a função e ele não pede nenhum parametro
f = lambda x:x**2 # x é local aqui:
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x)
x = 50
def func():
global x
print('This function is now using the global x!')
print('Because of global x is: ', x)
x = 2
print('Ran func(), changed global x to', x)
print('Before calling func(), x is: ', x)
func()
print('Value of x (outside of func()) is: ', x)
| false |
c856254295dfe0dfe2e8cd40554bf127a8dfef32 | UAL-AED/lab5 | /aed_ds/queues/adt_queue.py | 745 | 4.375 | 4 | from abc import ABC, abstractmethod
class Queue(ABC):
@abstractmethod
def is_empty(self) -> bool:
''' Returns true iff the queue contains no elements. '''
@abstractmethod
def is_full(self) -> bool:
''' Returns true iff the queue cannot contain more elements. '''
@abstractmethod
def size(self) -> int:
''' Returns the number of elements in the queue.'''
@abstractmethod
def enqueue(self, element: object) -> None:
''' Inserts the specified element at the rear of the queue.
Throws FullQueueException '''
@abstractmethod
def dequeue(self) -> object:
''' Removes and returns the element at the front of the queue.
Throws EmptyQueueException '''
| true |
6f26cbdbc4352a6a01f735f41ede7dcd3cf847e8 | lewie14/lists_sorting | /lists2.py | 2,684 | 4.28125 | 4 | list1 = range(2, 20, 2)
#Find length of list1
list1_len = len(list1)
print(list1_len)
#Change the list range so it skips 3 instead of 2 numbers
list1 = range(2, 20, 3)
#Find length of list1
list1_len = len(list1)
print(list1_len)
print()
#------------------------------------------------------
#indexes
employees = ['Michael', 'Dwight', 'Jim', 'Pam', 'Ryan', 'Andy', 'Robert']
index4 = employees[4]
print(len(employees))
#print(employees[8]) --------------- Makes an error coz out of range
print(employees[4])
print()
#------------------------------------------------------
#Last element selection
shopping_list = ['eggs', 'butter', 'milk', 'cucumbers', 'juice', 'cereal']
print(len(shopping_list))
last_element = shopping_list[-1]
element5 = shopping_list[5]
print(element5)
print(last_element)
print()
#------------------------------------------------------
#Slicing lists
suitcase = ['shirt', 'shirt', 'pants', 'pants', 'pajamas', 'books']
#print firt 4 items
beginning = suitcase[0:4]
print(beginning)
#select middle 2 items
middle = suitcase[2:4]
suitcase = ['shirt', 'shirt', 'pants', 'pants', 'pajamas', 'books']
#Select first 3 items
start = suitcase[:3]
#Select last 2 items
end = suitcase[-2:]
print()
#------------------------------------------------------
#Counting elements in a list
#Mrs. Wilson's class is voting for class president. She has saved each student's vote into the list votes.
#Use count to determine how many students voted for 'Jake'. Save your answer as jake_votes.
votes = ['Jake', 'Jake', 'Laurie', 'Laurie', 'Laurie', 'Jake', 'Jake', 'Jake', 'Laurie', 'Cassie', 'Cassie', 'Jake', 'Jake', 'Cassie', 'Laurie', 'Cassie', 'Jake', 'Jake', 'Cassie', 'Laurie']
jake_votes = votes.count('Jake')
print(jake_votes)
print()
#------------------------------------------------------
#Sorting elements in a list
### Exercise 1 & 2 ###
addresses = ['221 B Baker St.', '42 Wallaby Way', '12 Grimmauld Place', '742 Evergreen Terrace', '1600 Pennsylvania Ave', '10 Downing St.']
# Sort addresses here:
addresses.sort()
print(addresses)
### Exercise 3 ###
names = ['Ron', 'Hermione', 'Harry', 'Albus', 'Sirius']
names.sort()
### Exercise 4 ###
cities = ['London', 'Paris', 'Rome', 'Los Angeles', 'New York']
#The print doesnt work because the sort does not return a sorted list to a variable
sorted_cities = cities.sort()
print(sorted_cities)
print()
games = ['Portal', 'Minecraft', 'Pacman', 'Tetris', 'The Sims', 'Pokemon']
#Use sorted to order games and create a new list called games_sorted
games_sorted = sorted(games)
#Use print to inspect games and games_sorted
print(games)
print(games_sorted)
#------------------------------
#All together
| true |
5feadeba85d180dca1c7a7f0445a32692dc3b9c6 | MichaelrMentele/LearnPythonTheHardWay | /ex18.py | 566 | 4.25 | 4 | def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_one(arg1):
print "arg1: %r" % arg1
def print_none():
print "I got nothin'."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
#Ok so if we use the *args array notation is there a limited or finite amount of args that can happen here.
#So if we use the form variable = [args] for unpacking purposes we can have an unspecified amount of variables.
| true |
2d0c41f4f1e73659d39f318038f6bf7344d66112 | durgeshiv/py-basic-scripting-learning | /com/durgesh/software/slicing.py | 768 | 4.21875 | 4 | x='LetsSliceThisString'
# we have defined a string as above, lets try to slice it and print 'ThisString'
# [] -> is the syntax for slicing
#
slicedString = x[9:] # Here, this starts at index 9 and : means we haven't specified end
# index thus everything until end would be taken
print(slicedString) # give o/p as 'ThisString
# Lets try end index also
print(x[9:13])
# There is a provision for step size also within slice
# Lets try to print alternate alphabet from above string
print(x[::2]) ## first two index-values, I have assumed to be empty which mean to start from 0 and finish at end and 2 denotes step size
############# Important ::: step can have negative value also but then;
#it will start from end, and will take step size as defined
print(x[::-1]) | true |
a3bd72a4f86653946331505e4b8157675cc3e153 | irskep/mrjob_course | /solutions/wfc_job.py | 1,293 | 4.125 | 4 | """
Write a job that calculates the number of occurrences of individual words in
the input text. The job should output one key/value pair per word where the key
is the word and the value is the number of occurrences.
"""
from collections import Counter, defaultdict
from mrjob.job import MRJob
class MRWordFrequencyCountJob(MRJob):
def steps(self):
return [self.mr(mapper_init=self.mapper_init, mapper=self.mapper,
mapper_final=self.mapper_final,
combiner=self.sum_words, reducer=self.sum_words)]
def mapper_init(self):
#self.words = {}
#self.words = defaultdict(0)
#self.words = defaultdict(lambda: 0)
self.words = Counter()
def mapper(self, _, line):
for word in line.split():
if word.strip():
#self.words.setdefault(word, 0)
#if word not in words:
# words[word] = 0
#self.words[word] = self.words.get(word, 0) + 1
self.words[word] += 1
def mapper_final(self):
for word, count in self.words.iteritems():
yield word, count
def sum_words(self, key, values):
yield key, sum(values)
if __name__ == '__main__':
MRWordFrequencyCountJob.run()
| true |
98815d02b2b32a065ef7daf466ee5e503e4aed62 | meghasn/py4_everyone_solution | /question9.py | 255 | 4.34375 | 4 | #using a while loop read from last character of a string and print backwards
word=input("enter the string:")
index=len(word)-1
while index>=0:
a=word[index]
print(a)
index=index-1
#enter the string:banana
#a
#n
#a
#n
#a
#b | true |
5dbf1aba29216b6f6d444eecac10c86717de5dfe | sm-wilson/euler | /1-100/009.py | 420 | 4.15625 | 4 | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
for c in range(334,500):
for a in range(1, int((1000-c)/2)):
b = (1000-c) - a
if a**2 + b**2 == c**2:
print(a, b, c)
print(a*b*c) | false |
8020336c54f223edc92891c3689c880483e6085f | wingateep/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 894 | 4.28125 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
# TBC
#base case
count = 0 # sets count to 0 to start
th_occurences = "th" # setting up to find the occurences of "th"
indx = word.find(th_occurences) #set up index to find the "th" occurances
#if "th" is found set to 0 and increase count
if indx >=0:
count +=1 # increase count by 1
word = word[indx + len(th_occurences):] #changes word to next given/not including first case
count += count_th(word) # recursively starts func until word is finished
# and no more "th" is found
return count #return count
#pass
| true |
b7f45c60fd07b48dde5572e9d0f728d13fec1bee | da-foxbite/KSU121 | /Python/lab1 [1-19]/t6.py | 494 | 4.125 | 4 | # 141, Суптеля Владислав
# Дата: 19.02.20
# 6. Даний рядок. Отримайте новий рядок, вставивши між кожними двома символами вихідної рядки символ *. Виведіть отриманий рядок.
string = input("「Введите строку」: ")
str2 = ''
for i in range(0, len(string)):
if i % 2 == 0:
str2 += string[i]+'*'
else:
str2 += string[i]
print("【Результат】 => ", str2)
| false |
7bdd6912148e971df2cc6fde278be91dcedbac01 | Song-Q/Learn-python | /recur.py | 600 | 4.28125 | 4 | #为解决递归调用使用尾递归优化
#然后python并没有对尾递归做优化,实际过深的递归还是存在栈溢出
#计算n!
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num==1:
return product
return fact_iter(num-1, num*product)
#practice 汉诺塔
#将递归问题拆解为二阶递归,考虑最后一步干什么,重复的步骤,和最后之前一步干什么
def hanoi(n, a, b, c)
if n == 1:
print(a, '-->', c)
hanoi(n-1, a, c, b)
print(a, '-->', c)
hanoi(n-1, b, a, c)
| false |
9cc9fa08a66e0d79b46790ed5232c66f934933f0 | rachelmccormack/PythonRevision-Tutoring | /Homework/Solutions/furtherFileReading.py | 875 | 4.15625 | 4 | """
A list of words is given in a file words.txt
For this file, please give the number of times each word appears, in the form {word:number}
Please display the longest word
How many words are in the list? (Don't peek) What percentage of the words are unique?
"""
file = open("words.txt")
words = file.readlines()
file.close()
longestWordLength = 0
longestWord = ""
wordFrequency = {}
for i in words:
i = i.replace("\n", "")
if i not in wordFrequency.keys():
wordFrequency[i] = 1
else:
wordFrequency[i] = wordFrequency[i] + 1
if len(i) > longestWordLength:
longestWordLength = len(i)
longestWord = i
totalDictLength = len(words)
uniqueWords = 0
for key, value in wordFrequency.items():
if value == 1:
uniqueWords = uniqueWords + 1
print(wordFrequency)
print(longestWord)
print((uniqueWords/totalDictLength)*100)
| true |
ac0792f282322dc080a62a79f83b57aad55a4d38 | rachelmccormack/PythonRevision-Tutoring | /Homework/shoppinglist.py | 795 | 4.21875 | 4 | # Fill out Shopping List Program
print("Welcome to the shopping list program...")
shoppingList = []
finalise = False
def finaliseList():
print("Your final list is: ")
for item in shoppingList: print(item)
print("Thank you!")
return True
"""
Here we need functions for adding to the list and for removing from the list.
"""
while finalise == False:
print("The current shopping list contains: ")
for item in shoppingList: print(item)
option = int(input("To add an item, press 1\nTo remove an item, press 2\nTo finalise the list press 3: "))
"""
We need to tell the program what to do when 1 and 2 are pressed
"""
if option == 3:
finalise = finaliseList()
"""
What should we do if a user types 4?
"""
| true |
cefe128d5308652f4d34d798336ef8e9219b273d | zekeriyaolke/phyton-introduction | /HomeWork/Final.py | 2,050 | 4.15625 | 4 | class RecipeItem:
def __init__(self, name, quantity):
self.name = name
self.quantity = quantity
class Recipe:
def __init__(self, name, items):
self.name = name
self.items = items
def cook(self):
recipeItems = [f"{i.name}({i.quantity})" for i in self.items]
print(f"{self.name} pişiyor\n Kullanılan malzemeler:{recipeItems} \n")
class Hamburger(Recipe):
def __init__(self):
super(Hamburger, self).__init__("Hamburger", [RecipeItem("Kıyma", 150),
RecipeItem("Soğan", 10),
RecipeItem("Ekmek", 1),
RecipeItem("Turşu", 10)])
def cook(self):
super(Hamburger, self).cook()
class Pizza(Recipe):
def __init__(self):
super(Pizza, self).__init__("Pizza", [RecipeItem("Salam", 50),
RecipeItem("Sosis", 50),
RecipeItem("Mantar", 25),
RecipeItem("Biber", 25),
RecipeItem("Hamur", 100)])
def cook(self):
super(Pizza, self).cook()
class Kebap(Recipe):
def __init__(self):
super(Kebap, self).__init__("Kebap", [RecipeItem("Kıyma", 150),
RecipeItem("Biber", 25),
RecipeItem("Soğan", 50),
RecipeItem("Domates", 50),
RecipeItem("Marul", 25),
RecipeItem("Biber", 25),
RecipeItem("Pide", 1)])
def cook(self):
super(Kebap, self).cook()
hamburger = Hamburger()
hamburger.cook()
pizza = Pizza()
pizza.cook()
kebap = Kebap()
kebap.cook()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.