blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7f1c138d85fbee0ebe4f327ffb8d121124101765 | wxl789/python | /day13/02-类属性.py | 333 | 4.28125 | 4 |
class People(object):
name = "tom"#公有的类属性
__age = 12#私有类属性
# def __init__(self,name):
# self.name = name
p = People()
print(p.name)
# print(p.__age)
print(People.name)
# print(People.__age)
"""
注意:
不能在类的外面通过实例对象和类对象访问私有的类属性
""" | false |
5cfd2f5823ca835000b3e936f4072044a58570ce | wxl789/python | /Day08/2-代码/迭代器/2-生成器.py | 1,130 | 4.28125 | 4 | '''
生成器:
generator生成器:使用yield关键字的函数被称为生成器函数。
使用yield的函数与普通函数的区别:
1、使用yield的函数返回一个生成器对象。
2、普通函数的返回值属于程序员自己设置。
yield:将一个函数拆分成多个模块,模块与模块之间为连续的。
yield可以间接控制进程或线程。
生成器可以认为是一个迭代器,使用方式与迭代器一致。
'''
# 普通函数的返回值默认为NoneType类型
def func1():
print(1)
print(2)
print(3)
# print(type(func1)) # function
# print(type(func1())) # NoneType
print("********************************************************")
# yield 关键字
def func2():
print(1)
yield 100
print(2)
yield 200
print(3)
yield 300
print(type(func2)) # function
print(type(func2())) # generator
a = func2()
print(next(a))
print(next(a))
# [(print(1)-100),(print(2)-200),(print(3)-300)]
num = func2() # generator
# next(num)
# next(num)
# next(num)
# next(num) # StopIteration
print(next(num)) # next:会依次返回yield后面的数据
| false |
16752c42c19fb346530892de7ff2966d8a66e245 | wxl789/python | /Day10/2-代码/面向对象/4-通过对象调用类中的属性或函数.py | 1,771 | 4.40625 | 4 | # Wife的类
class Wife():
name = ""
height = 1.5
weight = 50.0
# 创建普通的成员方法的方式与之前创建def的方式一致,只是第一个形参默认
# 为self。
# 初始值 返回值 多个形参
def goShopping(self):
print("妻子能购物")
def makeHousework(self):
print("贤惠的做家务")
def hideMoney(self, money):
print("辛苦藏了%s的私房钱" % money)
# 只要通过某个类创建出来的实例对象,实例对象可以调用该类中的任意一个
# 属性或方法,实例对象可以调用任意次数。
# 实例化一个对象
wife1 = Wife()
'''
对象访问类中的属性
获取类中属性的值:对象名.属性名
修改类中属性的值:对象名.属性名 = 新值
'''
print(wife1.height)
wife1.height = 1.6
print(wife1.height)
wife1.name = "苍老师"
print(wife1.name)
'''
对象访问类中的方法
语法格式:对象名.函数名(参数列表)
注:类中的成员方法默认第一个形参叫self,当实例对象调用该方法时,
系统默认将实例对象传给self形参,不用我们手动传值。
注:实例对象调用成员方法时,第一个形参self可以忽略,但其他形参不能
省略。
'''
wife1.goShopping()
wife1.makeHousework()
wife1.hideMoney(100)
# 关键字形式
wife1.hideMoney(money=1000)
# 类中不存在的属性或变量不能直接使用
# wife1.findMoney(100)
print(wife1.name)
# 动态添加属性(后面会讲),只对当前实例对象有效
wife1.age = 22
print(wife1.age)
wife2 = Wife()
print(wife2.height) #1.5
# 调用成员方法
wife2.goShopping()
# 浅拷贝
wife3 = wife1
print(wife3.height)
print(wife3.name)
wife3.name = "小鸽子"
print(wife3.name)
print(wife1.name)
| false |
615e85b944a61c73a1e1e0a2c99738750ebd112a | CHANDUVALI/Python_Assingment | /python27.py | 274 | 4.21875 | 4 | #Implement a progam to convert the input string to lower case ( without using standard library)
Str1=input("Enter the string to be converted uppercase: ")
for i in range (0,len(Str1)):
x=ord(Str1[i])
if x>=65 and x<=90:
x=x+32
y=chr(x)
print(y,end="")
| true |
a105fe7cfd70b8b8eae640aae6983f5fddb64d09 | CHANDUVALI/Python_Assingment | /cal.py | 399 | 4.375 | 4 | # Implement a python code for arithmetic calculator for operation *, / , + , -
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
choice = input("Enter choice(+,-,*,/):")
if choice == '+':
print(num1 + num2);
elif choice == '-':
print(num1 - num2);
elif choice == '*':
print(num1 * num2);
elif choice == '/':
print(num1 / num2);
else:
print("invalid input")
| false |
6c299c77b83d1f18798aacebb941d947de7236d4 | monajalal/Python_Playground | /binary_addition.py | 510 | 4.1875 | 4 | '''
Implement a function that successfully adds two numbers together and returns
their solution in binary. The conversion can be done before, or after the
addition of the two. The binary number returned should be a string!
Test.assert_equals(add_binary(51,12),"111111")
'''
#the art of thinking simpler is POWER
def add_binary(a,b):
#your code here
#binary_sum = bin(a + b)
#b_index = binary_sum.index('b')
#return binary_sum[b_index+1:]
return bin(a + b)[2:]
print(add_binary(51, 12))
| true |
cce21967d8f50cdc3ac1312886f909db26cae7cf | bjgrant/python-crash-course | /voting.py | 1,033 | 4.3125 | 4 | # if statement example
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
# else stament example
else:
print("Sorry, you are too young to vote!")
print("Please register to vote as soon as you turn 18!")
# if-elif-else example
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
# more concise way of writing it
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
# adding multiple elif blocks
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
# not using an else block
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
| true |
0efc11ea4177989652d50c18eaeca9cf25988c18 | bjgrant/python-crash-course | /cars.py | 594 | 4.53125 | 5 | # list of car makers
cars = ["bmw", "audi", "toyota", "subaru"]
# sorts the list alphabetically
cars.sort()
print(cars)
# sorts the list in reverse alphabetic order
cars = ["bmw", "audi", "toyota", "subaru"]
cars.sort(reverse=True)
print(cars)
cars = ["bmw", "audi", "toyota", "subaru"]
# Print the list contents sorted, but do change the list itself
print("Here is the original list:")
print(cars)
print("Here is the sorted list:")
print(sorted(cars))
print("Here is the original list again:")
print(cars)
# reverse the order of the list
print(cars)
cars.reverse()
print(cars)
print(len(cars)) | true |
5bfeeb9948c267f0d0a4029800ef0cd8157a3689 | Japoncio3k/Hacktoberfest2021-5 | /Python/sumOfDigits.py | 225 | 4.1875 | 4 | num = int(input("Enter a number: "));
if(num<0):
print('The number must be positive')
else:
total = 0;
while num!=0:
total += num%10;
num = num//10;
print("The sum of the digits is: ", total); | true |
1d52ec1e83e2f428223741dde50588025375dd26 | derekhua/Advent-of-Code | /Day10/Solution.py | 1,859 | 4.125 | 4 | '''
--- Day 10: Elves Look, Elves Say ---
Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones", which becomes 1221 (1 2, 2 1s).
Look-and-say sequences are generated iteratively, using the previous value as input for the next step. For each step, take the previous value, and replace each run of digits (like 111) with the number of digits (3) followed by the digit itself (1).
For example:
1 becomes 11 (1 copy of digit 1).
11 becomes 21 (2 copies of digit 1).
21 becomes 1211 (one 2 followed by one 1).
1211 becomes 111221 (one 1, one 2, and two 1s).
111221 becomes 312211 (three 1s, two 2s, and one 1).
Starting with the digits in your puzzle input, apply this process 40 times. What is the length of the result?
Your puzzle answer was 360154.
--- Part Two ---
Neat, right? You might also enjoy hearing John Conway talking about this sequence (that's Conway of Conway's Game of Life fame).
Now, starting again with the digits in your puzzle input, apply this process 50 times. What is the length of the new result?
Your puzzle answer was 5103798.
Both parts of this puzzle are complete! They provide two gold stars: **
'''
# num_str is a string
# count is a in
# returns a string
def look_and_say(num_str, counts):
if counts == 0:
return num_str
builder = ''
candidate = num_str[0]
count = 1
for c in num_str[1:]:
if c != candidate:
builder += str(count) + candidate
candidate = c
count = 1
else:
count +=1
builder+= str(count) + candidate
return look_and_say(builder, counts-1)
print '40 times: ' + str(len(look_and_say('1113122113', 40)))
print '50 times: ' + str(len(look_and_say('1113122113', 50)))
| true |
2ad7197fd85f713b16fece5d7253bb4a4bd8b606 | JuanSaldana/100-days-of-code-challenges | /day-19/turtle_race.py | 1,638 | 4.125 | 4 | from turtle import Turtle, Screen, colormode
from random import randint
colormode(255)
def set_random_color(turtle: Turtle):
r, g, b = randint(0, 255), randint(0, 255), randint(0, 255)
turtle.color((r, g, b))
def setup_race(n):
turtles = []
screen_size = screen.screensize()
step = screen_size[1]/n
initial_pos = step/2.
y_pos = [initial_pos + i*step + y_offset for i in range(n)]
x_pos = [20 + x_offset]*n
for i in range(n):
turtle = Turtle("turtle")
turtles.append(turtle)
turtle.penup()
set_random_color(turtle)
turtle.setpos((x_pos[i], y_pos[i]))
return turtles
def race(turtles):
winner = None
while not winner:
for turtle in turtles:
turtle.forward(randint(5, 30))
winner = next(
(turtle for turtle in turtles if turtle.position()[0] >= race_limit), None)
return winner
screen = Screen()
x_offset = -500
y_offset = -200
race_limit = 800 + x_offset
size = (400, 1000)
screen.setup(height=size[0], width=size[1])
# screen.setworldcoordinates(-500, -100, 500, 100)
screen.screensize(canvheight=size[0], canvwidth=size[1])
n_turtles = 10
# Setup race
turtles = setup_race(n_turtles)
# ask turtle's name
turtle_id = screen.numinput(
"Bet for a turtle", f"Pick a number between 0 and {n_turtles-1}")
# Start race
winner = race(turtles)
winner_id = turtles.index(winner)
screen.title(f"WINNER IS TURTLE {winner_id}")
if winner_id == turtle_id:
message = "YOU WIN"
else:
message = "YOU LOOSE"
# Print race's output
screen.textinput(message, "Please just enter to leave")
screen.listen()
| true |
8412be3158ced9cda22b82984ba0b2296c3da8a2 | jsculsp/python_data_structure | /11/buildhist.py | 1,361 | 4.25 | 4 | # Prints a histogram for a distribution of the letter grades computed
# from a collection of numeric grades extracted from a text file.
from maphist import Histogram
def main():
# Create a Histogram instance for computing the frequencies.
gradeHist = Histogram('ABCDF')
# Open the text file containing the grades.
with open('cs101grades.txt') as gradeFile:
content = gradeFile.readlines()
# Extract the grades and increment the appropriate counter.
lst = []
for line in content:
lst += line.split(' ')
for i in lst:
grade = int(i)
gradeHist.incCount(letterGrade(grade))
# Print the histogram chart.
printChart(gradeHist)
# Determine the letter grade for the given numeric value.
def letterGrade(grade):
if grade >= 90:
return 'A'
elif grade >= 80:
return 'B'
elif grade >= 70:
return 'C'
elif grade >= 60:
return 'D'
else:
return 'F'
# Print the histogram as a horizontal bar chart.
def printChart(gradeHist):
print(' Grade Distribution.')
# Print the body of the chart.
letterGrades = ('A', 'B', 'C', 'D', 'F')
for letter in letterGrades:
print(' |')
print(letter + ' +'),
freq = gradeHist.getCount(letter)
print('*' * freq)
# Print the x-axis.
print(' |')
print(' ' + '+----' * 8)
print(' 0 5 10 15 20 25 30 35')
# Call the main routine.
if __name__ == '__main__':
main() | true |
4d79e76fceb858235da96274f62274bd8bc9fa7a | jsculsp/python_data_structure | /2/gameoflife.py | 1,548 | 4.25 | 4 | # Program for playing the game of Life.
from life import LifeGrid
from random import randrange
# Define the initial configuration of live cells.
INIT_CONFIG = [(randrange(10), randrange(10)) for i in range(50)]
# Set the size of the grid.
GRID_WIDTH = 10
GRID_HEIGHT = 10
# Indicate the number of generations.
NUM_GENS = 20
def main():
# Construct the game grid and configure it.
grid = LifeGrid(GRID_WIDTH, GRID_HEIGHT)
grid.configure(INIT_CONFIG)
# Play the game.
print('This is the initial generation: ')
draw(grid)
for i in range(NUM_GENS):
print('This is generation %s: ' % (i + 1))
evolve(grid)
draw(grid)
# Generates the next generation of organisms.
def evolve(grid):
# List for storing the live cells of the next generations.
liveCells = list()
# Iterate over the elements of the grid.
for i in range(grid.numRows()):
for j in range(grid.numCols()):
# Determine the number of live neighbors for this cell.
neighbors = grid.numLiveNeighbors(i, j)
# Add the (i, j) tuple to liveCells if this cell contains
# a live organism in the next generation.
if (neighbors == 2 and grid.isLiveCell(i, j)) or \
(neighbors == 3):
liveCells.append((i, j))
# Reconfigure the grid using the liveCells coord list.
grid.configure(liveCells)
# Prints a text-based representation of the game grid.
def draw(grid):
for i in range(grid.numRows()):
for j in range(grid.numCols()):
print grid[i, j],
print ''
print '\n\n'
# Executes the main routine
if __name__ == '__main__':
main() | true |
7b37bb7acc6c035aaeb649d750983ec9af284bdc | jsculsp/python_data_structure | /8/priorityq.py | 1,346 | 4.1875 | 4 | # Implementation of the unbounded Priority Queue ADT using a Python list
# with new items append to the end.
class PriorityQueue(object):
# Create an empty unbounded priority queue.
def __init__(self):
self._qList = list()
# Return True if the queue is empty.
def isEmpty(self):
return len(self) == 0
# Return the number of items in the queue.
def __len__(self):
return len(self._qList)
# Add the given item to the queue.
def enqueue(self, item, priority):
# Create a new instance of the storage class and append it to the list.
entry = _PriorityQEntry(item, priority)
self._qList.append(entry)
# Remove and return the first item in the queue.
def dequeue(self):
assert not self.isEmpty(), 'Cannot dequeue from an empty queue.'
# Find the entry with the highest priority.
highest = self._qList[0].priority
for i in range(self.len()):
# See if the ith entry contains a higher priority (smaller integer).
if self._qList[i].priority < highest:
highest = self._qList[i].priority
# Remove the entry with the highest priority and return the item.
entry = self._qList.pop(highest)
return entry.item
# Private storage class for associating queue items with their priority.
class _PriorityQEntry(object):
def __init__(self, item, priorty):
self.item = item
self.priority = priority | true |
c83fe07fcf908618d2c1659fcecd53d7f65fa16e | daid3/PracticeOfPython | /201802/180219CalculateBMI.py | 1,808 | 4.1875 | 4 | #By 000
####本程序计算BMI(Body Mass Index 身体质量指数)
##Python分支的应用:编写一个根据体重和身高计算并输出 BMI值的程序,要求同时输出国际和国内的BMI指标建议值。
# 分类 | 国际BMI值(kg/m^2) | 国内BMI值(kg/m^2)
# 偏瘦 | < 18.5 | <18.5
# 正常 | 18.5~25 | 18.5~24
# 偏胖 | 25~30 | 24~28
# 肥胖 | >=30 | >=28
#emmmmm guaiguaide
def CalculateBMI():
weight=0.0
height=0.0
moreInput="yes"
while moreInput[0]=="y":
weight = eval(input("请输入体重值(kg):"))
height = eval(input("请输入身高值(m):"))
calBMI = weight / (height ** 2)
print("计算得出的BMI值为:", calBMI)
if calBMI < 18.5:
print("对比国际及国内BMI值指标,此BMI为偏瘦...")
elif calBMI < 24:
print("国内BMI指标建议值为:正常")
elif calBMI < 25:
print("国际BMI指标建议值为:正常")
moreInput=input("想要继续计算吗?(yes or no):")
CalculateBMI()
####对分支程序的分析:
# 请分析下面的程序。若输入score为80,输出 grade为多少?是否符合逻辑,为什么?
def CalScore():
score=eval(input("请输入分数:"))
if score >=60.0:
grade='D'
elif score>=70.0:
grade='C'
elif score>=80.0:
grade='B'
elif score>=90.0:
grade='A'
print("grade为:",grade)
# CalScore()
#程序执行结果:
# 请输入分数:80
# grade为: D
### 结果应该是B的!,但是实际输出结果为 D!因为在第一个if判断里面,80是>60的!所以直接输出了 D!!
#####回顾Python分支和循环的用法! | false |
740cb7bc4bd7ba52c7fc4e93458310faedb75a04 | daid3/PracticeOfPython | /201803/180306OOExample.py | 2,447 | 4.125 | 4 | # !/usr/bin/env python
# encoding: utf-8
__author__ = 'Administrator'
#------------面向对象程序设计的例子
#铅球飞行轨迹计算
#铅球对象的属性:xpos,ypos,xvel,yvel
#构建投射体类 Projectile
#创建和更新对象的变量
from math import *
#Projectile类:
class Projectile:
def __init__(self,angle,velcity,height):
#根据给定的发射角度、初始速度和位置创建一个投射体对象
self.xpos=0.0
self.ypos=height
theta=radians(angle)
self.xvel=velcity*cos(theta)
self.yvel=velcity*sin(theta)
def update(self,time):
#更新投射体的状态
self.xpos=self.xpos+time*self.xvel
yvel1=self.yvel-9.8* time
self.ypos=self.ypos+time*(self.yvel+yvel1)/2.0
self.yvel=yvel1
def getY(self):
#返回投射体的角度
return self.ypos
def getX(self):
#返回投射体的距离
return self.xpos
def getInputs():
angle = eval(input("Enter the launch angle (in degrees):"))
vel = eval(input("Enter the initial velocity(in meters/sec):"))
h0 = eval(input("Enter the initial height (in meters):"))
time = eval(input("Enter the time interval:"))
return angle,vel,h0,time
#主函数:
def main():
angle,vel,h0,time=getInputs()
shot=Projectile(angle,vel,h0)
while shot.getY()>=0:
shot.update(time)
print("\n Distance traveled:{0:0.1f} meters..".format(shot.getX()))
if __name__ == '__main__':
main()
#程序运行结果:
# Enter the launch angle (in degrees):30
# Enter the initial velocity(in meters/sec):20
# Enter the initial height (in meters):50
# Enter the time interval:60
#
# Distance traveled :1039.2meters.
#选手1 技术强:铅球的出手角度41度,出手速度14米/秒,初始高度1.8米,仿真间隔0.3秒,
#结果:铅球最远飞行距离 22.2米
# Enter the launch angle (in degrees):41
# Enter the initial velocity(in meters/sec):14
# Enter the initial height (in meters):1.8
# Enter the time interval:0.3
#
# Distance traveled:22.2 meters..
#选手2 力量大:铅球的出手角度30度,出手速度15米/秒,初始高度2米,仿真间隔0.3秒,
#结果:铅球最远飞行距离 23.4米
# Enter the launch angle (in degrees):30
# Enter the initial velocity(in meters/sec):15
# Enter the initial height (in meters):2
# Enter the time interval:0.3
#
# Distance traveled:23.4 meters.. | false |
ac0ca45de03da9e85d16cbd00e07595e92ceb8cc | Ethan2957/p02.1 | /fizzbuzz.py | 867 | 4.5 | 4 | """
Problem:
FizzBuzz is a counting game. Players take turns counting the next number
in the sequence 1, 2, 3, 4 ... However, if the number is:
* A multiple of 3 -> Say 'Fizz' instead
* A multiple of 5 -> Say 'Buzz' instead
* A multiple of 3 and 5 -> Say 'FizzBuzz' instead
The function fizzbuzz should take a number and print out what the player
should say.
Tests:
>>> fizzbuzz(7)
7
>>> fizzbuzz(10)
Buzz
>>> fizzbuzz(12)
Fizz
>>> fizzbuzz(30)
FizzBuzz
"""
# Use this to test your solution. Don't edit it!
import doctest
def run_tests():
doctest.testmod(verbose=True)
# Edit this function
def fizzbuzz(n):
if n %3 == 0 and n %5 == 0:
print("FizzBuzz")
elif n %3 == 0:
print("Fizz")
elif n %5 == 0:
print("Buzz")
else:
print(n)
| true |
7307669144fb61678697580311b3e82de4dc9784 | sujoy98/scripts | /macChanger.py | 2,495 | 4.34375 | 4 | import subprocess
import optparse
# 'optparse' module allows us to get arguments from the user and parse them and use them in the code.
# raw_input() -> python 2.7 & input() -> python3
# interface = raw_input("Enter a interface example -> eth0,wlan0 :-")
'''
OptionParser is a class which holds all the user input arguments by
creating a object 'parser' i.e we cant use the class without making an instance or
object of the class here it is 'parser'.
'''
# from optparse import OptionParser
parser = optparse.OptionParser()
parser.add_option("-i", "--interface", dest="interface", help="interface modules like eth0, wlan0, etc.")
parser.add_option("-m", "--mac", dest="new_mac", help="example -> 00:xx:xx:xx:xx:xx")
'''
when we call .parse_args(), it will go through everything the user inputs and
separate it into two sets of information the first is arguments which is --interface and --mac and the
second one is the values i.e eth0 or wlan and the mac address
'''
'''
.parse_args() method will return two sets of information arguments and options, and to capture that we
are using two variables, we are calling them (options and arguments) which is equal to whatever it will return
through parser.parse_args()
'''
(options, arguments) = parser.parse_args()
# variables 1. interface 2. new_mac
# interface = input("Enter a interface example -> eth0,wlan0 :-")
# new_mac = input("Enter new Mac example -> 00:xx:xx:xx:xx:xx :-")
# to use the user input options we need to use options.interface and options.new_mac
interface = options.interface
new_mac = options.new_mac
print("[+] Changing MAC address for " + interface + " to " + new_mac)
'''
with this this script can be manipulated
by wlan0;ls;(in linux we can run multiple commands using ;) -> we are injecting two another extra command which
is not secure for out script
'''
# subprocess.call("ifconfig " + interface + " down", shell=True)
# subprocess.call("ifconfig " + interface + " hw ether " + new_mac, shell=True)
# subprocess.call("ifconfig " + interface + " up", shell=True)
'''
This is an another process to run subprocess in a secure way
using a list here we close quotations in place of space in the command and
as interface is a variable we doesn't need to put that in quotations
'''
subprocess.call(["ifconfig", interface, "down"])
subprocess.call(["ifconfig", interface, "hw", "ether", new_mac])
subprocess.call(["ifconfig", interface, "up"])
| true |
b3ccaee062de1a1701e4376c17af80b4f8450606 | robot-tutorial/robotics_tutorial | /python/loop.py | 542 | 4.15625 | 4 | # range
for i in range(10):
print(i, end=' ') # 取消换行
for i in range(5, 10):
print(i, end=' ')
for i in range(5, 10, 2):
print(i, end=' ')
# loop over a list
courses = ['Calculus', 'Linear Algebra', 'Mechanics']
# low-level
for i in range(3):
print(courses[i])
# advanced
for course in courses:
print(course)
# advanced
for i, course in enumerate(courses):
print(f'The No.{i+1} course is {course}')
# list a range
mylist = list(range(1, 101))
print(mylist)
sum = 0
for i in mylist:
sum += i
print(sum)
| false |
4da9e5bb9096d891064eb88bfa4ccfd5bcf95447 | catechnix/greentree | /sorting_two_lists.py | 502 | 4.15625 | 4 | """
compared two sorted arrays and return one that combining the two arrays
into one which is also sorted, can't use sort function
"""
array1=[0,3,2,1,6]
array2=[1,2,4,5]
print(array2)
for i in array1:
if i not in array2:
array2.append(i)
print(array2)
array3=[]
while array2:
minimum = array2[0] # arbitrary number in list
for x in array2:
if x < minimum:
minimum = x
array3.append(minimum)
array2.remove(minimum)
print(array3)
| true |
32061facf23b68d0d1b6f7794366186dba758ead | catechnix/greentree | /print_object_attribute.py | 442 | 4.375 | 4 | """
Write a function called print_time that takes a Time object and prints it in the form hour:minute:second.
"""
class Time():
def __init__(self,hour,minute,second):
self.hour=hour
self.minute=minute
self.second=second
present_time=Time(12,5,34)
def print_time(time):
time_text="The present time is {:2d}:{:2d}:{:2d}"
print(time_text.format(time.hour,time.minute,time.second))
print_time(present_time)
| true |
fa3eb3ea8a585370c8f2aaebd508ed4927a93dd6 | dreaminkv/gb_basic_python | /TolstovMikhail_dz_11/task_11_7.py | 936 | 4.21875 | 4 | # Реализовать проект «Операции с комплексными числами». Создать класс «Комплексное число».
# Реализовать перегрузку методов сложения и умножения комплексных чисел. Проверить работу проекта.
# Для этого создать экземпляры класса (комплексные числа), выполнить сложение и умножение созданных
# экземпляров. Проверить корректность полученного результата.
class Complex_nums:
def __init__(self, num):
self.num = num
def __add__(self, other):
return self.num + other.num
def __mul__(self, other):
return self.num * other.num
b = Complex_nums(22)
print(b)
c = Complex_nums(22)
print(b + c)
print(b * c)
| false |
8f6253e19d64eb0b4b7630e859f4e3a143fb0833 | IBA07/Test_dome_challanges | /find_roots_second_ord_eq.py | 751 | 4.1875 | 4 | '''
Implement the function find_roots to find the roots of the quadriatic equation:
aX^2+bx+c.
The function should return a tuple containing roots in any order. If the equation has only one solution, the function should return that solution as both elements of the tuple. The equation will always have at least one solution.
The roots of the quadriatic equation can be ound with the following formula:
x1,2=(-b+-sqrt(b^2-4ac))/2a
For example, find_roots(2,10,8) should return (-1, -4) or (-4,-1) as the roots of the equation 2x^2+10x+8=0 are -1 and -4.
'''
def find_roots(a, b, c):
import math
delta = b**2-4*a*c
x1 = (-1*b+math.sqrt(delta))/(2*a)
x2 = (-1*b-math.sqrt(delta))/(2*a)
return x1,x2
print(find_roots(2, 10, 8)); | true |
91bd2e803e12dae1fb6dad102e24e11db4dfdb03 | ZainabFatima507/my | /check_if_+_-_0.py | 210 | 4.1875 | 4 | num = input ( "type a number:")
if num >= "0":
if num > "0":
print ("the number is positive.")
else:
print("the number is zero.")
else:
print ("the number is negative.")
| true |
524b1d0fa45d90e7a326a37cc1f90cdabc1942e0 | CTEC-121-Spring-2020/mod-5-programming-assignment-Rmballenger | /Prob-1/Prob-1.py | 2,756 | 4.1875 | 4 | # Module 4
# Programming Assignment 5
# Prob-1.py
# Robert Ballenger
# IPO
# function definition
def convertNumber(numberGiven):
# Here a if/elif loop occurs where it checks if the numberGiven is equal to any of the numbers below, and if it does it prints the message.
if numberGiven == 1:
print("Your number of", numberGiven,
"converted to Roman Numerals is I")
elif numberGiven == 2:
print("Your number of", numberGiven,
"converted to Roman Numerals is II")
elif numberGiven == 3:
print("Your number of", numberGiven,
"converted to Roman Numerals is III")
elif numberGiven == 4:
print("Your number of", numberGiven,
"converted to Roman Numerals is IV")
elif numberGiven == 5:
print("Your number of", numberGiven,
"converted to Roman Numerals is V")
elif numberGiven == 6:
print("Your number of", numberGiven,
"converted to Roman Numerals is VI")
elif numberGiven == 7:
print("Your number of", numberGiven,
"converted to Roman Numerals is VII")
elif numberGiven == 8:
print("Your number of", numberGiven,
"converted to Roman Numerals is VIII")
elif numberGiven == 9:
print("Your number of", numberGiven,
"converted to Roman Numerals is IX")
elif numberGiven == 10:
print("Your number of", numberGiven,
"converted to Roman Numerals is X")
# Here it checks if the number is out of the 1-10 range.
elif numberGiven > 10 or numberGiven < 1:
print("I said a number BETWEEN 1 and 10.\nPlease try again...")
return
'''
main()
'''
# unit test function
def unitTest():
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Unit Tests")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# Here in my unit testing, I run a loop that checks the function with all all the potentail options the function is set to expect. I decided to use a range of 12 so both 0 and 11 are tested as well.
for numberGiven in range(12):
convertNumber(numberGiven)
print("\n")
def main():
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Main")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# For my main function here, it's just a simple input request. I do have an int selected so it makes sure to send the number as an int and not a string. I also added a break for readability. The program then calls the function convertNumber() with the paramater of whatever number was given by the user.
numberGiven = int(input("Pick a number 1 through 10\n"))
convertNumber(numberGiven)
unitTest()
main()
| true |
beca7f8a9a8a4caea549852badd96324da92a245 | sanchit0496/Python_Practice | /scratch_36.py | 322 | 4.1875 | 4 | #Dictionary
D= {1:"Hello", 2: "World"}
print(D)
my_dict = dict(item1="Apple", item2="Orange")
print(my_dict)
my_dict={x:x*x for x in range(8)}
print(my_dict)
my_dict={y:y*y for y in range(8)}
print(my_dict)
my_dict={'name':'John',1:[2,4,5]}
print(my_dict)
my_dict={'name':'John',1:['Hello','World',5]}
print(my_dict) | false |
03f6b186c0858c30b3ec64a7954bc98d6c2b169f | StephenTanksley/cs-algorithms | /moving_zeroes/moving_zeroes.py | 1,662 | 4.1875 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
"""
U - Input is a list of integers. The list of integers will have some 0s included in it.
The 0s need to be pushed to the tail end of the list. The rest of the list needs to remain in order.
P1 (in-place swap plan) -
1) We need a way of keeping track of where we are in the array.
2) We need to know the total length of the array.
3) We need to determine if an object at a certain index is equal to 0.
4) If the integer at the next looping index is NOT equal to 0, we can insert at that index.
5) We don't actually need to touch the 0s.
P2 (ugly-stepchild recombinant lists plan) -
1) - Count the number of zeroes in the array.
2) - Remove all zeroes from the array.
3) - Create a new array with the correct number of zeroes.
4) - Squash the old array (minus zeroes) together with the new array (with the right number of zeroes)
5) - Profit.
E - We'll need a counter, a list comprehension,
a new array for the correct number of zeroes,
and then to put things together.
R - Look for a way of cleaning these functions up.
Ideally, we'd want to use the in-place swap because it wouldn't require more space.
"""
def moving_zeroes(arr):
item_count = arr.count(0)
minus_zero = [item for item in arr if item != 0]
add_zero = [0] * item_count
final_array = minus_zero + add_zero
return final_array
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [0, 3, 1, 0, -2]
print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
| true |
fe2435cbaa4ebd9a2f7baca925e532e4fb5f6261 | myllenamelo/Exerc-cio | /Q1_Tupla_Myllena_Melo.py | 1,089 | 4.21875 | 4 | '''
seu carlos está abrindo uma lanchonete com apenas atendimento para delivery,
levando em conta que não haverá loja fisica, o atendimento será online.
Ajude seu Carlos a montar o cardápio da lanchonete.
1- Ultilizando tuplas monte todo o cardápio com comidas e bebidas por enquanto não precisa do preço
2- deve mostrar quantos itens existem no cardápio
3- o programa deve mostrar as comidas e bebidas separadas
'''
lanchonete =('Hamburguer','Coca cola','Cachorro quente','Fanta','Bolo de banana','Antártica','Batata frita','Suco de limão')
i = 0
n = ""
print('---------------------------------')
print('| Lanchonete do seu Carlos |')
print('---------------------------------')
print(' LANCHE BEBIDA ')
print('---------------------------------')
#leitura da tupla
for c in range(0, len(lanchonete)):
if(i != len(lanchonete)):
print('|',lanchonete[i],'-',lanchonete[i+1],'\t|')
i += 2
print('----------------------------------')
print('Total de itens do cardápio:',len(lanchonete))
print('----------------------------------')
| false |
4186c4b7ce7404bdb82854787a04983a3b1dd7c7 | priyankitshukla/pythontut | /Logical Operator.py | 594 | 4.25 | 4 | is_Hot=False
is_Cold=False
if is_Hot:
print('''
Its very hot day
Drink Plenty of water
''')
elif is_Cold:
print('Its a cold day')
else:
print('Its a lovely day')
print('Enjoy your day!')
# Excersise with logical operator
if is_Cold==False and is_Hot==False:
print("Both condidtion's are false")
if is_Cold==False and not is_Hot:
print("Both condidtion's are false")
#condition
temperature=30
if temperature>30:
print('Hot Day')
elif temperature<30 and temperature>20:
print('Lovely day')
else:
print('Cold day')
| true |
dcfeb5f5a83c47e5123cf8e0c07c39a8ed246898 | afahad0149/How-To-Think-Like-A-Computer-Scientist | /Chap 8 (STRINGS)/exercises/num5(percentage_of_a_letter).py | 1,515 | 4.3125 | 4 | import string
def remove_punctuations(text):
new_str = ""
for ch in text:
if ch not in string.punctuation:
new_str += ch
return new_str
def word_frequency (text, letter):
words = text.split()
total_words = len(words)
words_with_letter = 0
for word in words:
if letter in word:
words_with_letter += 1
frequency = (words_with_letter/total_words)*100
print ("Your text contains {0} words, of which {1} ({2:.2f}%) contain an '{3}'.".
format(total_words, words_with_letter, frequency, letter))
text = """“Voilà!
In view, a humble vaudevillian veteran cast vicariously as both victim
and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity,
is a vestige of the vox populi, now vacant, vanished.
However, this valorous visitation of a bygone vexation stands vivified
and has vowed to vanquish these venal and virulent vermin
vanguarding vice and vouchsafing the violently vicious
and voracious violation of volition! The only verdict is vengeance;
a vendetta held as a votive, not in vain,
for the value and veracity of such shall one day vindicate
the vigilant and the virtuous. [laughs] Verily, this vichyssoise of verbiage
veers most verbose, so let me simply add that
it’s my very good honor to meet you and you may call me “V”."""
no_punct_text = remove_punctuations(text)
#print(no_punct_text)
word_frequency(no_punct_text,'e')
word_frequency(no_punct_text,'v') | true |
c4d70d36aac58acf24e9dc492266e1e32a36aa4e | magedu-python22/homework | /homework/10/P22048-fuzhou-xiaojie/homework10.py | 1,583 | 4.15625 | 4 | # 自定义 map, reduce, filter 接受两个参数(fn, iterable)
# 检测iterable 是否为可迭代对象, 如果不是抛出异常 “Iterable not is Iterable”
from collections import Iterable
def add(x, y):
return x + y
def is_odd(x):
return x % 2 == 1
class MyException(Exception):
pass
class Custom:
def __init__(self, fn, iterable):
self.fn = fn
self.iterable = iterable
def map(self):
try:
if isinstance(self.iterable, Iterable):
return self.fn(*self.iterable)
else:
raise MyException
except MyException:
print('Iterable not is Iterable')
def reduce(self):
try:
if isinstance(self.iterable, Iterable):
result = 0
for i in self.iterable:
result += i
return result
else:
raise MyException
except MyException:
print('Iterable not is Iterable')
def filter(self):
try:
if isinstance(self.iterable, Iterable):
result = []
for i in self.iterable:
if self.fn(i):
result.append(i)
return result
else:
raise MyException
except MyException:
print('Iterable not is Iterable')
m = Custom(add, [3, 4])
print(m.map())
r = Custom(add, [1, 2, 3, 4, 5])
print(r.reduce())
f = Custom(is_odd, [1, 2, 3, 4, 5, 6, 7])
print(f.filter()) | false |
c5262a687592caede04cadc4f18ef5a66c8b9e0d | Chandu0992/youtube_pthon_practice | /core/array_example_one.py | 1,044 | 4.15625 | 4 | '''from array import *
arr = array('i',[])
n = int(input("Please Enter size of the array : "))
for i in range(n):
x = int(input("Enter next Value : "))
arr.append(x)
#manual method
print(arr)
s = int(input("Enter a Value to search : "))
k = 0
for i in arr:
if i == s:
print(k)
break
k += 1
if s not in arr:
print("Element not Found !")
#Inbulit Method
print(arr.index(s))
'''
#Assignment Questions
#1) Create an array with 5 values and delete the value at index number 2 without using in-built function
#2) write a code to reverse an array without using in-built function
from array import *
arr = array('i',[])
n = int(input("Enter size of an array : "))
for i in range(n):
x = int(input("Please Enter a value : "))
arr.append(x)
print(arr)
s = int(input("Enter value to delete : "))
for i in arr:
if i == s:
#arr.remove(s) #delete the particular element
#del arr[i] #delete the element at ith iendex
arr.remove(s)
break
print("After deletion array : ",arr) | true |
5354b5ce25def354480fbd85463224f527e38e83 | Ajat98/LeetCode-2020-Python | /good_to_know/reverse_32b_int.py | 702 | 4.3125 | 4 | '''
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
class Solution:
def reverse(self, x: int) -> int:
if x > 0:
val = int(str(x)[::-1])
else:
x = x*-1
val = int(str(x)[::-1]) *-1
if val > 2**31 -1 or val < -2**31:
return 0
else: return val
| true |
00409eb918845cfc869eb7dec7c9e85292c98d25 | sofyansetiawan/learn-python-bootcamp | /02-intermediate/condition.py | 943 | 4.25 | 4 | x = 3
y = 3
if(x == y):
print("they are equals")
else:
print("the are not equals")
print("program is working fine")
# ------------------
a = 10
b = 10
c = 80
if(a == b):
print("a is equals b")
elif(b > a):
print("b is greater than a")
elif(a > b):
print("a is greater than b")
else:
print("the are not equals")
# -------------------------
skor = 80
if(skor >= 80 and skor <= 100):
print("Nilai Kamu A")
elif(skor >= 60 and skor < 80):
print("Nilai Kamu B")
elif(skor >= 40 and skor < 60):
print("Nilai Kamu C")
elif(skor >= 0 and skor < 40):
print("Nilai Kamu D")
else:
print("Nilai kamu tidak valid")
# --------------------------
types = "Human"
names = "Sofyan"
ages = 30
if(types == "Human"):
if(ages >= 20):
print(f"Welcome.Please {names} drink this beer")
else:
print(f"Welcome.Please {names} drink this juice")
else:
print("You cant enter this house") | false |
412485e1024007908fc7ae3f65bc31897545985b | vaishnavi-gupta-au16/GeeksForGeeks | /Q_Merge Sort.py | 1,565 | 4.125 | 4 | """
Merge Sort
Merge Sort is a Divide and Conquer algorithm. It repeatedly divides the array into two halves and combines them in sorted manner.
Given an array arr[], its starting position l and its ending position r. Merge Sort is achieved using the following algorithm.
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide
the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in
step 2 and 3:
Call merge(arr, l, m, r)
Example 1:
Input:
N = 5
arr[] = {4 1 3 9 7}
Output: 1 3 4 7 9
Link - https://practice.geeksforgeeks.org/problems/merge-sort/1#
"""
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print() | true |
9cadb464d665ebddf21ddc73b136c0cf4026ba11 | chaiwat2021/first_python | /list_add.py | 390 | 4.34375 | 4 | # append to the end of list
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
# insert with index
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
# extend list with values from another list
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
| true |
f47e0a404ee9c531f82b657c0cc4ecc987e9279c | 2flcastro/python-exercises | /solutions/2flcastro/intermediate/smallest_common_multiple.py | 2,773 | 4.375 | 4 | # ----------------------------------
# Smallest Commom Multiple
# ----------------------------------
# Find the smallest common multiple of the provided parameters that can be
# evenly divided by both, as well as by all sequential numbers in the range
# between these parameters.
#
# The range will be a list of two numbers that will not necessarily be in
# numerical order.
#
# e.g. for 1 and 3, find the lowest common multiple of both 1 and 3 that is
# evenly divisible by all numbers BETWEEN 1 and 3.
#
# Helpful Links:
# - https://www.mathsisfun.com/least-common-multiple.html
# - https://www.artofproblemsolving.com/wiki/index.php/Least_common_multiple
# ----------------------------------
import unittest
# Using a while loop to test multiples of the largest number in list,
# incrementing the largest value on itself until it reaches a value all numbers
# in the range can evenly divide into.
def smallest_common(lst):
lst.sort()
largest_num = lst[len(lst) - 1]
scm = largest_num
while True:
for number in range(lst[0], largest_num + 1):
if scm % number != 0:
scm += largest_num
break
else:
# break out of the while-loop if scm found
break
return scm
# There is another formula for finding the SCM of a pair of numbers:
# LCM(a, b) = a * b / GCD(a, b)
# You first need to find the GCD (greatest common divisor), which is done Using
# the Euclidean Algorithm (euclidean_gcd() function).
def smallest_common_2(lst):
def euclidean_gcd(a, b):
if b == 0:
return a
else:
return euclidean_gcd(b, a%b)
lst.sort()
scm = lst[0]
for i in range(lst[0] + 1, lst[len(lst) - 1] + 1):
scm = scm * i / euclidean_gcd(scm, i)
return scm
# ----------------------------------
# Unit Tests
# ----------------------------------
class Test_Smallest_Common(unittest.TestCase):
def test_1(self):
self.assertEqual(smallest_common([1, 5]), 60)
def test_2(self):
self.assertEqual(smallest_common([5, 1]), 60)
def test_3(self):
self.assertEqual(smallest_common([1, 13]), 360360)
def test_4(self):
self.assertEqual(smallest_common([23, 18]), 6056820)
class Test_Smallest_Common_2(unittest.TestCase):
def test_1(self):
self.assertEqual(smallest_common_2([1, 5]), 60)
def test_2(self):
self.assertEqual(smallest_common_2([5, 1]), 60)
def test_3(self):
self.assertEqual(smallest_common_2([1, 13]), 360360)
def test_4(self):
self.assertEqual(smallest_common_2([23, 18]), 6056820)
# ----------------------------------
# Run Tests
# ----------------------------------
if __name__ == "__main__":
unittest.main()
| true |
c253c625f1d74938fc087d2206d75b75c974cd23 | 2flcastro/python-exercises | /beginner/longest_word.py | 1,175 | 4.1875 | 4 | # ----------------------------------
# Find the Longest Word in a String
# ----------------------------------
# Return the length of the longest word in the provided sentence.
#
# Your response should be a number.
# ----------------------------------
import unittest
def find_longest_word(strg):
return len(strg)
# ----------------------------------
# Unit Tests
# ----------------------------------
class Test_Find_Longest_Word(unittest.TestCase):
def test_1(self):
self.assertEqual(find_longest_word('The quick brown fox jumped over the lazy dog'), 6)
def test_2(self):
self.assertEqual(find_longest_word('May the force be with you'), 5)
def test_3(self):
self.assertEqual(find_longest_word('Google do a barrel roll'), 6)
def test_4(self):
self.assertEqual(find_longest_word('What is the average airspeed velocity of an unladen swallow'), 8)
def test_5(self):
self.assertEqual(find_longest_word('What if we try a super-long word such as otorhinolaryngology'), 19)
# ----------------------------------
# Run Tests
# ----------------------------------
if __name__ == '__main__':
unittest.main()
| true |
cb64405d60c43194cb2fd4455a68a4ec7f4441d0 | 2flcastro/python-exercises | /solutions/2flcastro/beginner/longest_word.py | 2,172 | 4.28125 | 4 | # ----------------------------------
# Find the Longest Word in a String
# ----------------------------------
# Return the length of the longest word in the provided sentence.
#
# Your response should be a number.
# ----------------------------------
import unittest
# using list comprehension and max() built-in function
def find_longest_word(strg):
words = strg.split()
return max([len(word) for word in words])
# using split() and a for-loop
def find_longest_word_2(strg):
sentence = strg.split()
longest_word = len(strg[0])
for word in sentence:
if len(word) > longest_word:
longest_word = len(word)
return longest_word
# ----------------------------------
# Unit Tests
# ----------------------------------
class Test_Find_Longest_Word(unittest.TestCase):
def test_1(self):
self.assertEqual(find_longest_word('The quick brown fox jumped over the lazy dog'), 6)
def test_2(self):
self.assertEqual(find_longest_word('May the force be with you'), 5)
def test_3(self):
self.assertEqual(find_longest_word('Google do a barrel roll'), 6)
def test_4(self):
self.assertEqual(find_longest_word('What is the average airspeed velocity of an unladen swallow'), 8)
def test_5(self):
self.assertEqual(find_longest_word('What if we try a super-long word such as otorhinolaryngology'), 19)
class Test_Find_Longest_Word_2(unittest.TestCase):
def test_1(self):
self.assertEqual(find_longest_word_2('The quick brown fox jumped over the lazy dog'), 6)
def test_2(self):
self.assertEqual(find_longest_word_2('May the force be with you'), 5)
def test_3(self):
self.assertEqual(find_longest_word_2('Google do a barrel roll'), 6)
def test_4(self):
self.assertEqual(find_longest_word_2('What is the average airspeed velocity of an unladen swallow'), 8)
def test_5(self):
self.assertEqual(find_longest_word_2('What if we try a super-long word such as otorhinolaryngology'), 19)
# ----------------------------------
# Run Tests
# ----------------------------------
if __name__ == '__main__':
unittest.main()
| true |
5a55b4a608a8512b528fe6ea53bccca2b13bafba | ads2100/100DaysOfPython | /Week#3/Day16.py | 430 | 4.25 | 4 | """----------Day16----------"""
Tuple1 = ( 'cat' , 5 , 1.9 , 'man' )
print(Tuple1)#print all value
print(Tuple1[0])#print index 0
print(Tuple1[ 1 : 4 ])#print from index 1 to 3
Tuple2 = ( 'Dog' , ) #must use ( , ) if there one value
print(Tuple2)
Tuple3 = ( 'Dog' )#will print as a regular value not tuple
print(Tuple3)
Tuple4 = ( 'cat' , 5 , 1.9 , 'man' )
for x in Tuple4: #put all index inside x using for loop
print(x)
| false |
21461cf869ccdbf60483fa57465520315dc12450 | fangfa3/test | /python/BasicAlgorithm/insert_sort.py | 317 | 4.125 | 4 | def insert_sort(array):
length = len(array)
for i in range(1, length):
j = i
while array[j] < array[j - 1] and j > 0:
array[j], array[j-1] = array[j-1], array[j]
j -= 1
if __name__ == '__main__':
A = [2, 4, 5, 8, 1, 9, 7, 6, 3]
insert_sort(A)
print(A) | false |
166f72638df619e350bc3763d1082890106a7303 | smysnk/my-grow | /src/lib/redux/compose.py | 820 | 4.1875 | 4 | """
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* lambda *args: f(g(h(*args)))
"""
def compose(*funcs):
if len(funcs) == 0:
return lambda *args: args[0] if args else None
if len(funcs) == 1:
return funcs[0]
# reverse array so we can reduce from left to right
funcs = list(reversed(funcs))
last = funcs[0]
rest = funcs[1:]
def composition(*args):
composed = last(*args)
for f in rest:
composed = f(composed)
return composed
return composition
| true |
80c7a5e3c64f31e504c793b59951260636c65d17 | mike-something/samples | /movies/movies_0.py | 974 | 4.3125 | 4 | # https://namingconvention.org/python/
#
# define variables for the cost of tickets
#
# we try and use names for variables which are clear and memorable. Its
# good to prefer longer names which are clearer - in a large program this
# can really matter
#
adult_ticket_cost = 18
child_ticket_cost = 10
print('Welcome to the movie price calculator!\n\nHow many tickets do you require?\n\n')
# a simple use of input - there is no validation though so this isn't
# nearly sufficient in the real world
adult_count = int(input('How many adults? '))
child_count = int(input('How many children? '))
total_cost = adult_ticket_cost * adult_count + child_ticket_cost * child_count
# __repr__ is a special thing in python which returns a string representation
# of an object but you can't rely on what is returned being a simple string if
# the object is a complex object
print("\n\nTotal cost to take your family to the movies: " + total_cost.__repr__())
| true |
76db9c3360d671f7461297a63475063908e33df9 | carlos-paezf/Snippets_MassCode | /python/factorial.py | 472 | 4.5 | 4 | #Calculates the factorial of a number.
#Use recursion. If num is less than or equal to 1, return 1.
#Otherwise, return the product of num and the factorial of num - 1.
#Throws an exception if num is a negative or a floating point number.
def factorial(num):
if not ((num >= 0) & (num % 1 == 0)):
raise Exception(
f"Number( {num} ) can't be floating point or negative ")
return 1 if num == 0 else num * factorial(num - 1)
factorial(6) # 720
| true |
c8f0da7555edde737b7f5e8ad697305b1087079c | carlos-paezf/Snippets_MassCode | /python/keys_only.py | 714 | 4.3125 | 4 | #Function which accepts a dictionary of key value pairs and returns
#a new flat list of only the keys.
#Uses the .items() function with a for loop on the dictionary to
#track both the key and value and returns a new list by appending
#the keys to it. Best used on 1 level-deep key:value pair
#dictionaries (a flat dictionary) and not nested data-structures
#which are also commonly used with dictionaries. (a flat dictionary
#resembles a json and a flat list an array for javascript people).
def keys_only(flat_dict):
lst = []
for k, v in flat_dict.items():
lst.append(k)
return lst
ages = {
"Peter": 10,
"Isabel": 11,
"Anna": 9,
}
keys_only(ages) # ['Peter', 'Isabel', 'Anna']
| true |
56f8f9eb11022cce409c96cabf50ecb13273e7df | HaoyiZhao/Text-chat-bot | /word_count.py | 1,116 | 4.34375 | 4 | #!/usr/bin/python
import sys
import os.path
# check if correct number of arguments
if len(sys.argv)!=2:
print "Invalid number of arguments, please only enter only one text file name as the command line argument"
sys.exit()
# check if file exists
if os.path.isfile(sys.argv[1]):
file=open(sys.argv[1], "r+")
wordFrequency={}
# read all words in file into a list, then iterate through list words
for word in file.read().split():
# separate word by hyphens, if it has hyphens
for hyphenWord in word.split('-'):
hyphenWord = ''.join(l for l in hyphenWord if l.isalpha())
# don't add word if it is a empty string after removing non-alphabetic characters(e.g. numbers)
if hyphenWord == '':
continue;
hyphenWord = hyphenWord.lower()
if hyphenWord in wordFrequency:
wordFrequency[hyphenWord] += 1
else:
wordFrequency[hyphenWord] = 1
# sort by second field of tuples (values) returned by items(), then print tuple pairs
file.close()
for k,v in sorted(wordFrequency.items(), key=lambda tup:tup[1], reverse=True):
print "%s:%s" %(k,v)
else:
print "Invalid file name specified"
| true |
c6c066383c6d2fc587e3c2bf5d26ee36c060e288 | sarank21/SummerSchool-Assignment | /SaiShashankGP_EE20B040/Assignment1Q2.py | 1,483 | 4.25 | 4 | '''
Author: Sai Shashank GP
Date last modified: 07-07-2021
Purpose: To find a pair of elements (indices of the two numbers) from a given array whose sum equals a specific target number.
Sample input: 10 20 10 40 50 60 70
Sample ouput: {1: [0, 3], 2: [2, 3], 3: [3, 0], 4: [3, 2]}
'''
# importing useful libraries
import numpy as np
import random
# creating a random numbers list and target number
mean = uniform(0, 10)
std_dev = uniform(0, 10)
numbers = list((np.random.rand(100)*std_dev)+mean)
targetnumber = uniform(0, 100)
def Checkcondition(N, T):
'''
This function checks the required condition for each and every possile pair and returns the list of pairs of required indices.
'''
finallist = []
len_N = len(N)
for i in range(len_N):
for j in range(len(N)):
if N[i]+N[j] == T:
answer = [i, j]
finallist.append(answer)
else:
continue
return finallist
class FindTargetIndices:
'''
This class contains to find indices of a pair of elements in a given list which add up to the given target number.
'''
target_indices = Checkcondition(numbers, targetnumber)
def show(self):
dict_target_indices = {}
for i in range(len(self.target_indices)):
dict_target_indices[i+1] = self.target_indices[i]
print(dict_target_indices)
answer_2 = FindTargetIndices()
answer_2.show()
| true |
11e4324bf7174179c032c239d3b19af379dd871a | Iaraseverino/my-first-repo | /Projects/exercise.py | 397 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 22:05:34 2020
@author: Iari Severino
"""
def is_even():
number = input("type a number: ")
if int(number) % 2 == 0:
print('true')
else: print('False')
is_even()
#%%
def is_odd():
number = input("type a number: ")
if int(number) % 2 == 0:
print('False')
else: print('True')
is_odd() | false |
d5131ecef9b8ab0918033d2a66a4e21ff329dd39 | NinjaOnRails/fillgaps | /fillGaps.py | 916 | 4.15625 | 4 | #! /usr/bin/env python3
# fillGaps - Finds all files with a given prefix in a folder,
# locates any gaps in the numbering and renames them to close the gap.
import shutil, os, re
folder = input("Enter path to the folder containing your files: ")
prefix = input("Enter prefix: ")
def fillGaps(folder, prefix):
regex = re.compile(r'(%s)(\d+)' % prefix)
foundFiles = []
for filename in os.listdir(folder):
if filename.startswith(prefix):
foundFiles.append(filename)
foundFiles.sort()
for i in range(1, len(foundFiles) + 1):
mo = regex.search(foundFiles[i-1])
if mo.group(2) != '0'*(3 - len(str(i))) + str(i):
newName = prefix + '0'*(3 - len(str(i))) + str(i)
print('Renaming %s to %s' % (foundFiles[i-1], newName))
shutil.move(os.path.join(folder, foundFiles[i-1]), os.path.join(folder, newName))
fillGaps(folder, prefix)
| true |
23152386219203cd737c4dde47f9822c410ba181 | enriqueee99/learning_python | /ejercicio_16.1.py | 466 | 4.25 | 4 | personas = {}
for x in range(3):
numero = int(input('Ingrese el numero de la persona: '))
nombre = input('Ingrese el nombre de la persona: ')
personas[numero] = nombre
print('Listado completo de las personas: ')
for numero in personas:
print(numero, personas[numero])
num_consulta = int(input('¿Qué numero desea consultar?: '))
if num_consulta in personas:
print(f'La persona es: ', personas[numero] )
else:
print('La persona no existe.') | false |
a7aff197a21019a5e75502ad3e7de79e08f80465 | jesusbibieca/rock-paper-scissors | /piedra_papel_tijeras.py | 2,820 | 4.4375 | 4 | ##Rock, paper o scissors##
#Written by Jesus Bibieca on 6/21/2017...
import random # I import the necessary library
import time #This will import the module time to be able to wait
#chose = "" #Initializing variables
def computer(): #This function will get a rand value between 1-99 and depending on the number I'll select either "rock, paper o scissors"
for i in range(1): #Determines the amount of numbers that will be returned
rand_value = random.randint(1, 99) #Set the limits of the random library
if rand_value <= 33:
chose = "rock"
elif rand_value <= 66:
chose = "paper"
else:
chose = "scissors"
return chose #Gives back an answer with the computer's selection
def game(): #This function is the game perce
print
print "This is the rock, paper, scissors' game written by Jesus Bibieca." #Display msgs
print
user = raw_input("Choose rock, paper or scissors and type it to play: ")#Takes user's entry
selection = computer()#Look for a rand selection
if user == selection:#Here below I've set a way to determine who wins
print "You chose: ", user, " and the computer chose: ", selection
print "It was a tie."
elif user == "rock" and selection == "paper":
print "You chose: ", user, " and the computer chose: ", selection
print "You lost."
elif user == "rock" and selection == "scissors":
print "You chose: ", user, " and the computer chose: ", selection
print "You won!"
elif user == "paper" and selection == "rock":
print "You chose: ", user, " and the computer chose: ", selection
print "You won!"
elif user == "paper" and selection == "scissors":
print "You chose: ", user, " and the computer chose: ", selection
print "You lost."
elif user == "scissors" and selection == "rock":
print "You chose: ", user, " and the computer chose: ", selection
print "You lost."
elif user == "scissors" and selection == "paper":
print "You chose: ", user, " and the computer chose: ", selection
print "You won!"
else:
print
print "You chose: ", user, " and this is not a valid option."
time.sleep(3) #The game waits for 3 secs and then starts again.
play_again()
def play_again():
print
keep_play = raw_input("Do you want to play again? (Type yes or no) ")
if keep_play == "yes":
time.sleep(2)
game()
elif keep_play == "no":
print
print "Thank you for playing!"
time.sleep(2)
exit()
else:
print
print "This is not a valid option."
play_again()
game()#The game executes.
| true |
13c728affd7e5939a50aa5001c77f8bf25ee089c | FadilKarajic/fahrenheitToCelsius | /temp_converter.py | 653 | 4.4375 | 4 | #Program converts the temperature from Ferenheit to Celsius
def getInput():
#get input
tempInCAsString = input('Enter the temperature in Ferenheit: ')
tempInF = int( tempInCAsString )
return tempInF
def convertTemp(tempInF):
#temperature conversion formula
tempInC = (tempInF - 32) * 5/9
return tempInC
def main():
tempInF=getInput()
tempInC=convertTemp(tempInF)
print('The temperature in Celsius is: ', "%.1f" %tempInC, 'degrees')
#asks the user to perform 3 conversions
#for conversionCount in range( 3 ):
# doConversion()
if __name__ == "__main__":
main() | true |
273f798d759f25e69cfe21edcad3418d66ffd0aa | Victor094/edsaprojrecsort | /edsaprojrecsort/recursion.py | 1,020 | 4.46875 | 4 | def sum_array(array):
'''Return sum of all items in array'''
sum1 = 0
for item in array:
sum1 = sum1 + item # adding every item to sum1
return sum1 # returning total sum1
def fibonacci(number):
"""
Calculate nth term in fibonacci sequence
Args:
n (int): nth term in fibonacci sequence to calculate
Returns:
int: nth term of fibonacci sequence,
equal to sum of previous two terms
Examples:
>>> fibonacci(1)
1
>> fibonacci(2)
1
>> fibonacci(3)
2
"""
if number == 0:
return 0
if number == 1:
return 1
else :
return fibonacci(number - 1) + fibonacci(number - 2)
def factorial(n):
'''
Return n!
Example :
n! = 1*2*3*4....n
'''
if n == 0:
return 1
else:
return n * factorial(n-1)
def reverse(word):
'''
picking from last to first index
Return word in reverse
'''
return word[::-1]
| true |
c1ea1eede64d04257cd5ba8bde4aea1601044136 | Rekid46/Python-Games | /Calculator/app.py | 1,076 | 4.1875 | 4 | from art import logo
def add(a,b):
return(a+b)
def subtract(a,b):
return(a-b)
def multiply(a,b):
return(a*b)
def divide(a,b):
return(a/b)
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print(logo)
n1=float(input("Enter first number: "))
n2=float(input("Enter second number: "))
while True:
for symbol in operations:
print(symbol)
operation_symbol = input("Pick an operation: ")
calculation_function=operations[operation_symbol]
first_answer=calculation_function(n1,n2)
print(f"{n1}{operation_symbol}{n2}={first_answer}")
cont=input(f"type 'y' to continue with previous result{first_answer} or type 'n' to start fresh calculation and type 'q' to exit: ")
if cont=="y":
n1=first_answer
n2=float(input("Enter the next number: "))
elif cont=='n':
calculator()
elif cont=='q':
print("Thanks for using calculator.Have a good day! :-) ")
break
calculator()
| true |
838775b7700e92d22745528eb8a0d03135d44f55 | brandong1/python_textpro | /files.py | 1,485 | 4.28125 | 4 | myfile = open("fruits.txt")
content = myfile.read()
myfile.close() # Flush and close out the IO object
print(content)
##########
file = open("fruits.txt")
content = file.read()
file.close()
print(content[:90])
##########
def foo(character, filepath="fruits.txt"):
file = open(filepath)
content = file.read()
return content.count(character)
##########
with open("bear.txt") as file:
content = file.read()
with open("first.txt", "w") as file:
file.write(content[:90])
###########
# Append the text of bear1.txt to bear2.txt.
with open("bear1.txt") as file:
content = file.read()
with open("bear2.txt", "a") as file:
file.write(content)
############
# Modify the content of data.txt
with open("data.txt", "a+") as file:
file.seek(0)
content = file.read()
print(content)
file.seek(0)
file.write(content)
file.write(content)
#############
You can read an existing file with Python:
with open("file.txt") as file:
content = file.read()
You can create a new file with Python and write some text on it:
with open("file.txt", "w") as file:
content = file.write("Sample text")
You can append text to an existing file without overwriting it:
with open("file.txt", "a") as file:
content = file.write("More sample text")
You can both append and read a file with:
with open("file.txt", "a+") as file:
content = file.write("Even more sample text")
file.seek(0)
content = file.read() | true |
8e5033488a99f2c785a5d52e13745d4ab0910f61 | tanglan2009/Python-exercise | /classCar.py | 2,858 | 4.4375 | 4 | # Imagine we run a car dealership. We sell all types of vehicles,
# from motorcycles to trucks.We set ourselves apart from the competition
# by our prices. Specifically, how we determine the price of a vehicle on
# our lot: $5,000 x number of wheels a vehicle has. We love buying back our vehicles
# as well. We offer a flat rate - 10% of the miles driven on the vehicle. For trucks,
# that rate is $10,000. For cars, $8,000. For motorcycles, $4,000.
#If we wanted to create a sales system for our dealership using Object-oriented
# techniques, how would we do so? What would the objects be? We might have a Sale class,
# a Customer class, an Inventory class, and so forth, but we'd almost certainly have
# a Car, Truck, and Motorcycle class.
from abc import ABCMeta, abstractmethod
class Vehicle(object):
"""A vehicle for sale by Jeffco Car Dealership.
Attributes:
wheels: An integer representing the number of wheels the vehicle has.
miles: The integral number of miles driven on the vehicle.
make: The make of the vehicle as a string.
model: The model of the vehicle as a string.
year: The integral year the vehicle was built.
sold_on: The date the vehicle was sold.
"""
__metaclass__ = ABCMeta
base_sale_price = 0
wheels = 0
def __init__(self, miles, make, model, year, sold_on):
self.miles = miles
self.make = make
self.model = model
self.year = year
self.sold_on = sold_on
def sale_price(self):
"""Return the sale price for this vehicle as a float amount."""
if self.sold_on is not None:
return 0.0 # Already sold
return 5000.0 * self.wheels
def purchase_price(self):
"""Return the price for which we would pay to purchase the vehicle."""
if self.sold_on is None:
return 0.0 # Not yet sold
return self.base_sale_price - (.10 * self.miles)
@abstractmethod
def vehicle_type(self):
""""Return a string representing the type of vehicle this is."""
pass
class Car(Vehicle):
"""A car for sale by Jeffco Car Dealership."""
base_sale_price = 8000
wheels = 4
def vehicle_type(self):
""""Return a string representing the type of vehicle this is."""
return 'car'
class Truck(Vehicle):
"""A truck for sale by Jeffco Car Dealership."""
base_sale_price = 10000
wheels = 4
def vehicle_type(self):
""""Return a string representing the type of vehicle this is."""
return 'truck'
class Motorcycle(Vehicle):
"""A motorcycle for sale by Jeffco Car Dealership."""
base_sale_price = 4000
wheels = 2
def vehicle_type(self):
""""Return a string representing the type of vehicle this is."""
return 'motorcycle'
| true |
e8bab715fb8ff2303ff7d5eb444789393d298844 | cristianoandrad/ExerciciosPythonCursoEmVideo | /ex075.py | 768 | 4.3125 | 4 | '''Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
A) Quantas vezes apareceu o valor 9.
B) Em que posição foi digitado o primeiro valor 3.
C) Quais foram os números pares.'''
tupla = (int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite um ultimo número: ')))
print(f'Voce digitou os valores {tupla}.')
print(f'O número 9 apareceu {tupla.count(9)} vezes.')
if 3 in tupla:
print(f'O número 3 apareceu primeiro na posição {tupla.index(3)+1}.')
else:
print('O valor 3 não foi digitado.')
print('Os valores pares foram: ', end='')
for n in tupla:
if n % 2 == 0:
print(n, end=' ')
| false |
ca4270f470222f13e66ea1842074eb2cf0ba0806 | cristianoandrad/ExerciciosPythonCursoEmVideo | /ex014.py | 251 | 4.34375 | 4 | # Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
cel = float(input('Informe a temperatura em celsius: '))
print('A temperatura equivalente em Fahrenheit é {}ºF'.format((cel * 1.8)+32))
| false |
c259a0fb4637d7d3c208a8e08657b7584501e424 | Karlhsiao/py4kids | /homework/hw_30_pay_calc.py | 1,262 | 4.21875 | 4 | '''
Calculate weekly payment by working hours and hourly rate
'''
STANDARD_HOURS = 40
OVERTIME_FACTOR = 1.5
def process_user_input(working_hours, hourly_rate):
hrs = float(working_hours)
r = float(hourly_rate)
return hrs, r
def input_from_user():
#working hours in the week, ex. 40
working_hours = None
#the hourly rate per hour, ex. 10.5
hourly_rate = None
working_hours = input("What's your working hours?:")
hourly_rate = input("What's the hourly rate?:")
return working_hours, hourly_rate
def transform_payment(hrs, rate):
overtime = hrs - STANDARD_HOURS
overtime_hr = rate * OVERTIME_FACTOR
payment = None
if hrs > STANDARD_HOURS:
payment = (STANDARD_HOURS*rate)+(overtime*overtime_hr)
else:
payment = hrs*rate
return payment
def output_to_user(payment):
payment = str(payment)
print("Your payment will be: " + payment)
def test():
hrs = 40
rate = 10.5
payment = transform_payment(hrs, rate)
assert payment == 498.75, "Please check your code..."
if __name__ == "__main__":
hrs, rate = input_from_user()
hrs, rate = process_user_input(hrs, rate)
payment = transform_payment(hrs, rate)
output_to_user(payment)
| true |
a094eace179eb7883904a900bb4ec3587c580d2c | KonstantinKlepikov/all-python-ml-learning | /python_learning/class_attention.py | 1,427 | 4.15625 | 4 | # example of traps of class construction
"""Chenging of class attributes can have side effect
"""
class X:
a = 1
"""Chenging of modified attributes can have side effect to
"""
class C:
shared = []
def __init__(self):
self.perobj = []
"""Area of visibility in methods and classes
"""
def generate1():
class Spam: # Spam - name for local area of generate()
count = 1
def method(self):
print(Spam.count)
return Spam()
def generate2():
return Spam1()
class Spam1: # is in top level of module
count = 2
def method(self):
print(Spam1.count)
def generate3(label): # return class instead of exemplar
class Spam:
count = 3
def method(self):
print('{0}={1}'.format(label, Spam.count))
return Spam
if __name__ == "__main__":
I = X()
print(I.a)
print(X.a)
print('side effect')
X.a = 2
print(I.a)
J = X()
print(J.a) # and in that exemplar to
x = C()
y = C()
print(y.shared, y.perobj) # ([], [])
x.shared.append('spam') # is translated to class attr in C()
x.perobj.append('spam') # is actual only in class exemplar
print(x.shared, x.perobj) # (['spam'], ['spam'])
print(y.shared, y.perobj) # (['spam'], [])
print(C.shared) # ['spam]
generate1().method() # 1
generate2().method() # 2
a = generate3('WhoIAm')
a().method() # WhoIAm' = 3
| true |
4d1f40485e149b3a99a3266349f33b59956e9e41 | KonstantinKlepikov/all-python-ml-learning | /python_learning/super_example.py | 993 | 4.4375 | 4 | # example of super() usage
"""Traditional method of superclass calling
"""
class C:
def act(self):
print('spam')
class D(C):
def act(self):
C.act(self) # explicit usage of superclass name to give it to self
print('eggs')
class DSuper(C):
def act(self):
super().act() # link to superclass without self
print('eggs')
class A:
def act(self):
print('not spam')
class Trap1(C, A): # mixed class
def act(self):
super().act() # choice only C method!
class Trap2(A, C): # mixed class
def act(self):
super().act() # choice only A method!
class E(C, A): # transitive form
def act(self):
print('transitive:')
A.act(self)
C.act(self)
if __name__ == "__main__":
X = D()
X.act() # spam eggs
Y = DSuper()
Y.act() # spam eggs
Z1 = Trap1()
Z1.act() # spam
Z2 = Trap2()
Z2.act() # not spam
trans = E()
trans.act() # not spam spam | false |
0704f17a81bb58ccfb55885b3f05ab85da62f5f6 | himik-nainwal/PythonCodeFragments | /Search And Sort/BubbleSort Python.py | 270 | 4.15625 | 4 | def bubble_sort(array):
for i in range(len(array)):
for j in range(i,len(array)):
if array[j] < array[i]:
array[j], array[i] = array[i], array[j]
return array
print(bubble_sort([5,54,87,3,9,47,12,65,92,45,78,2])) | false |
8dfac5602f8b55eb4b850bf8f3b7c15ea7c3363b | merryta/alx-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 550 | 4.34375 | 4 | #!/usr/bin/python3
"""
This is the "0-add_integer" module.
add a and b and it can be int or floats
"""
def add_integer(a, b):
'''
add two number
Args:
a : int or float
b : int or float
Rueturn an int
'''
if not isinstance(a, int) and not isinstance(a, float):
raise TypeError("a must be integer")
if not isinstance(b, int) and not isinstance(b, float):
raise TypeError("b must be integer")
if type(a) is float:
a = int(a)
if type(b) is float:
b = int(b)
return a + b
| true |
3ad8001b48d6a98de48be16b061b2d64efd31315 | bagustris/python-intro | /code/dictionary.py | 245 | 4.125 | 4 | #! /usr/bin/env python3
dictionary = {'book' : 'buku',
'table' :'meja',
'chair' : 'kursi' }
for k in dictionary.keys():
print(k, "-->", dictionary[k])
for i in dictionary.items():
print(i)
print(i[0])
print(i[1])
| false |
b6f03023ab52a12b262e46960de3ff0b3c1986d9 | ras9841/practice | /sorting/sortMethods.py | 2,150 | 4.25 | 4 | def bubbleSort(lst):
"""
Time complexity: O(n^2)
Space complexity: O(1)
"""
size = len(lst)
for _ in range(size):
swapping = True
while swapping:
for i in range(size-1):
if lst[i] < lst[i+1]:
lst[i], lst[i+1] = lst[i+1], lst[i]
else:
swapping = False
return lst
def selectionSort(lst):
"""
Time complexity: O(n^2)
Space complexity: O(1)
"""
size = len(lst)
for i in range(size):
max_val = lst[i]
max_loc = i
for j in range(i+1,size):
if lst[j] > max_val:
max_loc = j
max_val = lst[j]
lst[i], lst[max_loc] = max_val, lst[i]
return lst
def mergeSort(lst):
"""
Time complexity: O(nlog(n))
Space complexity: Depends on type stored in list
"""
if len(lst) < 2:
return lst
mid = int(len(lst)/2)
left = mergeSort(lst[:mid])
right = mergeSort(lst[mid:])
return merge(left, right)
def merge(lst_a, lst_b):
"""
Helper function for mergeSort. Contains the merging logic.
"""
merged = []
size_a = len(lst_a)
size_b = len(lst_b)
a = b = 0
while a < size_a and b < size_b:
if lst_a[a] > lst_b[b]:
merged.append(lst_a[a])
a += 1
else:
merged.append(lst_b[b])
b += 1
while a < size_a:
merged.append(lst_a[a])
a += 1
while b < size_b:
merged.append(lst_b[b])
b += 1
return merged
def quickSort(lst):
"""
Time complexity: O(nlog(n)) av, O(n^2) worst
Space complexity: O(log(n))
Note: like mergeSort in the average case, but spacially constant.
"""
if len(lst) < 2:
return lst
pivot = lst[-1]
# Partitioning
q = 0
for i in range(len(lst)-1):
if lst[i] <= pivot:
lst[i], lst[q] = lst[q], lst[i]
q += 1
lst[-1], lst[q] = lst[q], pivot
left = lst[:q]
right = lst[q+1:]
return quickSort(left) + [pivot] + quickSort(right)
| false |
b8ba0f7e41dea4b26753cf931b2ad1fb67240a4f | Miguel-Caringal/CHCIProgrammingClub | /Challenge of the Week/week 1/easy/Miguel Caringal.py | 277 | 4.21875 | 4 | month= int(input())
day= int(input())
if month > 2:
print ('After')
else:
if month == 2:
if day == 18:
print ('Special')
elif day <18:
print ('Before')
else:
print ('After')
else:
print ('Before') | false |
a5a62e8a5f03096ad0ad03eb27d9da6e1864a6b5 | JesusSePe/Python | /recursivity/Exercises3.py | 1,503 | 4.28125 | 4 | """Exercise 1. Rus multiplication method."""
from math import trunc
from random import randint
def rus(num1, num2):
if num1 == 1:
print(num1, "\t\t", num2, "\t\t", num2)
return num2
elif num1 % 2 == 0:
print(num1, "\t\t", num2)
return rus(trunc(num1 / 2), num2 * 2)
else:
print(num1, "\t\t", num2, "\t\t", num2)
return num2 + rus(trunc(num1 / 2), num2 * 2)
# print("A\t\t", "B\t\t", "SUMS")
# print(rus(3000, 82))
"""Exercise 2. Mathematical curiosity."""
def curiosity(num):
if num == 11111111:
print(num**2)
return
else:
print(num**2)
return curiosity(num * 10 + 1)
# curiosity(1)
"""Exercise 3. Guess the number."""
def guess(num, min=0, max=1000, attempt=1):
user_guess = int(input("Which number do you think it is? "))
if num == user_guess:
print("CORRECT! You guessed the number at the ", attempt, "attempt")
return
else:
if min < user_guess < num:
print("The number is between", user_guess, "and", max)
return guess(num, user_guess, max, attempt+1)
elif num < user_guess < max:
print("The number is between", min, "and", user_guess)
return guess(num, min, user_guess, attempt+1)
else:
print("The number is between", min, "and", max)
return guess(num, min, max, attempt+1)
print("A random number between 0 and 1000 will be chosen.")
guess(randint(0, 1001))
| true |
237d9f3039570ac80821bfde409e8acdf2344c47 | lesenpai/project-euler | /task4.py | 738 | 4.1875 | 4 | """ Число-палиндром с обеих сторон (справа налево и слева направо) читается одинаково.
Самое большое число-палиндром, полученное умножением двух двузначных чисел – 9009 = 91 × 99.
Найдите самый большой палиндром, полученный умножением двух трехзначных чисел. """
def is_palindrome(n):
s = str(n)
return s == s[::-1]
max_palindrome = -1
for a in range(100, 999):
for b in range(100, 999):
x = a * b
if is_palindrome(x) and x > max_palindrome:
max_palindrome = x
print(max_palindrome)
| false |
502b41273a57a4d1ca29215e005d5763eb41e163 | jeromeslash83/My-First-Projects | /random_stuff/BMI_Calculator.py | 661 | 4.28125 | 4 | #BMI CALCULATOR
print("Welcome to Jerome's BMI Calculator!")
while True:
Name = input("What is your name? ")
Weight = input("What is your weight (in kgs)? ")
Height = input("What is your height(in m)?")
BMI = float(Weight) / (float(Height) * float(Height))
print("Your BMI is", BMI)
if BMI < 18.5:
print(Name, "You are underweight.")
elif BMI < 25:
print(Name, "You're normal.")
elif BMI < 30:
print(Name, "You're overweight.")
else:
print(Name, "You're obese.")
ans = input('continue? (y/n):')
if ans == 'n':
print('OK have a nice day!')
break
| false |
01dfc11678b81a19780e0a47f2b962301c155df5 | Markos9/Mi-primer-programa | /comer_helado.py | 972 | 4.25 | 4 |
apetece_helado_input = input("Te apetece un helado? (SI/NO): ").upper()
if apetece_helado_input == "SI":
apetece_helado = True
elif apetece_helado_input == "NO":
apetece_helado = False
print("Pues nada")
else:
print("Te he dicho que me digas si o no, no se que has dicho pero cuento como que no")
apetece_helado = False
tienes_dinero_input = input("Tienes dinero para un helado? (SI/NO): ").upper()
esta_el_senor_de_los_helados_input = input("Esta el senor de los helados? (SI/NO): ").upper()
esta_tu_tia_input = input("Estas con tu tia? (SI/NO): ").upper()
apetece_helado = apetece_helado_input == "SI"
tienes_dinero = tienes_dinero_input == "SI"
esta_tu_tia = esta_tu_tia_input == "SI"
puede_permitirselo = tienes_dinero or esta_tu_tia
esta_el_senor_de_los_helados = esta_el_senor_de_los_helados_input == "SI"
if apetece_helado and puede_permitirselo and esta_el_senor_de_los_helados:
print("Tomate tu helado")
else:
print("Pues nada")
| false |
d02faf79c21f33ace38aabe121dcffc7a213e457 | vivekmuralee/my_netops_repo | /learninglists.py | 1,069 | 4.34375 | 4 | my_list = [1,2,3]
print (my_list)
print (my_list[0])
print (my_list[1])
print (my_list[2])
#########################################################
print ('Appending to the lists')
my_list.append("four")
print(my_list)
######################################################
print ('Deleting List Elements')
del my_list[2]
print (my_list)
#######################################################
print ('Learning nested List')
nest_list= []
nest_list.append (123)
nest_list.append (22)
nest_list.append ('ntp')
nest_list.append ('ssh')
my_list.append(nest_list)
print (my_list)
#######################################################
print ('Manipulating Lists')
print(my_list[3])
print (my_list[3][2])
#print (my_list[0][1])
print (my_list[2][1])
###########################################################
print ('Slicing')
sliced = my_list[1:3]
print (sliced)
#############################################################
slice_me = "ip address"
sliced = slice_me[:2]
print (sliced)
#############################################################
| true |
92379a4874c8af8cc39ba72f79aeae7e0edb741c | RyanIsCoding2021/RyanIsCoding2021 | /getting_started2.py | 270 | 4.15625 | 4 |
if 3 + 3 == 6:
print ("3 + 3 = 6")
print("Hello!")
name = input('what is your name?')
print('Hello,', name)
x = 10
y = x * 73
print(y)
age = input("how old are you?")
if age > 6:
print("you can ride the rolercoaster!")
else:
print("you are too small!")
| true |
f9e1251d704a08dc1132f4d54fb5f46fb171766e | BjornChrisnach/Edx_IBM_Python_Basics_Data_Science | /objects_class_02.py | 2,998 | 4.59375 | 5 | #!/usr/bin/env python
# Import the library
import matplotlib.pyplot as plt
# %matplotlib inline
# Create a class Circle
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
# Method
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
plt.axis('scaled')
plt.show()
# Create an object RedCircle
RedCircle = Circle(10, 'red')
# Find out the methods can be used on the object RedCircle
dir(RedCircle)
# Print the object attribute radius
RedCircle.radius
# Print the object attribute color
RedCircle.color
# Set the object attribute radius
RedCircle.radius = 1
RedCircle.radius
# Call the method drawCircle
RedCircle.drawCircle()
# We can increase the radius of the circle by applying the method add_radius(). Let increases the
# radius by 2 and then by 5:
# Use method to change the object attribute radius
print('Radius of object:', RedCircle.radius)
RedCircle.add_radius(2)
print('Radius of object of after applying the method add_radius(2):', RedCircle.radius)
RedCircle.add_radius(5)
print('Radius of object of after applying the method add_radius(5):', RedCircle.radius)
# Create a blue circle with a given radius
BlueCircle = Circle(radius=100)
# Print the object attribute radius
print(BlueCircle.radius)
# Print the object attribute color
print(BlueCircle.color)
# Call the method drawCircle
BlueCircle.drawCircle()
# Create a new Rectangle class for creating a rectangle object
class Rectangle(object):
# Constructor
def __init__(self, width=2, height=3, color='r'):
self.height = height
self.width = width
self.color = color
# Method
def drawRectangle(self):
plt.gca().add_patch(plt.Rectangle((0, 0), self.width, self.height, fc=self.color))
plt.axis('scaled')
plt.show()
# Let’s create the object SkinnyBlueRectangle of type Rectangle. Its width will be 2 and height
# will be 3, and the color will be blue:
# Create a new object rectangle
SkinnyBlueRectangle = Rectangle(2, 10, 'blue')
# Print the object attribute height
print(SkinnyBlueRectangle.height)
# Print the object attribute width
print(SkinnyBlueRectangle.width)
# Print the object attribute color
print(SkinnyBlueRectangle.color)
# Use the drawRectangle method to draw the shape
SkinnyBlueRectangle.drawRectangle()
# Let’s create the object FatYellowRectangle of type Rectangle :
# Create a new object rectangle
FatYellowRectangle = Rectangle(20, 5, 'yellow')
# Print the object attribute height
print(FatYellowRectangle.height)
# Print the object attribute width
print(FatYellowRectangle.width)
# Print the object attribute color
print(FatYellowRectangle.color)
# Use the drawRectangle method to draw the shape
FatYellowRectangle.drawRectangle()
| true |
987a02de30705a5c911e4182c0e83a3e46baecb3 | littleninja/udacity-playground | /machine_learning_preassessment/count_words.py | 1,201 | 4.25 | 4 | """Count words."""
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# TODO: Count the number of occurences of each word in s
word_dict = {}
word_list = s.split(" ")
max_count = 1
max_word_list = []
top_n = []
for word in word_list:
if word in word_dict:
word_dict[word] += 1
max_count = max(max_count, word_dict[word])
else:
word_dict[word] = 1
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
for word in word_dict:
max_word_list.append((word, word_dict[word]))
max_word_list.sort(key=lambda item: item[0]) # Sort alphabetically first
max_word_list.sort(key=lambda item: item[1],reverse=True) # Sort numerically last
# TODO: Return the top n words as a list of tuples (<word>, <count>)
n = min(n, len(max_word_list))
top_n = max_word_list[0:n]
return top_n
def test_run():
"""Test count_words() with some inputs."""
print count_words("cat bat mat cat bat cat", 3)
print count_words("betty bought a bit of butter but the butter was bitter", 3)
if __name__ == '__main__':
test_run() | true |
857692c3bf179c775cb1416fc7d742dfbb254a39 | NCCA/Renderman | /common/Vec4.py | 1,551 | 4.125 | 4 | import math
################################################################################
# Simple Vector class
# x,y,z,w attributes for vector data
################################################################################
class Vec4:
# ctor to assign values
def __init__(self, x, y, z, w=1.0):
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.w = float(w)
# debug print function to print vector values
def __str__(self):
return "[", self.x, ",", self.y, ",", self.z, ",", self.w, "]"
# overloaded sub operator subtract (self - rhs) returns another vector
def __sub__(self, rhs):
return Vec4(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z, self.w)
# overloaded sub operator subtract (self - rhs) returns another vector
def __add__(self, rhs):
return Vec4(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z, self.w)
# Cross product of self with rhs returns another Vector
def cross(self, rhs):
return Vec4(
self.y * rhs.z - self.z * rhs.y, self.z * rhs.x - self.x * rhs.z, self.x * rhs.y - self.y * rhs.x, 0.0
)
# Normalize vector to unit length (acts on itself)
def normalize(self):
len = math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
if len != 0:
self.x /= len
self.y /= len
self.z /= len
# simple dot product of self and rhs value n
def dot(self, n):
return (self.x * n.x) + (self.y * n.y) + (self.z * n.z)
| true |
f6d6fce48a00f5af17044c4fafbcfef686ddd1f3 | nikdom769/test_py111 | /Tasks/a2_priority_queue.py | 1,534 | 4.21875 | 4 | """
Priority Queue
Queue priorities are from 0 to 5
"""
from typing import Any
memory_prior_queue = {}
def enqueue(elem: Any, priority: int = 0) -> None:
"""
Operation that add element to the end of the queue
:param elem: element to be added
:return: Nothing
"""
global memory_prior_queue
if priority in memory_prior_queue:
memory_prior_queue[priority].append(elem)
else:
memory_prior_queue[priority] = [elem]
return None
def dequeue() -> Any:
"""
Return element from the beginning of the queue. Should return None if not elements.
:return: dequeued element
"""
global memory_prior_queue
if memory_prior_queue:
priority_min = min(memory_prior_queue)
data = memory_prior_queue[priority_min].pop(0)
if not memory_prior_queue[priority_min]:
del memory_prior_queue[priority_min]
return data
else:
return None
def peek(ind: int = 0, priority: int = 0) -> Any:
"""
Allow you to see at the element in the queue without dequeuing it
:param ind: index of element (count from the beginning)
:return: peeked element
"""
global memory_prior_queue
return memory_prior_queue[priority][ind] if memory_prior_queue\
and memory_prior_queue[priority]\
and ind < len(memory_prior_queue[priority]) - 1 else None
def clear() -> None:
"""
Clear my queue
:return: None
"""
global memory_prior_queue
memory_prior_queue = {}
return None
| true |
1e415caf237f77e59e13218ab583efdb567f0570 | LordBars/python-tutorial | /python-tutorial/stringler-ve-methotları.py | 753 | 4.125 | 4 | ## String'ler
string = ' Merhaba, Dünya '
print("String'ler listedir. Elemanlara erişebilir ve değişterebilirsiniz")
print(string)
print("string[6]:", string[6])
print("len(string):", len(string))
print("Merhaba in string:", 'Merhaba' in string)
print("Merhaba not in string:", 'Merhaba' not in string)
print("string.upper():", string.upper())
print("string.lower():", string.lower())
print("string.strip():", string.strip())
print("string.split(','):", string.split('j'))
print("string.replace('Dünya', 'Mars'):", string.replace('Dünya', 'Mars'))
print("string + ' Ben Jüpiter':", string + "Ben Jüpiter")
form = """
İsim = {}
Yaş = {}
Şifre = {} """.format('Python', '30', '123')
print(".format() fonksiyonu ile bilgi doldurma:\n", form) | false |
2be9e85741dc8553d4f6accc9f6bfd4f9ad545d1 | jwex1000/Learning-Python | /learn_python_the_hard_way_ex/ex15_extra.py | 865 | 4.4375 | 4 | #!/usr/bin/env python
# this imports the argv module from the sys libaray
print "What is the name of the file you are looking for?"
filename = raw_input("> ")
#creates a variable txt and opens the variable passed into it from the argv module
txt = open (filename)
#Shows the user what the file name is
print "Here's your file %r:" % filename
#shows the actualy contents of the file by performing the read method on the txt variable
print txt.read()
txt.close()
print txt.closed
#asks the user to retype the file name and will see it again
print "I'll also ask you to type it again:"
#put whatever the user writes into the file_again variable
file_again = raw_input("> ")
#puts the open file from the file_again variable into the txt_again variable
txt_again = open (file_again)
#shows the user the contents of the file
print txt_again.read()
txt_again.close()
| true |
45667bc90b655d757017bc8701ad16ce5060822c | codymlewis/Euler | /Nine.py | 668 | 4.5625 | 5 | '''
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.
'''
def find_triplet_product():
a = 1
b = 1
c = 1000 - (a + b)
while a < c:
while c > 0:
if (a**2 + b**2) == c**2:
return a * b * c
b += 1
c -= 1
a += 1
b = a
c = 1000 - (a + b)
return -1
if __name__ == "__main__":
print(f"The product of the Pythagorean triplet fitting a + b + c = 1000 is {find_triplet_product()}")
| false |
3701a03acf60f25c3eb9037343f0fc99ccf82d0e | manaleee/python-foundations | /age_calculator.py | 764 | 4.3125 | 4 | from datetime import date
def check_birthdate(year1,month1,day1):
today = date.today()
if today.year < year1:
return False
if today.year > year1:
return True
def calculate_age(year1,month1,day1):
today = date.today()
#age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
age = today.year - year1 - ((today.month, today.day) < (month1, day1))
print (" you are ", age, " years old. " )
year = int(input('Enter year of birth: '))
month = int(input('Enter month of birth: '))
day = int(input('Enter day of birth: '))
if check_birthdate(year,month,day) == True:
calculate_age(year, month, day)
else:
print("The birthdate is invalid.")
| false |
66efbf4f5f6c20fe0a4a715e8f10bbf6d5690913 | JMCCMJ/CSCI-220-Introduction-to-Programming | /HW 1/usury.py | 1,750 | 4.34375 | 4 | ##
## Name: <Jan-Michael Carrington>
## <usury>.py
##
## Purpose: <This program calculates the priniple payments on a car or home
## purchase. It will tell exactly how much interest will be paid
## over the period of the loans. It also will tell the total payment.>
##
##
## Certification of Authenticity:
##
## I certify that this lab is entirely my own work.
##
##
## Input: <The principal amount, the length of the loan in months,
## and the interest rate.>
## Output: <The principal payment each month, amound paid over the life of the
## loan, and the total interest paid.>
"""
Program 1 Usury
Author: <Jan-Michael Carrington>
Purpose: Calculate the monthly payment, total amount paid, and total interest paid for a loan.
Inputs:
1.principal
2.months
3.interest rate
Outputs:
1.monthly payments
2.total payment
3.total interest paid
Authenticity:
I certify that this program is entirely my work.
"""
def main():
print('This program calculates the monthly payment, total amound paid, and total interest paid over the course of a loan.')
# Get inputs
principal = eval(input("Enter the loan amount: $"))
months = eval(input("Enter the length of the loan in months: "))
interest = eval(input('Enter the interest rate (ex. "4.3" for 4.3%) '))
# Calculate outputs
rate = interest / 1200
monthly_payment = (principal * (rate * (1 + rate)**months)) / ((1 + rate)**months - 1)
total_payment = monthly_payment * months
total_interest = total_payment - principal
# Print the outputs with text to explain what they are
print("The monthly payment is $", monthly_payment,sep="")
print("The total amount paid is $",total_payment,sep="")
print("The total interest paid is $",total_interest,sep="")
main()
| true |
0d359a3c30b12076205a4b030b7723ecf65b7ba0 | asiguqaCPT/Hangman_1 | /hangman.py | 1,137 | 4.1875 | 4 | #TIP: use random.randint to get a random word from the list
import random
def read_file(file_name):
"""
TODO: Step 1 - open file and read lines as words
"""
words = open(file_name,'r')
lines = words.readlines()
return lines
def select_random_word(words):
"""
TODO: Step 2 - select random word from list of file
"""
r_word_pos = random.randint(0,len(words)-1)
r_word = words[r_word_pos]
letter_pos = random.randint(0,len(r_word)-1)
letter = r_word[letter_pos]
word_prompt = r_word[:letter_pos] + '_' + r_word[letter_pos+1:]
print("Guess the word:",word_prompt)
return r_word
def get_user_input():
"""
TODO: Step 3 - get user input for answer
"""
guess = input("Guess the missing letter: ")
return guess
def run_game(file_name):
"""
This is the main game code. You can leave it as is and only implement steps 1 to 3 as indicated above.
"""
words = read_file(file_name)
word = select_random_word(words)
answer = get_user_input()
print('The word was: '+word)
if __name__ == "__main__":
run_game('short_words.txt')
| true |
4d94f7809e935cfcebf874d37163f49abf581bf4 | S-Oktay-Bicici/PYTHON-PROGRAMMING | /7-Metodlar-(Fonksiyonlar)/sqrt-karakök.py | 1,333 | 4.5625 | 5 | from math import sqrt
# Kullanıcıdan değer alınıyor
sayi = float(input("Sayı Giriniz: "))
# Karakök hesaplanarak kok değişkenine aktarılıyor
kok = sqrt(sayi) # kok değişkenine sqrt fonksiyonunun sonucu aktarılmış
print(sqrt(sayi))
# Sonuçlar yazdırılıyor
print(sayi," sayısının karekökü" "=", kok)
##################################################################################
"""
# Bu program sqrt() fonksiyonunun farklı kullanımlarını gösterir.
x = 16
# İstenilen sabit değerin karekökünün alınması
print("1 = >",sqrt(16.0))
# Değişkenin karekökünün alınmasını sağlar
print("2 = >",sqrt(x))
# sqrt() fonksiyonunun içerisinde işlem kullanımı
print("3 = >",sqrt(2 * x - 5))
# İşlem sonucu geri dönen değerin değişkene aktarılması
y = sqrt(x)
print("4 = >",y)
# İçerisinde işlem kullanılan sqrt() fonksiyonunun dönen değerinin işleme tabi tutulması
y = 2 * sqrt(x + 16) - 4
print("5 = >",y)
# İç içe sqrt() fonksiyonunun kullanılması
y = sqrt(sqrt(256.0))
print("6 = >",y)
print("7 = >",sqrt(int("45")))
"""
#########################################################################
"""
x = 2
print("x = 2....",x)
print("sqrt(x).....",sqrt(x))
print("x.....",x)
x = sqrt(x)
print("x = sqrt(x) .....x => ",x)
""" | false |
9b3f76d0f3659b1b5d9c4c1221213ea6fbbc2a5b | arloft/thinkpython-exercises | /python-thehardway-exercises/ex4.py | 892 | 4.34375 | 4 | my_name = "Aaron Arlof"
my_age = 40 # sigh...
my_height = 70 # inches
my_weight = 152 # about
my_eyes = 'blue'
my_teeth = 'mostly white'
my_hair = 'brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall" % my_height
print "He's %d pounds heavy" % my_weight
print "Actually, that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
# more examples to show the difference between %s (format as a string) and %r (format as the literal object)
print "This -> %r is what shows up when modulo+r is used in a string." % my_name
months = "\nJan\nFeb\nMar\nApr\nMay"
print "Here are the months (as a string): %s" % months
print "Here are the months (the literal object): %r" % months
| true |
c4d6ef81f598c2f0277bb734bfd90316be19043b | andrijana-kurtz/Udacity_Data_Structures_and_Algorithms | /project3/problem_5.py | 2,914 | 4.21875 | 4 | """
Building a Trie in Python
Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete features on mobile phones or web search.
Before we move into the autocomplete function we need to create a working trie for storing strings. We will create two classes:
A Trie class that contains the root node (empty string)
A TrieNode class that exposes the general functionality of the Trie, like inserting a word or finding the node which represents a prefix.
Give it a try by implementing the TrieNode and Trie classes below!
"""
class TrieNode(object):
def __init__(self):
self.is_word = False
self.children = {}
def suffixes(self):
suff_store = []
self._suffixes_helper('', suff_store, self)
return suff_store
def _suffixes_helper(self, suffix, store, pnode):
## Recursive function that collects the suffix for
## all complete words below this point
if self.is_word:
store.append(suffix)
for ck, node in self.children.items():
if self == pnode:
suffix = ''
newsuffix = suffix + ck
node._suffixes_helper(newsuffix, store, pnode)
return store
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
insert `word` to trie
"""
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_word = True
def find(self, prefix):
node = self.root
for c in prefix:
if c not in node.children:
return None
node = node.children[c]
return node
MyTrie = Trie()
wordList = [
"ant", "anthology", "antagonist", "antonym",
"fun", "function", "factory",
"trie", "trigger", "trigonometry", "tripod"
]
for word in wordList:
MyTrie.insert(word)
node = MyTrie.find('tr')
print(node.suffixes())
assert(node.suffixes() == ['ie', 'igger', 'igonometry', 'ipod'])
node = MyTrie.find('ant')
print(node.suffixes())
assert(node.suffixes() == ['', 'hology', 'agonist', 'onym'])
node = MyTrie.find('f')
print(node.suffixes())
assert(node.suffixes() == ['un', 'unction', 'actory'])
node = MyTrie.find('') #edge case empty input prefix, I would personally expect all available words
print(node.suffixes())
assert(node.suffixes() == ['ant', 'anthology', 'antagonist', 'antonym', 'fun', 'function', 'factory', 'trie', 'trigger', 'trigonometry', 'tripod'])
node = MyTrie.find('Slavko') #edge case non existing input prefix
assert(node == None)
| true |
8ec108d9e7689393dce6d610019da91cd693dfd7 | ottoman91/ds_algorithm | /merge_sort.py | 1,124 | 4.375 | 4 | def merge_sort(list_to_sort):
#base case: lists with fewer than 2 elements are sorted
if len(list_to_sort) < 2:
return list_to_sort
# step 1: divide the list in half
# we use integer division so we'll never get a "half index"
mid_index = len(list_to_sort) / 2
left = list_to_sort[:mid_index]
right = list_to_sort[mid_index:]
# step 2: sort each half
sorted_left = merge_sort(left)
sorted_right = merge_sort(right)
#step 3: merge the sorted halves
sorted_list = []
current_index_left = 0
current_index_right = 0
#sortedLeft's first element comes next
# if its less than sortedRight's first
# element or if sortedRight is exhausted
while len(sorted_list) < len(left) + len(right):
if((current_index_left < len(left))) and
(current_index_right == len(right) or
sorted_left[current_index_left] < sorted_right[current_index_right]):
sorted_list.append(sorted_left[current_index_left])
current_index_left += 1
else:
sorted_list.append(sorted_right[current_index_right])
current_index_right += 1
return sorted_list
| true |
d7a97cdf17638e92d14fab42dfce81e4ff9636fa | IagoRodrigues/PythonProjects | /Python3_oo2/modelo.py | 1,822 | 4.15625 | 4 | class Filme:
def __init__(self, nome, ano, duracao):
# Atributos privados são marcados usando __ no inicio do nome
self.__nome = nome.title()
self.ano = ano
self.duracao = duracao
self.__likes = 0
# Posso criar getters usando uma função com o mesmo nome do atributo
# e adicionar a notação @property
# assim quando fizer objeto.atributo ele chama o getter, não o atributo de fato
@property
def likes(self):
return self.__likes
def dar_like(self):
self.__likes += 1
@property
def nome(self):
return self.__nome
"""
Com essa sintaxe definimos o metodo nome como setter do atributo __nome
Quando fizermos:
>>>cliente.nome = "marco"
Por baixo dos panos o Python vai chamar esse método
"""
@nome.setter
def nome(self, nome):
self.__nome = nome
class Serie:
# Se tivermos um atributo de classe devemos fazer:
# tamanho_dos_ep = 40
def __init__(self, nome, ano, temporadas):
self.__nome = nome.title()
self.ano = ano
self.temporadas = temporadas
self.__likes = 0
def dar_like(self):
self.__likes += 1
@property
def likes(self):
return self.__likes
@property
def nome(self):
return self.__nome
"""
Na hora de usar:
__class__.tamanho_dos_ep
"""
vingadores = Filme('vingadores - guerra infinita', 2018, 160)
vingadores.dar_like()
vingadores.dar_like()
print(f'Nome: {vingadores.nome} - Ano: {vingadores.ano} - Duração: {vingadores.duracao} - Likes: {vingadores.likes}')
atlanta = Serie('atlanta', 2018, 2)
atlanta.dar_like()
print(f'Nome: {atlanta.nome} - Ano: {atlanta.ano} - Temporadas: {atlanta.temporadas} - Likes: {atlanta.likes}')
| false |
b4505d0b7b4b1b9a2bbaebbd49ca261054ef935b | DIdaniel/coding-training | /3-countLetters/demo.py | 275 | 4.125 | 4 | # -*- coding: utf-8 -*-
# 인풋 : string 넣는 input 만들기
# string function
# 아웃풋 : STRING has STRING.LENGTH characters
say = input('What is the input string? : ')
def smthString(say) :
print(say + ' has ' + str(len(say)) + ' characters' )
smthString(say) | false |
03dc6d2c4223efe10b69acd3cc6b8bbda5732fc8 | noltron000-coursework/data-structures | /source/recursion.py | 1,182 | 4.40625 | 4 | #!python
def factorial(n):
'''
factorial(n) returns the product of the integers 1 through n for n >= 0,
otherwise raises ValueError for n < 0 or non-integer n
'''
# check if n is negative or not an integer (invalid input)
if not isinstance(n, int) or n < 0:
raise ValueError(f'factorial is undefined for n = {n}')
# implement factorial_iterative and factorial_recursive below, then
# change this to call your implementation to verify it passes all tests
return factorial_iterative(n)
# return factorial_recursive(n)
def factorial_iterative(n):
# initialize total
total = 1
while n > 1:
# loop-multiply total by n
total *= n
# subtract multiplier (n) by one before looping again
n -= 1
else:
return total
def factorial_recursive(n):
# check if n is an integer larger than the base cases
if n > 1:
# call function recursively
return n * factorial_recursive(n - 1)
else:
return 1
def main():
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) == 1:
num = int(args[0])
result = factorial(num)
print(f'factorial({num}) => {result}')
else:
print(f'Usage: {sys.argv[0]} number')
if __name__ == '__main__':
main()
| true |
1f6878f1a62be6110158401c6e04d0c8d46a5d8b | noltron000-coursework/data-structures | /source/palindromes.py | 2,633 | 4.3125 | 4 | #!python
def is_palindrome(text):
'''
A string of characters is a palindrome if it reads the same forwards and
backwards, ignoring punctuation, whitespace, and letter casing.
'''
# implement is_palindrome_iterative and is_palindrome_recursive below, then
# change this to call your implementation to verify it passes all tests
assert isinstance(text, str), f'input is not a string: {text}'
# return is_palindrome_iterative(text)
return is_palindrome_recursive(text)
def is_palindrome_iterative(text):
'''
for each letter's index, check if [len-index-1] is equal
if its not, then its not a palindrome
'''
# lft & rgt represent index locations in the text
# lft character index mirrors rgt character index
lft = 0
rgt = len(text) - 1
# we go through the string at both ends,
# checking if its mirrored along the way
while lft < rgt:
# these while loops will skip non-alphabetical chars
# also, if lft==rgt, text[lft]==text[rgt], hence lft<rgt
while not text[lft].isalpha() and lft < rgt:
lft += 1
while not text[rgt].isalpha() and lft < rgt:
rgt -= 1
# nesting these while loops still avoids O(n^2)
# each time one of these while loops are hit...
# ...the parent while loop is hit one less time
# check if the letters are (not) symmetrical
if text[lft].lower() != text[rgt].lower():
return False
else:
# continue loop
lft += 1
rgt -= 1
else:
# if loop ends, this is a palindrome
return True
def is_palindrome_recursive(text, lft=None, rgt=None):
'''
for each letter's index, check if [len-index-1] is equal
if its not, then its not a palindrome
'''
# these can only be true on first run
if lft == None:
lft = 0
if rgt == None:
rgt = len(text) - 1
if text == '':
return True
# we go through the string at both ends,
# checking if its mirrored along the way
while lft < rgt and not text[lft].isalpha():
lft += 1
while lft < rgt and not text[rgt].isalpha():
rgt -= 1
# check if the letters are symmetrical
if text[lft].lower() != text[rgt].lower():
return False
elif lft >= rgt:
return True
else:
# continue loop
lft += 1
rgt -= 1
return is_palindrome_recursive(text,lft,rgt)
def main():
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) > 0:
for arg in args:
is_pal = is_palindrome(arg)
result = 'PASS' if is_pal else 'FAIL'
is_str = 'is' if is_pal else 'is not'
print(f'{result}: {repr(arg)} {is_str} a palindrome')
else:
print(f'Usage: {sys.argv[0]} string1 string2 ... stringN')
print(' checks if each argument given is a palindrome')
if __name__ == '__main__':
main()
| true |
ac8e6616fe97a418e310efd5feced4ffde77a8cd | themeliskalomoiros/bilota | /stacks.py | 1,696 | 4.46875 | 4 | class Stack:
"""An abstract data type that stores items in the order in which they were
added.
Items are added to and removed from the 'top' of the stack. (LIFO)"""
def __init__(self):
self.items = []
def push(self, item):
"""Accepts an item as a parameter and appends it to the end of the list.
Returns nothing.
The runtime for this method is O(1), or constant time, because appending
to the end of a list happens in constant time.
"""
self.items.append(item)
def pop(self):
"""Removes and returns the last item from the list, which is also the
top item of the Stack.
The runtime is constant time, because all it does is index to the last
item of the list (and returns it).
"""
if self.items:
return self.items.pop()
return None
def peek(self):
"""This method returns the last item in the list, which is also the item
at the top of the Stack.
The runtime is constant time, because indexing into a list is done in
constant time.
"""
if self.items:
return self.items[-1]
return None
def size(self):
"""Returns the length of the list that is representing the Stack.
This method runs in constant time because finding the length of a list
also happens in constant time.
"""
return len(self.items)
def is_empty(self):
"""This method returns a boolean value describing whethere or not the
Stack is empty.
Testing for equality happens in constant time.
"""
return self.items == []
| true |
994247baf36ffebae449b717429bd937ba770b60 | paolithiago/Python-Paoli | /GraficoLinhaValores_Mes(Mod3Sigmoidal).py | 607 | 4.3125 | 4 | #2. REVISÃO MODULO 3 - VISUALIZAÇÃO DE DADOS
import matplotlib.pyplot as plt # IMPORTA BIBLIOTECA MATPLOTLIB
data = ['set','ago','jul'] # CRIA UMA LISTA COM OS MESES
print(saldo_lista) # IMPRIME A LISTA COM OS TRES SALDOS(EX ANTERIOR)
print(data) # IMPRIME A LISTA DE DATA
plt.plot(data,saldo_lista) # IMPRIME O GRAFICO DE LINHA TENDO EIXO X A DATA E EIXO Y O SALDO_LISTA
plt.show() # COMANDO PARA EXIBIR O GRAFICO
| false |
4022fb87a259c9fd1300fd4981eb3bd23dce7c1f | 0ushany/learning | /python/python-crash-course/code/5_if/practice/7_fruit_like.py | 406 | 4.15625 | 4 | # 喜欢的水果
favorite_fruits = ['apple', 'banana', 'pear']
if 'apple' in favorite_fruits:
print("You really like bananas!")
if 'pineapple' in favorite_fruits:
print("You really like pineapple")
if 'banana' in favorite_fruits:
print("You really like banana")
if 'lemon' in favorite_fruits:
print("You really like lemon")
if 'pear' in favorite_fruits:
print("You really like pear")
| true |
500d2e4daea05e14d3cedad52e0fae2d1ca4fe92 | harjothkhara/computer-science | /Intro-Python-I/src/08_comprehensions.py | 1,847 | 4.75 | 5 | """
List comprehensions are one cool and unique feature of Python.
They essentially act as a terse and concise way of initializing
and populating a list given some expression that specifies how
the list should be populated.
Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
for more info regarding list comprehensions.
Comprehensions in Python. Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined.
List comprehensions are used for creating new lists from other iterables. As list comprehensions returns lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. ... Here, square brackets signifies that the output is a list
"""
# Write a list comprehension to produce the array [1, 2, 3, 4, 5]
y = [i for i in range(1, 6)]
print(y)
# Write a list comprehension to produce the cubes of the numbers 0-9:
# [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
# creates a new list containing the cubes of all values from range(10)
y = [i**3 for i in range(10)]
print(y)
# Write a list comprehension to produce the uppercase version of all the
# elements in array a. Hint: "foo".upper() is "FOO".
a = ["foo", "bar", "baz"]
y = [words.upper() for words in a]
print(y)
# Use a list comprehension to create a list containing only the _even_ elements
# the user entered into list x.
x = input("Enter comma-separated numbers: ").split(',')
# What do you need between the square brackets to make it work? used int() build in python method
# elements in x are strings, need to convert each to int before using any math operation
y = [elements for elements in x if int(elements) % 2 == 0]
print(y)
| true |
23d8562ec8a10caa237d4544bb07cfefbb6fcd7f | harjothkhara/computer-science | /Sprint-Challenge--Data-Structures-Python/names/binary_search_tree.py | 2,610 | 4.1875 | 4 |
class BinarySearchTree: # a single node is a tree
def __init__(self, value): # similar to LL/DLL
self.value = value # root at each given node
self.left = None # left side at each given node
self.right = None # right side at each given node
# Insert the given value into the tree
def insert(self, value):
# compare the root value to the new value being added
# if the value is less than the root, move left
if value < self.value:
# if no child on that side insert
if self.left is None:
# creating a new class instance
self.left = BinarySearchTree(value) # a single node is a tree
# else keep moving left and call insert method again (on left) and do the check again until no child, and you can insert value to the tree
else:
self.left.insert(value)
# if the value is greater than the root, move right
elif value >= self.value:
# if no child on that side insert
if self.right is None:
# creating a new class instance
self.right = BinarySearchTree(value) # a single node is a tree
# else keep moving right and call insert method again (on right) and do the check again until no child, and you can insert value to the tree
else:
self.right.insert(value)
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
# look at root and compare it to the target
# if the target is less than the current node value,
if target < self.value:
# move left, if value exists repeat
if self.left is not None:
# recurse left side until target is found
return self.left.contains(target)
else:
return False
# if target is greater than the current node value, move right and repeat
elif target > self.value:
# move right, if value exists repeat
if self.right is not None:
# recurse right side until target is found
return self.right.contains(target)
else:
return False
# if the target equals the value return True - basecase
elif target == self.value:
return True
bst = BinarySearchTree(1)
bst.insert(8)
bst.insert(5)
bst.insert(7)
bst.insert(6)
bst.insert(3)
bst.insert(4)
bst.insert(2)
# bst.in_order_print(print)
# bst.dft_print(print)
# bst.bft_print(print)
| true |
49e4c6e85a28647c59bd025e34ac9bae09b05fc8 | rtorzilli/Methods-for-Neutral-Particle-Transport | /PreFlight Quizzes/PF3/ProductFunction.py | 445 | 4.34375 | 4 | '''
Created on Oct 9, 2017
@author: Robert
'''
#===============================================================================
# (5 points) Define a function that returns the product (i.e. ) of an unknown set of
# numbers.
#===============================================================================
def mathProduct(xi):
total = 1
for i in xi:
total = total*i
return total
answer=mathProduct([3,2,5])
print(answer)
| true |
a8e5c4bc11d9a28b1ef139cbd0f3f6b7377e6780 | itsmedachan/yuri-python-workspace | /YuriPythonProject2/YuriPy2-6.py | 337 | 4.21875 | 4 | str_temperature = input("What is the temperature today? (celsius) : ")
temperature = int(str_temperature)
if temperature >= 27:
message = "It's hot today."
elif temperature >= 20:
message = "It's warm and pleasant today."
elif temperature >= 14:
message = "It's coolish today."
else:
message = "It's cold today."
print(message) | true |
423247af19d550fbf231b08b655c6d6287ff84e2 | itsmedachan/yuri-python-workspace | /YuriPythonProject5/YuriPy5-3.py | 590 | 4.125 | 4 | import math
class YuriPythonProject5no3:
def circle_area(self):
circumference_length = 2*math.pi*radius
circle_area = math.pi*radius*radius
return "円周は"+str(circumference_length)+"、面積は"+str(circle_area)+"です"
print('円の円周と面積を求めます')
radius = float(input('半径を入力してください: '))
circle = YuriPythonProject5no3()
circle.radius = radius
print(circle.circle_area())
# 円の円周と面積を求めます
# 半径を入力してください: 2
# 円周は12.566370614359172、面積は12.566370614359172です | false |
5079c30dbdb327661f2959b057a192e45fa20319 | itsmedachan/yuri-python-workspace | /YuriPythonProject2/YuriPy2-1.py | 242 | 4.15625 | 4 | str_score = input("Input your score: ")
score = int(str_score)
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is: ", grade) | true |
0b5d8f76a5767a6c913dce4b8107f4399cfd77b2 | louielolo/LeetCodeFMH | /BinTree/二叉树中结点和最大的二叉搜索树/largestBST.py | 2,281 | 4.25 | 4 | """
给你一棵以 root 为根的 二叉树 ,请你返回 任意 二叉搜索子树的最大键值和。
二叉搜索树的定义如下:
任意节点的左子树中的键值都 小于 此节点的键值。
任意节点的右子树中的键值都 大于 此节点的键值。
任意节点的左子树和右子树都是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-sum-bst-in-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.maxSum = 0
def is_BST(self,root: TreeNode):
if root.left and root.right is None:
return True
if root.left is not None:
return False
def findMax(self,root):
pass
def findMin(self,root):
pass
def getSum(self,root):
pass
def traverse(self,root: TreeNode):
"""前序遍历的位置,就是干活的位置,如果主函数不能递归,就写一个专门递归的方法来完成遍历功能"""
if root is None:
return
#只有左右子树均为BST,该root的树才可能为BST
if not self.is_BST(root.left) or not self.is_BST(root.right):
goto next
leftmax = self.findMax(root.left)
rightmin = self.findMin(root.right)
#如果root的val比左边小,比右边大,就不是BST
if root.val <= leftmax or root.val >= rightmin:
goto next
#如果条件都符合,开始计算BST的和
leftsum = self.getSum(root.left)
rightsum = self.getSum(root.right)
bstSum = leftsum + rightsum +root.val
self.maxSum = max(bstSum,self.maxSum)
"""递归的位置"""
next
self.traverse(root.left)
self.traverse(root.right)
return self.maxSum
def maxSumBST(self,root:TreeNode)->int:
self.maxSumBST(root.left)
self.maxSumBST(root.right)
if root.left and root.right is not None:
return max(root.left.val + root.right.val + root.val)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.