blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
8ab936ebb880310a33675c8faf9c325deba0d735 | TonyJenkins/python-workout | /06-pig-latin-sentence/pig_latin.py | 154 | 3.828125 | 4 | #!/usr/bin/env python3
def pig_latin(word):
if word[0] in 'aeiou':
return word + 'way'
else:
return word[1:] + word[0] + 'way'
|
e6b2fd430d1cfbcf71817cc0aea228da5c76517b | yeoeunhwang/python-works | /leetcode_problem/move_zeroes.py | 191 | 3.71875 | 4 | def move_zeroes(nums):
count = 0
for n in nums:
if n == 0:
nums.remove(0)
nums.append(0)
return nums
print(move_zeroes([1,0,2,3,0,4]))
|
c404d7892a14e457ca000f8f72b540ccb8d2f314 | hyelim-kim1028/lab-python | /LEC04/exception1.py | 2,139 | 3.90625 | 4 | """
error, exception: 프로그램 실행 중에 발생할 수 있는 오류
- exception 은 예외 (프로그램 실행 중 비정상적인 발생 -> 오류)
프로그램 실행중에 오류가 발생하면 해결 방법:
1) 오류가 발생한 코드 위치를 찾아서 오류가 발생하지 않도록 수정
2) 오류가 발생하더라도, 오류를 무시하고 프로그램이 실행될 수 있도록 프로그램을 작성
-> try 구문
"""
# Different types of errors
print(1)
# TYpical Error 1: nameerror: 변수나 함수등의 없는 이름을 사용하려고 할 때 ( ~ not defined)
#pritn(1)
n = int('1')
# n = int(input('정수 입력: '))
# when we run this code: the number received will be deemed as 'character string' for Python
# Por eso, debe poner int/float
# int(): 문자열 -> 정수, float(): 문자열 -> 실수
# 사용자가 키보드로 입력한 값들은 regardless of its type, they are all regarded as character strings
n = int('123')
print(n)
# PERO, n = int('123.') se occura un error: ValueError: invalid literal for int() with base 10: '123.'
# . 때문에 10 진수로 변환할 수 없다
# 코딩을 잘 하려면 에러 메시지 보는 연습을 잘 해야한다
numbers = [1,2,3]
#print(numbers[3])
# IndexError: list index out of range
# Index [0,(n-1)] -> numbers의 인덱스는 0,1,2 니까, 3은 out of range 가 맞다
# oracle 이나 R은 인덱스가 1 부터 시작하지만, 다른 언어들 C, java와 같은 아이들은 0부터 시작
#print('123' + 456)
# TypeError: can only concatenate str (not "int") to str
# '123' is a character, 456 is a number type; different types cannot be added
"""
n = 100
x = input()
하면 x 의 값은 character 이 되고, 그냥
n + x해버리면 그것도 type error 이 되어버린다
"""
print(123 / 0)
# ZeroDivisionError: division by zero
# 수학에서 0으로 나눌 수 없다 -> mathematically wrong
# 이것말고도 여러가지 다른 에러들이 발생할 수 있다. 발생 했을 때 가서 고친다 혹은 에러가 발생하더라도 실행될 수 있도록 한다
|
1d28e2e312043342856020926b0196cb5e8d0535 | venkateshpitta/python-exercism | /anagram/anagram.py | 199 | 3.765625 | 4 | from typing import List
def detect_anagrams(string: str, array: List[str]) -> List[str]:
return [x for x in array if x.lower() != string.lower() and sorted(x.lower()) == sorted(string.lower())]
|
3845f57d169ddefe7152a86b47545dabf77e7b0d | ryanfitch/Python_Mini_Projects | /Python-W3-Exercises/python-exercise37.py | 252 | 4.25 | 4 | # Write a Python program to display your details like name, age,
# address in three different lines.
name = input("Give me your name: ")
age = input("Give me your age: ")
address = input("Give me your address: ")
print(name)
print(age)
print(address)
|
9d7f5c5e56b17e1eec9d4aff5456cbf8259beb9b | glaubersabino/python-cursoemvideo | /world-02/exercice-055.py | 435 | 3.859375 | 4 | # Exercício 055
# Faça um programa que leia o peso de cinco pessoas.
# No final, mostre qual foi o maior e o menor peso lidos.
maior = 0
menor = 0
for c in range(0, 5):
peso = float(input('Qual o peso da pessoa {}? '.format(c + 1)))
if peso > maior:
maior = peso
if c == 0:
menor = peso
elif peso < menor:
menor = peso
print('O maior peso é {} e o menor peso é {}.'.format(maior, menor))
|
3be1451c533dc8121e909b7f40def217dcf7f4a6 | AishwaryaBhaskaran/261644_Daily-commits-Python | /str.py | 470 | 4.25 | 4 | #Write a python program to check the user input abbreviation.If the user enters "lol", print "laughing out loud".If the user enters "rofl", print "rolling on the floor laughing".If the user enters "lmk", print "let me know".If the user enters "smh", print "shaking my head"
str=input()
if str=="lol":
print("laughing out loud")
elif str=="rofl":
print("rolling on the floor laughing")
elif str=="lmk":
print("let me know")
else:
print("shaking my head")
|
e9fe4f39fbde4a99afa41aa24b8dc086374f4246 | Frankiee/leetcode | /graph_tree_dfs/backtracking/131_palindrome_partitioning.py | 976 | 4 | 4 | # [Backtracking]
# https://leetcode.com/problems/palindrome-partitioning/description/
# 131. Palindrome Partitioning
# History:
# 1.
# Feb 12, 2019
# 2.
# Dec 1, 2019
# Given a string s, partition s such that every substring of the partition
# is a palindrome.
#
# Return all possible palindrome partitioning of s.
#
# Example:
#
# Input: "aab"
# Output:
# [
# ["aa","b"],
# ["a","a","b"]
# ]
class Solution(object):
def is_palindrome(self, s):
return s == s[::-1]
def dfs(self, ret, s, start, prefix):
if start == len(s):
ret.append(prefix)
else:
for i in range(start + 1, len(s) + 1):
new_word = s[start:i]
if self.is_palindrome(new_word):
self.dfs(ret, s, i, prefix + [new_word])
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
ret = []
self.dfs(ret, s, 0, [])
return ret
|
27f371dcc889c5fd98e1554e238eb07e4a9e789e | bshankar/hackerrank | /src/strings/super_reduced_string.py | 540 | 3.71875 | 4 | # https://www.hackerrank.com/challenges/reduced-string/problem
def super_reduced_string(s):
s_list = list(s)
is_reduced = True
while is_reduced:
i = 0
is_reduced = False
while i < len(s_list) - 1:
if s_list[i] == s_list[i + 1]:
del s_list[i]
del s_list[i]
is_reduced = True
else:
i += 1
if s_list:
return "".join(s_list)
return "Empty String"
s = input().strip()
print(super_reduced_string(s))
|
e8914afce49f32ee9cda85de26036d1ff93dcdcb | vrushti-mody/Leetcode-Solutions | /Valid_Perfect_Square.py | 400 | 3.859375 | 4 | # Given a positive integer num, write a function which returns True if num is a perfect square else False.
# Follow up: Do not use any built-in library function such as sqrt.
class Solution:
def isPerfectSquare(self, num: int) -> bool:
num=num**0.5
print( num)
num=str(num)
if num[len(num)-1]=='0':
return True
else:
return False
|
962aa75fea71466930e04b124dcc696a65409d75 | AKondro/ITSE-1329-Python | /CC5/CC5-Ex11/code.py | 250 | 3.796875 | 4 | fhand= open("mbox-short.txt")
records = 0
for record in fhand:
if record.startswith("From "):
split_record = record.split()
print(split_record(1))
records += 1
print("There were",records,"lines in the file with From as the first word") |
f4ce6a373b70c3c56465564c46fa80e64a138529 | poojataksande9211/python_data | /python_tutorial/excercise/winning_random_guessing_game1.py | 551 | 3.9375 | 4 | # win_num=45
import random
win_num=random.randint(1,100)
guess=1
guess_num=input("enter a no between 1 to 100")
guess_num=int(guess_num)
game_over=False
while not game_over:
if guess_num == win_num:
print(f"YOU WIN,and you guess a no in {guess} times")
game_over=True
else:
if guess_num <win_num:
print("TOO LOW")
else:
print("TOO HHIG")
guess=guess+1
guess_num=int(input("AGAIN enter no")) #(no need to write both the statement in if else block )
|
fbe376a3ac1cf002051bb73614d2ea1f2347ccb6 | sakkugupta/python | /pattern-1.py | 192 | 3.953125 | 4 | '''for i in range (1,6):
for j in range(1,6):
print('*',end='\t')
print()'''
for i in range (1,6):
for j in range (5,0,-1):
print('*',end="\t")
print()
|
3877046cb608fbeeab852d02116bb28ef8ad8f75 | prcopt/Python-Course-May2021 | /S02Q02.py | 2,607 | 4.4375 | 4 | """
EXERCISE SET S02Q02
- Using the starting and ending values of your car’s odometer,
and the measure of fuel consumed,
calculate the number of stops one should make for refuelling
while travelling from Bangalore to Goa,
a distance of 560 kms.
2 methods are provided: calculation using math library and the other using basic operators.
"""
##### function to calculate mileage
def mileage(start,end,fuel):
return (end-start)/fuel
##### Function to calculate fuel consumption (Mileage) km/ltr for car
def get_fuel_consumption():
input_data = input("Key in Start and End values of Odometer Readings with comma separating the numbers:")
(x,y)=input_data.split(",")
start_value = int(x)
end_value = int(y)
if start_value >= 0 and end_value >= 0 and start_value < end_value:
fuel_consumed_in_ltr = float(input("Enter Fuel consumed in Liters:"))
if fuel_consumed_in_ltr > 0:
return mileage(start_value,end_value,fuel_consumed_in_ltr)
else:
print("There was no fuel to consume or quantity cannot be negetive!!")
else:
print("Give meaningful odometer readings seperated by comma!!")
##### Function to print results - Dash board
def result_board(fc,fr,tc,fs,stop):
print(" Fuel Consumption of Car :",fc ,"Kms/Ltr\n",
"Fuel required for journey:",fr ,"Ltrs\n",
"Tank Capacity :",tc ,"Ltrs\n",
"Fuel in tank at start :",fs ,"Ltrs\n",
"No of stops for refil :",stop)
return
###### Calculating fuel required for journey
fc = get_fuel_consumption()
dist_to_goa = 560
fuel_required_for_goa = dist_to_goa/ fc
tank_capacity = int(input("Enter the Fuel Tank Capacity in Liters as integer:"))
fuel_at_start = float(input("Enter Fuel in Tank in Liters at Start: "))
# calculation by using math function
print("\nMETHOD-1: BY USE OF MATH LIBRARY\n")
import math
no_of_stops_for_refils = math.ceil((fuel_required_for_goa - fuel_at_start)/tank_capacity)
result_board(fc,fuel_required_for_goa,tank_capacity,fuel_at_start,no_of_stops_for_refils)
# calculation by using remainder operator
print("\nMETHOD-2: BY USE OF REMAINDER OPERATOR\n")
if fuel_at_start < fuel_required_for_goa:
no_of_stops_for_refils = int((fuel_required_for_goa - fuel_at_start)/tank_capacity)
if (fuel_required_for_goa - fuel_at_start)%tank_capacity > 0 :
no_of_stops_for_refils += 1
result_board(fc,fuel_required_for_goa,tank_capacity,fuel_at_start,no_of_stops_for_refils)
|
52a286f663ed2b7a704bd80414b5b6c64516f6c2 | moliming0905/Python | /Spider/getBaiduTiebaInfo.py | 1,582 | 3.703125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import urllib
import urllib2
def loadPage(url,filename):
"""
作用:根据URL发送请求,获取服务器响应文件
url:需要爬取的url地址
filename:处理的文件名
"""
print "Download "+filename
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36"
}
request = urllib2.Request(url, headers = headers)
return urllib2.urlopen(request).read()
def writePage(html,filename):
"""
作用:将html内容写入到本地
html:服务器相应文件内容
"""
print "Saveing "+filename
with open(filename+".html",'w') as f:
f.write(html)
print "_"*30
def tiebaSpider(url,beginPage,endPage):
"""
作用: 贴吧爬虫调度器,负责组合处理每个页面的url
url:贴吧url的前部分
beginPage:起始页
endPage:结束页
"""
for page in range(beginPage,endPage+1):
pn = (page - 1 )*50
filename = str(pn)+"page"
fullurl = url + "&pn="+str(pn)
html = loadPage(fullurl,filename)
#print html
writePage(html,filename)
if __name__ == "__main__":
kw = raw_input("Enter the name of tieba :")
beginPage = int(raw_input("Enter start page number:"))
endPage = int(raw_input("Enter end page number:"))
url = "http://tieba.baidu.com/f?"
key = urllib.urlencode({"kw": kw})
fullurl = url + key
tiebaSpider(fullurl,beginPage,endPage)
|
b0ae29eb0766073101e56dc15b5bc208a04d47dc | oeeen/algorithm-practice | /boj/1110.py | 285 | 3.640625 | 4 | def func(n):
if (n < 10):
return n * 10 + n
else:
return (n%10) * 10 + (n//10 + n%10)%10
def main():
n = int(input())
current = func(n)
count = 1
while (current != n):
current = func(current)
count += 1
print (count)
main() |
f548eb1636d968bc0821c463aa9f82c40a6c78be | Batman001/leetcode_in_python | /dp/longest-common-sub-sequence.py | 715 | 3.71875 | 4 | # -*- coding:utf-8 -*-
def longest_common_sub_sequence(text1: str, text2: str) -> int:
"""
查找两个字符串的最长公共序列
:param text1: 字符串1
:param text2: 字符串2
:return: 最长公共序列的长度
"""
m = len(text1)
n = len(text2)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
if __name__ == "__main__":
str1 = "abcde"
str2 = "ace"
print(longest_common_sub_sequence(str1, str2))
|
cd21e72989f60548f6b3485aa6a86ef885e9876e | navyakanu/30-Days-Of-Code | /Day8/Solution.py | 442 | 3.859375 | 4 | n = int(input())
phone_book = {}
for i in range(0,n):
print("Enter the name and number to add to phone book in the format name number")
name, id = input().split()
phone_book[name] = id
while 1:
temp = ''
print("Enter the name to search number for")
name = input()
if name == temp:
break
if name in phone_book:
print("Found" + name + "=" + phone_book[name])
else:
print("Not found")
|
03e6ab07c9c80cc13ef3883f02c492ff6c4b700a | iamksir/studyEveryDay | /first/study_list.py | 919 | 3.96875 | 4 | #list一种有序的集合
classmates = ['zhangsan','lisi','wangwu']
print(classmates)
#用索引访问list中每一个位置的元素
print(classmates[0])
print(classmates[-2])
#超出索引报'indexError'
#print(classmates[4])
#用len()获取list元素的个数
a = len(classmates)
print(a)
#lisr是一个可变的有序表,可以用append()追加元素到末尾
classmates.append('zhouliu')
print(classmates)
#通insert()将元素插入到指定位置
classmates.insert(0,'wuer')
print(classmates)
#用pop()删除末尾的元素
classmates.pop()
print(classmates)
#用pop(索引)删除指定位置的元素
classmates.pop(0)
print(classmates)
#可通过执行赋值的方式替换对应索引位置的元素
classmates[0] = 'zhangyi'
print(classmates)
#list里面的数据可以不同
L = [123,12.0,'QWE']
print(L)
#list可以嵌套使用
s = ['a','b',['c','d'],'e']
print(s)
b = len(s)
print(b)
print(s[2][0]) |
93cdd20bada04e8c46cbc75b20499bbcfb5e4e3b | hemangandhi/derpspace | /pythons/divesh/8_queens.py | 817 | 3.546875 | 4 | def intersect(x1,y1,x2,y2):
return x1 == x2 or y1 == y2 or abs(x1 - x2) == abs(y1 - y2)
def solve_queens_h(curr_sol,ind):
if ind == len(curr_sol):
return curr_sol
while curr_sol[ind] < len(curr_sol):
if not any(intersect(ind,curr_sol[ind],i,curr_sol[i]) for i in range(ind)):
guess = solve_queens_h(curr_sol[:],ind + 1)
if guess:
return guess
curr_sol[ind] = curr_sol[ind] + 1
return False
def solve_queens(dim):
return solve_queens_h([0 for i in range(dim)],0)
def print_sol(sol):
if not sol:
print("No solution")
return
print('--')
for i in sol:
ln = ['#' for j in range(len(sol))]
ln[i] = 'Q'
print(''.join(ln))
if __name__ == "__main__":
print_sol(solve_queens(8))
|
1ab6a912927cd0f3254fdf875455c1638b3fa8e9 | Abhishek532/Python-Practice-Programs | /Table of a number using FOR.py | 138 | 4.15625 | 4 | a = int(input("Enter a number : "))
n = int(input("Enter number of multiples :"))
for i in range(1,n+1):
print(a,"x",i,"=",a*i)
|
e96d043129788ccd284059aebdd28d9369ae1ee4 | eewf/SoftUni-Fundamentals-Tasks | /Sum of chars.py | 142 | 3.96875 | 4 | n = int(input())
total = 0
for i in range(n):
symbol = input()
char = ord(symbol)
total += char
print(f"The sum equals: {total}")
|
ebc162d4ea3b927eaa416b6c108df42c230e2b5b | JackM400/Text_Adventure_Test | /TextAdventureTest.py | 2,953 | 3.953125 | 4 | import time
import random
def GameInrto():
print('You awake in a overgrown grotto')
time.sleep(2)
print('You dont know who you are.......')
time.sleep(3)
print('or how you got here')
time.sleep(1)
print('In front of you you see two caves.\n')
time.sleep(1)
print('In one cave lies a kind dragon that will share his treasure with you.\n'
'The other is greedy and will kill you if given the chance.\n')
def describeCaves():
print('To your left is a gash cut into the stone , a long cruel slice across the mountain side ,\n'
'no light penetrates it shadowy depths\n')
time.sleep(2)
print('To your right is a well built entrance of white stone ,\n'
'an arch protrudes from the mouth supported by elegant pillars of the same white stone \n'
'The rock itself seems to be giving off a kind of light,beckoning you\n')
def chooseCave():
print("Would you like to examine the caves?")
if input() == 'yes' or input() == 'y' or input() == 'Y' or input() == 'Yes':
describeCaves()
else:
print('which cave will you venture down? (Right 1 or Left 2)')
cave = ""
while cave != '1' and cave != '2':
print('which cave will you venture down? (Right 1 or Left 2)')
cave = input()
return cave
def checkCave(chooseCave):
print('You approach the cave of your choice......')
time.sleep(2)
print('The cave is dark , you feel an intense heat on your face.....')
time.sleep(2)
print('You see a glimmer out of the corner of your eye, do you examine?\n')
chestAnswer = ''
while chestAnswer != '1' and chestAnswer != '2':
print('yes or no (1 or 2)')
chestAnswer = input()
if chestAnswer == 1:
print('you open the chest and see that is is locked but a long wide dust patch leads away from it to a book '
'bound in chain')
time.sleep(1)
print('As you approach you hear a shrill voice in your ear ')
time.sleep(1)
print(' Night Fury.\n'
'Speed: Unknown.\n'
'Size: Unknown.\n'
'The unholy offspring of lightning and death itself. '
'Never engage this dragon. Your only chance:'
' Hide and pray it does not find you.')
time.sleep(1)
print('You walk for what seems like hours in the pitch black when suddenly you spot the beast across the cavern')
time.sleep(2)
friendlyCave = random.randint(1, 2)
if checkCave == str(friendlyCave):
print('The dragon is immense,your eyes can barely see for its slow rhythmic breaths,\n'
'its black injured wings curl around it to veil its eyes\n'
'great gashes and scars are littered throughout its scales\n')
time.sleep(1)
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
GameInrto()
caveNumber = chooseCave()
checkCave(caveNumber)
|
9e9957995bf4f555d0ee02970fcb46ac5aedf664 | heyhello89/openbigdata | /03_Data Science/1. Collection/1. CSV Handle/2.csv_read_row_column.py | 773 | 3.625 | 4 | import csv
def get_cvs_colInstance(col_name):
col_instance=[]
col_index=data[0].index(col_name)
for row in data[1:]:
col_instance.append(row[col_index])
return col_instance
def print_row(col_instance, type="int"):
if type == "int":
list(map(int, col_instance))
elif type == "float":
list(map(float, col_instance))
for row_element in col_instance:
print(row_element)
def print_clo(row_instance):
for row_element in row_instance:
print(row_element, end=' ')
with open('Demographic_Statistics_By_Zip_Code.csv', newline='') as infile:
data=list(csv.reader(infile))
# print_row(get_cvs_colInstance("COUNT FEMALE"))
print_row(get_cvs_colInstance("PERCENT FEMALE"), "float")
print_clo(data[2])
|
0c78fe580eb76e1bca6d4a6c41d505636075f820 | harsha1223/Data-Structure-using-python | /Graph/InsertionOperation/AddEdgeusingAdjacencyMatrix.py | 1,565 | 3.859375 | 4 | def add_node(v):
global node_count
if (v in nodes):
print("The node already present in the graph")
else:
node_count = node_count + 1
nodes.append(v)
for n in graph:
n.append(0)
temp = []
for i in range (node_count):
temp.append(0)
graph.append(temp)
#for undirected and unweighted graph:
def add_edge(v1,v2):
if(v1 not in nodes):
print(v1,"is not present in the graph")
elif(v2 not in nodes):
print(v2,"is not present in the graph")
else:
index1 = nodes.index(v1)
index2 = nodes.index(v2)
graph [index1][index2] = 1
graph [index2][index1] = 1
#for undirected and/ weighted graph:
def add_edge_cost(v1,v2,cost):
if(v1 not in nodes):
print(v1,"is not present in the graph")
elif(v2 not in nodes):
print(v2,"is not present in the graph")
else:
index1 = nodes.index(v1)
index2 = nodes.index(v2)
graph [index1][index2] = cost
graph [index2][index1] = cost
def print_graph():
for i in range(node_count):
for j in range(node_count):
print(format(graph[i][j],"<3"),end=" ")
print()
node_count = 0
nodes = []
graph = []
# print("Before adding nodes")
# print(nodes)
# print(graph)
# add_node("A")
# add_node("B")
# add_node("D")
# add_edge_cost("A" , "B" , 10)
# add_edge_cost("A" , "D" , 5)
# print("After adding nodes")
# print(nodes)
# print(graph)
# print_graph() |
f96084792065b949edbac63b313119f6d65d0ea7 | slavishtipkov/Python | /Fundamentals/collections/dics.py | 1,412 | 4.15625 | 4 |
#dict
# delimited by { and }
# key-value pairs comma separated
# corresponding keys and values joined by colon
# the KEY obj must be immutable
# the VALUE obj can be mutable
# dict() constructor accepts:
# iterable series of key-value 2-tuples
# keyword arguments - requires keys are valid Python identifiers
# Copying - d.copy() for copying dictionaries
# Or the other copying simply dict(d) constructor
# Extend a dictionary with update()
# Update replaces values corresponding to duplicate keys
# Iteration is over keys
# Get corresponding value with d[key] lookup
# Remember! Order is arbitrary!
# Use values() for an iterable view onto the series of values
# No efficient way to get the key corresponding to a value
# keys() method gives iterable view onto keys - not often needed
# Use items() for an iterable view onto the series of key-value tuples
# Use with tuple unpacking
# The 'in' and 'not in' operators work on the keys
# Use del keyword to remove by key
# keys myst be immutable
# values may be mutable
# The dictionary itself is mutable
# Python Standard Library 'pprint' module
# Be careful not to rebind the module reference!
# Knows how to pretty-print all built-in data structures, including => dict
d = {'article': 'asdfhfd', 'bob': 'worm'}
print(d['bob']) # 'worm' |
297f7aff8303af116c57510859338dfafd0a3c07 | damnmicrowave/cs102 | /homework01/vigenere.py | 1,635 | 3.734375 | 4 | def encrypt_vigenere(plaintext: str, key: str) -> str:
"""
>>> encrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> encrypt_vigenere("python", "a")
'python'
>>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
'LXFOPVEFRNHR'
"""
key = [key[i % len(key)] for i in range(len(plaintext))]
shifts = [ord(char) - 65 if ord(char) in range(65, 91) else ord(char) - 97 for char in key]
ciphertext = ''
for index, char in enumerate(plaintext):
code = ord(char)
if code in range(65, 91):
code += shifts[index] - 26 if code + shifts[index] > 90 else shifts[index]
elif code in range(97, 123):
code += shifts[index] - 26 if code + shifts[index] > 122 else shifts[index]
ciphertext += chr(code)
return ciphertext
def decrypt_vigenere(ciphertext: str, key: str) -> str:
"""
>>> decrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> decrypt_vigenere("python", "a")
'python'
>>> decrypt_vigenere("LXFOPVEFRNHR", "LEMON")
'ATTACKATDAWN'
"""
key = [key[i % len(key)] for i in range(len(ciphertext))]
shifts = [ord(char) - 65 if ord(char) in range(65, 91) else ord(char) - 97 for char in key]
plaintext = ''
for index, char in enumerate(ciphertext):
code = ord(char)
if code in range(65, 91):
code -= shifts[index] - 26 if code - shifts[index] < 65 else shifts[index]
elif code in range(97, 123):
code -= shifts[index] - 26 if code - shifts[index] < 97 else shifts[index]
plaintext += chr(code)
return plaintext
|
3dccc499d2dd2d6126caebdbbd4a7188437a8b6b | Robbie-Cook/COSC470-Assignment-1 | /decisionTree.py | 8,070 | 3.65625 | 4 | import numpy as np
"""
Class which defines a value,classification pair
"""
class Data:
def __init__(self, values, classification=None):
assert type(values) is list
self.values = values
self.classification = classification
def __str__(self):
return "Values: {}, Class: {}".format(self.values, self.classification)
"""
Defines a value point -- contains the attribute (the dimension to use) e.g.
Class
----------------------------------- ---------------
| 0.3 | 2.1 | 0 | | 0 |
----------------------------------- ---------------
^
|
1
and the value to value on e.g. 2.1
"""
class Split:
def __init__(self, attribute, value, score, left=None, right=None):
assert type(attribute) == int
assert type(value) == float
assert type(score) == float
self.attribute = attribute
self.value = value
self.score = score
self.left = left
self.right = right
def __str__(self):
if self.left == None or self.right == None:
return "Column {} < {} (Score: {})".format(self.attribute, self.value, self.score)
else:
return "Column {} < {} (Score: {}), Left: {}\n\n, Right: {}".format(
self.attribute, self.value, self.score, [str(i) for i in self.left], [str(i) for i in self.right])
"""
Make a new tree, which contains a split (criteria to split by), and two leaf branches
"""
class Tree:
def __init__(self, dataset):
self.left = None # the left tree
self.right = None # the right tree
self.dataset = dataset
self.classification = mostCommonClass(dataset) # Which class to assign
# the branch
self.split = None
def __str__(self):
attribute = ""
value = ""
if self.left != None or self.right != None:
attribute, value = self.split.attribute, self.split.value
return "attr({}) < {}:\n (Left:{}\n Right: {})\n\n".format(str(attribute),
str(value),
str(self.left),
str(self.right))
return ""
"""
Predict the class of a given set
data -- must be a Data object
"""
def predict(self, data):
if self.split == None:
return self.classification
if data.values[self.split.attribute] < self.split.value:
return self.left.predict(data)
else:
return self.right.predict(data)
"""
Main decision tree class to be used by outside methods
"""
class DecisionTree:
def __init__(self, max_depth):
self.max_depth = max_depth
"""
Fit the data using my implementation of Data instead of [X,y]
"""
def fit(self, dataset):
self.classifications = list(set([d.classification for d in dataset]))
global classifications
classifications = self.classifications
return self.growTree(dataset)
# """
# Fit the data using the standard (X,y) way by transferring the information
# to a list of Data objects
# X -- the inputs
# y -- the expected outputs
# """
# def fit(self, x, y):
# assert len(x) == len(y)
# dataset = [Data(list(x[i]), int(y[i])) for i in range(len(x))]
# return self.data_fit(dataset)
"""
Main recursive splitting method used with data_fit()
"""
def growTree(self, dataset, depth=0):
assert type(dataset) == list
m = Tree(dataset)
# Stopping conditions
# -- only one item or all items are of the same class
# -- max depth reached
if depth >= self.max_depth:
m.classification = mostCommonClass(dataset)
return m
if len(dataset) == 1:
m.classification = dataset[0].classification
return m
allSame = True
for item in dataset:
if item.classification != dataset[0].classification:
allSame = False
if allSame:
m.classification = dataset[0].classification
return m
# Assign the best split to the tree
m.split = self.find_split(dataset)
if len(m.split.left) == 0 or len(m.split.right) == 0:
print("Caution -- false split")
# Run the algorithm recursively
m.left = self.growTree(dataset = m.split.left, depth=depth+1)
m.right = self.growTree(dataset = m.split.right, depth=depth+1)
return m
"""
Get the proportion of a given class and dataset
(i.e. proportion(X,Y))
"""
def proportion(self, dataset, classification):
assert type(dataset) == list
assert type(classification) == int
if( len(dataset) == 0 ):
return 0
classes = [a.classification for a in dataset]
proportion = float(classes.count(classification)) / len(classes)
return proportion
"""
Get imparity of a dataset using the gini attribute
"""
def imparity(self, dataset):
assert type(dataset) == list
gini = 0
for c in self.classifications:
p_k = self.proportion(dataset, c)
gini += p_k * (1 - p_k)
return gini
"""
Finds the best value of data (currently from one attribute)
"""
def find_split(self, dataset):
best_split = Split(
attribute = 0,
value = float(np.inf),
score = float(np.inf))
attributes = range(len(dataset[0].values))
for attribute in attributes:
split_values = [data.values[attribute] for data in dataset]
for value in split_values: # The value to value the groups by
left, right = [],[] # Make the two groups of the current value
# Split dataset
for row in dataset:
if row.values[attribute] < value:
left.append(row)
else:
right.append(row)
# Get imparity of the two datasets and add them
score = self.imparity(left) + self.imparity(right)
# If neither left nor right is empty -- i.e. stops false splits
if len(left) > 0 and len(right) > 0:
# Update best score if its better
if score < best_split.score:
best_split = Split(
left = left,
right = right,
attribute=attribute,
value=float(value),
score=float(score))
# print("Best split found", str(best_split))
return best_split
"""
Process a file and return an appropriate data set
e.g. file1.txt (
1 1 1 0
2 1 0 0
...
)
-->
[
Data([1,1,1],0),
Data([2,1,0],0),
...
]
"""
def processFile(self, myfile):
myfile = open(myfile, 'r')
mylist = []
line = myfile.readline().split()
while len(line) != 0:
mylist.append(Data([float(a) for a in line[:-1]], int(line[-1])))
line = myfile.readline().split()
return mylist
"""
Find the most common classification in a dataset
"""
def mostCommonClass(dataset):
assert len(dataset) != 0
classInstances = [a.classification for a in dataset]
biggest = classifications[0]
score = 1
for c in classifications:
num = classInstances.count(c)
if num > score:
biggest = c
score = num
return biggest |
62a9bb7dd2e4f975819b93255d653186065d88b1 | Percygu/my_leetcode | /排序专题/堆排序/heap_sort.py | 2,522 | 3.796875 | 4 | '''
以小顶堆为例
0
1 2
3 4 5 6
7 8
'''
# 对数组里的第i个元素向下调整堆-----使堆为小顶堆
def heap_down(arr,size,i):
t = i
left,right = 2 * i +1, 2 * i +2 # 左右孩子的下标
if left < size and arr[left] < arr[t]: # 当前节点值比左孩子值大,t 变为做孩子下标 ,此时的t是左孩子和跟中的最小者
t = left
if right < size and arr[right] < arr[t]:
t = right # 此时的t是左孩子,右孩子还有根中的最小者
if i != t: # 存在不满足对情况的,需要做调整
arr[i],arr[t] = arr[t],arr[i] # 交换根和左右孩子中较小的那一个的值
heap_down(arr,size,t) # 以交换后的节点为根节点,递归向下调整
# 对数组里的第i个元素向上调整堆-----使堆为小顶堆
def heap_up(arr,i):
father = (i-1) // 2 # 当前节点的父节点的下标为(i-1) // 2,对顶元素即i为0不需要向上调整了
while (i-1) // 2 >= 0 and arr[(i-1) // 2] > arr[i]: # 父节点比当前节点大,不满足小顶堆,需要调整
arr[i],arr[(i-1) // 2] = arr[(i-1) // 2],arr[i] # 只需要交换当前节点和根节点即可,因为原来根节点一定比两个左右孩子小,此时这个孩子碧根节点还小,与根节点交换后,一定比另一个孩子小,不需要调整了
i = (i-1) // 2
# 堆排序
def heap_sort(arr):
n = len(arr)
# 1.从下往上构建堆,即从数组arr里的每个元素开始一次执行,从下表为1开始
for i in range(1,n):
heap_up(arr,i)
# 把最大元素放到最后面,调整堆
for i in range(n-1,0,-1): # n表示代派的序列的长度最后一个元素位置,若只有一个对顶元素,则不需要做调整了
# 2.交换,堆顶元素放到数组末尾
arr[0],arr[i] = arr[i],arr[0] # 把最小的元素放到了数组最后
# 3.剩下的元素向下调整
heap_down(arr,i,0) # 对数组前面的元素进行向下调整堆操作,调整完之后,对顶就是从整个数组的次小元素,i表示剩余待排元素的个数
return arr
if __name__ == "__main__":
arr = [1,4,6,3,7,9,0,2,5,8]
print(heap_sort(arr))
|
1c42e473e5ad2f19ec8dc7a1b3fc8a77143481db | jackharv7/Python-2 | /PyParagraph/paragraph.py | 1,028 | 3.703125 | 4 | import re
import os
path_to_dir = os.path.dirname(os.path.abspath(__file__))
file_descriptor = os.path.join(path_to_dir, "paragraph2.txt")
sent_count = -1
letter_count = 0
count = 0
with open(file_descriptor) as inputfile:
text = inputfile.read()
for letters in text:
if not letters.isalpha():
continue
for letter in letters:
letter_count +=1
split_words = re.split(" ", text)
for words in split_words:
count += 1
split_sent = re.split("(?<=[.!?])", text)
for sents in split_sent:
sent_count += 1
avg_sent_length = count/sent_count
avg_letter_count = letter_count/count
text_summary = """
Paragraph Analysis
--------------------------
Approximate Word Count: {count}
Approximate Sentence Count: {sent_count}
Average Letter Count: {avg_letter_count:.2f}
Average Sentence Length: {avg_sent_length:.2f}""".format(count=count,sent_count=sent_count,avg_sent_length=avg_sent_length,avg_letter_count=avg_letter_count)
print(text_summary) |
3f6e89e6379d8e22795a2593a94a46139e5dd0b9 | sam-kumar-sah/Leetcode-100- | /79s. Word_search.py | 1,430 | 3.953125 | 4 | //79. Word Search
'''
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent
cell, where "adjacent" cells are those horizontally or vertically
neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
'''
//code:
class solution(object):
def exist(self,board,word):
for y in range(len(board)):
for x in range(len(board[0])):
if(self.exit(board,word,x,y,0)):
return True
return False
#i=count
def exit(self,board,word,x,y,i):
if(len(word)==i):
return True
if( x<0 or x>=len(board[0]) or y<0 or y>=len(board)):
return False
if(board[y][x]!=word[i]):
return False
board[y][x]=board[y][x].swapcase()
isexit=(self.exit(board,word,x+1,y,i+1) or
self.exit(board,word,x,y+1,i+1) or
self.exit(board,word,x-1,y,i+1) or
self.exit(board,word,x,y-1,i+1) )
board[y][x]=board[y][x].swapcase()
return isexit
board=[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E'] ]
word="FDA"
ss=solution()
print(ss.exist(board,word))
|
38d2c3eba95e4a3cc4d626dad56710a01bdcdbd1 | ticotheps/practice_problems | /edabit/hard/remove_smallest/remove_smallest.py | 4,452 | 4.3125 | 4 | """
THE MUSEUM OF INCREDIBLY DULL THINGS
A museum wants to get rid of some exhibitions. Katya, the interior architect,
comes up with a plan to remove the most boring exhibitions. She gives them a
rating, and removes the one with the lowest rating. Just as she finishes rating
the exhibitions, she's called off to an important meeting. She asks you to write
a program that tells her the ratings of the items after the lowest one is
removed.
Create a function that takes a list of integers and removes the smallest value.
Examples:
- remove_smallest([1, 2, 3, 4, 5]) -> [2, 3, 4, 5]
- remove_smallest([5, 3, 2, 1, 4]) -> [5, 3, 2, 4]
- remove_smallest([2, 2, 1, 2, 1]) -> [2, 2, 2, 1]
Notes:
- Don't change the order of the left over items.
- If you get an empty list, return an empty list (i.e. - "[]" -> "[]").
- If there are multiple items with the same value, remove the item with the
lower index (i.e. - look at the 3rd example above).
"""
"""
The 4 Phases of the U.P.E.R. Problem-Solving Framework
***** U = UNDERSTAND Phase *****
- Objective:
- Write an algorithm that takes in a single input list of integers and removes the
smallest integer (or the duplicate of the smallest with the smallest index
if there are more than one), returning the revised list (without the
smallest integer included) as a single output.
- Expected Input(s):
- Number Of: 1
- Data Type(s): list
- Var Names: 'lst'
- Expected Output(s):
- Number Of: 1
- Data Type(s): list
- Var Names: 'new_lst'
Edge Cases & Constraints:
- Can the input list be empty?
- Yes, but you must return an empty list ("[]") if the given input is an
empty list.
- Can the numbers in the given input list be negative?
- No. These are "ratings" so they must be positive.
- Can the numbers in the given input list be floating point numbers?
- No. They must be whole integers
***** P = PLAN Phase *****
- Brute Force Solution
(1) Define a function that takes in a single input list of integers, "lst",
and returns a copy of that list where the smallest (or a copy of the
smallest) has been removed from that list.
(2) Declare a var, "new_lst", that will be returned as the output and
initialize it with an empty list.
(3) Declare another var, "smallest_rating", and initialize it with a value of 0.
(4) Use a "for" loop to iterate through the given input list.
(a) If the iterated-on element is less than the current value of
"smallest_rating", set the value of "smallest_rating" to be equal to the
value of that element.
(b) Else, do nothing.
(5) Declare another var, "removed_smallest", and initialize it with a value
of False (Boolean).
(6) Use another "for" loop to iterate through the given input list again.
(a) If the value of the iterated-on element is equal to the value of
"smallest_rating"...
(i) ...and if the value of "removed_smallest" equals False (Boolean),
then do NOT append the element's value to the "new_lst" list.
(ii) ...and if the value of "removed_smallest" equals True (Boolean),
then append the element's value to the "new_lst" list.
(b) If the value of the iterated-on element is NOT equal to the value of
"smallest_rating", then append the element to the "new_lst" list.
(7) Return the value of "new_lst".
***** E = EXECUTE Phase ***** (Please see below)
"""
def remove_smallest(lst):
new_lst = []
smallest_rating = None
for count,num in enumerate(lst):
if smallest_rating == None:
smallest_rating = num
if num < smallest_rating:
smallest_rating = num
removed_smallest = False
for count,num in enumerate(lst):
if num == smallest_rating:
if removed_smallest == False:
removed_smallest = True
else:
new_lst.append(num)
else:
new_lst.append(num)
return new_lst
"""
***** R = REFLECT/REFACTOR Phase *****
- Asymptotic Analysis:
- BRUTE FORCE SOLUTION:
- Time Complexity: O(n) -> "linear"
- Space Complexity: O(1) -> "constant"
"""
|
703d30f905866f41f09f8364b2415f64dc90c4da | calebperkins/algorithms | /algorithms/tries.py | 1,430 | 3.71875 | 4 | class TrieMap(object):
"""A map based on a prefix tree."""
def __init__(self):
self.chars = {}
self.value = None
def __contains__(self, key):
trie = self
for c in key:
if not c in trie.chars:
return False
trie = trie.chars[c]
return trie._terminates()
def __setitem__(self, key, value):
trie = self
for c in key:
if not c in trie.chars:
trie.chars[c] = TrieMap()
trie = trie.chars[c]
trie.value = value
def _terminates(self):
return self.value is not None
def by_prefix(self, prefix):
trie = self
for c in prefix:
if not c in trie.chars:
return []
trie = trie.chars[c]
s = [trie]
while s:
t = s.pop()
if t._terminates():
yield t.value
for n in t.chars.values():
s.append(n)
def __getitem__(self, key):
trie = self
for c in key:
trie = trie.chars[c]
return trie.value
def __repr__(self):
return repr(self.chars)
class TrieSet(object):
"""A set interface over a TrieMap."""
def __init__(self):
self.trie = TrieMap()
def __contains__(self, x):
return x in self.trie
def add(self, item):
self.trie[item] = item
|
865a8712c325a49be0b61c568a1f9a339844adbf | xxxxgrace/COMP1531-19T3 | /Labs/lab08/19T3-cs1531-lab08/encapsulate.py | 1,056 | 4.15625 | 4 | # Author: @abara15 (GitHub)
# I added functions that get the name and birth year because we don't want to directly access self.name and self.birth_year.
# Also imported datetime to get the current year and find the correct age.
import datetime
class Student:
def __init__(self, firstName, lastName, birth_year):
self.name = firstName + " " + lastName
self.birth_year = birth_year
def get_name(self):
return self.name
def get_birth_year(self):
return self.birth_year
if __name__ == '__main__':
s = Student("Rob", "Everest", 1961)
years_old = datetime.datetime.now().year - s.get_birth_year()
print(f"{s.get_name()} is {years_old} years old")
# class Student:
# def __init__(self, firstName, lastName, birth_year):
# self.name = firstName + " " + lastName
# self.birth_year = birth_year
# if __name__ == '__main__':
# s = Student("Rob", "Everest", 1961)
# years_old = 2019 - s.birth_year
# print(f"{s.name} is {years_old} old")
|
898005b5a09860c2ee9f8dfa021620f80c8d66e5 | PanPapag/A-Complete-Python-Guide-For-Beginners | /Python_Basics/Programming_in_Python/update_variables.py | 208 | 4.09375 | 4 | x = 5 # initialize x
print(x)
x = x + 1 # update x
print(x)
x += 2 # increment x by 2 (same as x = x + 2)
print(x)
x -= 1 # decrement x by 1 (same as x = x - 13)
print(x)
|
f533326c5ccd902cc0ee60e1082384cc87e23834 | Risauce/Pre2015Code | /CSCI 127/Practicum Stuff/Practicum 1/william-roberts.py | 678 | 3.734375 | 4 | import statistics
theList = [1,2]
print(str(statistics.median(theList)))
print(str(statistics.median_low(theList)))
charList = ["You", "may", "say", "I'm", "a", "dreamer"]
def count_characters(theList):
count = 0
for i in theList:
for ch in i:
count +=1
return count
print(count_characters(charList))
def my_reverse(theList):
newList = []
for i in theList:
newList.insert(0, i)
return newList
print(my_reverse(charList))
def create_file(fileName, num):
output = open(fileName, "w")
for i in range(num):
output.write(str(i + 1) + "\n")
create_file("jbd.txt", 5)
|
25eb17bc02f6ef500d3418de6bdebeeed823d210 | NeilWangziyu/Leetcode_py | /permution.py | 718 | 3.78125 | 4 | def permute(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def swap(i, j, nums):
x = nums.copy()
tem = x[i]
x[i] = x[j]
x[j] = tem
return x
res = [nums]
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
print(i, j)
if i==0:
res.append(swap(i, j, nums))
else:
tem = []
for each in res:
print("each", each)
if j!=i+1:
tem.append(swap(i, j, each))
res = res + tem
print("res",res)
res.sort()
return res
print(permute([1,2,3,4])) |
f4ac2a2339195fe99bc3dcd4ebfa01417638f51d | AdamZhouSE/pythonHomework | /Code/CodeRecords/2609/58585/318980.py | 162 | 3.703125 | 4 | a=int(input())
b=input()
c=input()
if a==3 and b=='6 2' and c=='1 2 1 3 4 2':
print(4)
print(10)
print(1)
else:
print(a)
print(b)
print(c) |
afd7c8c1d27f0b954c7f29812e2a6bca563bd3a0 | ecedavis/CodingChallenges | /src/day18.py | 484 | 3.875 | 4 | from collections import deque
class Solution:
# Write your code here
def __init__(self):
self.q=deque()
self.s=[]
def pushCharacter(self, ch):
#stack
self.s.append(ch)
def enqueueCharacter(self, ch):
#queue
self.q.append(ch)
def popCharacter(self):
#stack
return self.s.pop()
def dequeueCharacter(self):
#queue
return self.q.popleft()
|
1bdc7697c49876c818fb384f0995e86fd91d2b0b | udhayprakash/PythonMaterial | /python3/11_File_Operations/04_zipping_files/b_tar_files/a_writing_tar_files.py | 651 | 3.703125 | 4 | """
Purpose: Working with tar files
"""
import os
import tarfile
os.makedirs("files", exist_ok=True)
os.chdir("files")
# creating files
open("fileOne.txt", "w").write("This is first line")
open("fileTwo.txt", "w").write("This is second line")
open("fileThree.txt", "w").write("This is third line")
# Creating new archives
with tarfile.open("tarFileOne.tar", mode="w") as tF:
tF.add("fileOne.txt")
tF.add("fileTwo.txt")
# Appending to existing archive
with tarfile.open("tarFileOne.tar", mode="a") as tF:
tF.add("fileThree.txt")
# deleting existing files
os.remove("fileOne.txt")
os.remove("fileTwo.txt")
os.remove("fileThree.txt")
|
99bf7f8a9843c586fb247feb827a3937f413fa34 | Boot-Camp-Coding-Test/Tips | /[노태윤]/Python Tips/Counter.py | 862 | 3.71875 | 4 | # Counter
from collections import Counter
# element의 갯수를 dictionary 형태로 반환
a = [1,1,2,3,2,1,2,3,4,5,2,3,3]
b = [4,5,3,1,2,3,2,4,5,3,1,6,1]
a = Counter(a)
b = Counter(b)
print(a) # Counter({2: 4, 3: 4, 1: 3, 4: 1, 5: 1})
print(b) # Counter({3: 3, 1: 3, 4: 2, 5: 2, 2: 2, 6: 1})
# dictionary 형태이므로 python set operation 가능
print(a+b) # 갯수 더하기 : Counter({3: 7, 1: 6, 2: 6, 4: 3, 5: 3, 6: 1})
print(a-b) # a-b : Counter({2: 2, 3: 1})
print(b-a) # b-a : Counter({4: 1, 5: 1, 6: 1})
print(a|b) # a b 합집합 (갯수 더 많은 게 반환되는 듯) : Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 2, 6: 1})
print(a&b) # a b 교집합 : Counter({1: 3, 3: 3, 2: 2, 4: 1, 5: 1})
print(a^b) # TypeError 남.. 왜 그런진 아직 모르겠음
# set within list 형태로 바꿔보기
print(list((a-b).items())) # [(2, 2), (3, 1)]
|
06f2c277588b436488ed92345f58e82ddf15d1bd | erjan/coding_exercises | /itresume/Разница между произведением и суммой цифр.py | 655 | 3.890625 | 4 |
'''
Дано целое число n. Найти разницу
между произведение и суммой цифр в записи числа n.
'''
class Answer:
def subtractProductAndSum(self, n):
m = list(str(n))
m = [int(i) for i in m]
t = 1
for i in m:
t = t*i
s = sum(m)
return t - s
-----------------------------------------------------------------------
from functools import reduce
import operator
class Answer:
def subtractProductAndSum(self, n):
A = list(map(int, str(n)))
return reduce(operator.mul, A) - sum(A)
|
e7a51034ec0edcfd1ae37c07b8bef855c5694d5f | CircularWorld/Python_exercise | /month_01/day_06/homework_06/homework_06.py | 567 | 3.9375 | 4 | '''
6. 将列表中整数的十位不是3和7和8的数字存入另外一个列表
list03 = [135, 63, 227, 675, 470, 733, 3127]
结果:[63, 227, 3127]
提示:将数字转换为字符串进行处理
'''
list03 = [135, 63, 227, 675, 470, 733, 3127]
# for i in range(len(list03)):
# list03[i] = str(list03[i])
list03 = [str(list03[i]) for i in range(len(list03))]
print(list03)
list_result = [int(item) for item in list03 if item[-2] not in '378']
# for item in list03:
# if item[-2] not in '378':
# list_result.append(item)
print(list_result) |
ccba60662c36d5bb9ab97fc048412b75e213afa6 | ATrui/Projects | /Arithmetic_arranger/arithmetic_arranger.py | 1,203 | 3.734375 | 4 | def arithmetic_arranger(problems, solution=False):
if len(problems) > 5:
return "Error: Too many problems."
operators = ["+", "-"]
line_1 = ""
line_2 = ""
line_3 = ""
line_4 = ""
for i, problem in enumerate(problems):
n1, op, n2 = problem.split(" ")
# Check for errors
if op not in operators:
return "Error: Operator must be '+' or '-'."
if not (n1.isdigit() and n2.isdigit()):
return "Error: Numbers must only contain digits."
if len(n1) > 4 or len(n2) > 4:
return "Error: Numbers cannot be more than four digits."
if op == "+":
result = int(n1) + int(n2)
else:
result = int(n1) - int(n2)
space = max(len(n1), len(n2))
line_1 = line_1 + n1.rjust(space+2)
line_2 = line_2 + op + n2.rjust(space+1)
line_3 = line_3 + "".rjust(space+2, "-")
line_4 = line_4 + str(result).rjust(space+2)
if i < len(problems) - 1:
line_1 += " "
line_2 += " "
line_3 += " "
line_4 += " "
if solution:
arranged_problems = line_1 + "\n" + line_2 + "\n" + line_3 + "\n" + line_4
else:
arranged_problems = line_1 + "\n" + line_2 + "\n" + line_3
return arranged_problems |
a4907c94a7280d1a6898aa6afac8e080c5300dc6 | jinurajan/Datastructures | /LeetCode/stack_and_queue/perfect_squares.py | 1,019 | 3.734375 | 4 | """
Perfect Squares
Given an integer n, return the least number of perfect square numbers that sum to n.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
Constraints:
1 <= n <= 104
"""
class Solution:
def numSquares(self, n: int) -> int:
squares = [i * i for i in range(1, int(n ** 0.5) + 1)]
level = 0
q = {n}
while q:
level += 1
next_queue = set()
for rem in q:
for sq in squares:
if rem == sq:
return level
elif rem < sq:
break
else:
next_queue.add(rem - sq)
q = next_queue
return level
|
a78afc2f159b596f1e0e17cc27008e11751319e7 | ScrappyCocco/TheColonistsItalian | /validator/main.py | 574 | 3.703125 | 4 | #!/usr/bin/env python3
import sys
from CSVValidator import CSVValidator
print("Starting script...")
if len(sys.argv) > 2:
print("Passed more than 1 arguments! You must pass only the filename! "
"(if necessary pass it as \"filename\" with quotes")
elif len(sys.argv) == 2:
if sys.argv[1].endswith(".csv"):
validator = CSVValidator()
validator.process_file(sys.argv[1])
else:
print("You passed a filename without the .csv extension!")
else:
print("Passed 0 arguments! You must pass the filename!")
print("Script end...")
|
2942eac4521b7c77cae4afe56647faa44531efb3 | SilentWraith101/course-work | /lesson 03/capitalize points and name.py | 1,160 | 3.828125 | 4 | #input
firstname = str(input("Enter your first name: "))
lastname = str(input("Enter your last name: "))
position = str(input("Enter the position you finished in words: "))
points = 0
prizemoney = 0
#checking thier position and giving them the correct amount of points
if position.lower() == 'first':
print("you have gained 5 points!")
points = points + 5
if position.lower() == 'second':
print("you have gained 3 points!")
points = points + 3
if position.lower() == 'third':
print("you have gained 1 points!")
points = points + 1
if position.lower() == 'first':
points = prizemoney = prizemoney + 10
if position.lower() == 'second':
points = prizemoney = prizemoney + 7
if position.lower() == 'third':
points = prizemoney = prizemoney + 4
if position.lower() == 'fourth':
points = prizemoney = prizemoney + 3
if position.lower() == 'fith':
points = prizemoney = prizemoney + 2
if position.lower() == 'sixth':
points = prizemoney = prizemoney + 1
#output
print (firstname.capitalize(), lastname.capitalize())
print ("You have also won ",points,"points")
print ("You have also won £",prizemoney)
|
54c836cd916772ce56f7332d5409be1c646974b4 | foshay/cs325 | /hw1/qsort.py | 670 | 3.765625 | 4 | def sort(a):
if a == []:
return []
else:
pivot = a[0]
left = [x for x in a if x < pivot]
right = [x for x in a[1:] if x >= pivot]
return [sort(left)] + [pivot] + [sort(right)]
def sorted(t):
if t == []:
return []
else:
return sorted(t[0]) + [t[1]] + sorted(t[2])
return
def search(t, x):
if _search(t, x):
return True
else:
return False
def insert(t, x):
q = _search(t, x)
print(id(t)-id(_search(t,x)))
return
def _search(t, x):
if t == []:
return t
if t[1] == x:
return t
else:
return _search(t[0], x) + _search(t[2], x)
|
7db7db628f827b981386467b07d320b68977f555 | janishsiroya/Janish_Basics_Python | /src/google-python-exercises/8.jpg/datastruc.py | 1,604 | 3.875 | 4 | #list*********************************************************************
shoplist = ['apple','banana','flower','carrot']
shop = ['ha']
print shop
print shoplist
print len(shoplist)
shoplist.append('berry')
print shoplist
print 'the items are'
for i in shoplist:
print i
a = shoplist[0]
del shoplist[0]
print shoplist
print a
#tuple***********************************************************************
zoo = ('lion','tiger','cat','dog','rat')
print zoo
print len(zoo)
new_zoo = ('spider','horse', zoo)
print new_zoo
print (len(new_zoo)-1 + len(new_zoo[2]))
zoo1 = ('janish',)
print zoo1
#Dictionary*******************************************************************
ab = {'1':'janish','2':'john','3':'rahul'}
print ab
print ab['2']
ab['4'] = 'jessica'
print ab
del ab['1']
print ab
print ('there are {} contacts in dict'.format(len(ab)))
for a,b in ab.items():
print a,b
print ('contact {} at {}'.format(a,b))
if '1' in ab:
print 'found'
else:
print 'not found'
#Sequence*************************************************************************
#slicing
a = 'janish'
print a[1:5]
print a[::2]
print a[-3:-1]
b = ['jan','feb','march']
print b[1:2]
#Sets************************************************************
s = set(['a','b','c'])
print s
print 'a' in s
new_s = s.copy()
print new_s
new_s.add('d')
print new_s
print s & new_s
print new_s.issuperset(s)
print s.issubset(new_s)
#References***************************************************************
li = ['j','h','k','l']
a = li
print a
print li
del a[1]
print a
print li
b = li[:]
print b
del b [2]
print b
print li
|
791626b2f47a9663025ff40b2667cd262864c462 | VSerpak/AIND | /AIND-Sudoku-reviewed/Tests/solution_1.py | 8,352 | 3.6875 | 4 |
# coding: utf-8
# In[1]:
grid3 = '9.1....8.8.5.7..4.2.4....6...7......5..............83.3..6......9................'
# In[2]:
rows = 'ABCDEFGHI'
cols = '123456789'
# In[3]:
def cross(a, b):
return [s+t for s in a for t in b]
# In[4]:
boxes = cross(rows, cols)
# In[5]:
assignments = []
# In[6]:
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
# In[7]:
# Define diagonal units of a sudoku
diagonal_units = [[x+y for x, y in zip(rows, cols)], [x+y for x, y in zip(rows, cols[::-1])]]
# And refresh unitlist and peers
row_units = [cross(r,cols) for r in rows]
col_units = [cross(rows,c) for c in cols]
square_units = [cross(rs,cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]
unitlist = row_units + col_units + square_units + diagonal_units
units = dict((s, [u for u in unitlist if s in u]) for s in boxes)
peers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)
# In[8]:
def display(values):
"""
Display the values as a 2-D grid.
Input: The sudoku in dictionary form
Output: None
"""
width = 1 + max(len(values[s]) for s in boxes)
line = '+'.join(['-'*(width*3)]*3)
for r in rows:
print(''.join(values[r+c].center(width)+('|' if c in '36' else '')
for c in cols))
if r in 'CF': print(line)
return
# In[9]:
def grid_values(grid):
"""Convert grid string into {<box>: <value>} dict with '.' value for empties.
Args:
grid: Sudoku grid in string form, 81 characters long
Returns:
Sudoku grid in dictionary form:
- keys: Box labels, e.g. 'A1'
- values: Value in corresponding box, e.g. '8', or '.' if it is empty.
"""
lst = list(enumerate(grid))
ind = list(enumerate(boxes))
num = '123456789'
for i in range(len(lst)):
if lst[i][1] == '.':
lst[i] = (i,num)
val = dict((k[1], [v[1] for v in lst][k[0]]) for k in ind)
return val
# In[10]:
def eliminate(values):
"""Eliminate values from peers of each box with a single value.
Go through all the boxes, and whenever there is a box with a single value,
eliminate this value from the set of values of all its peers.
Args:
values: Sudoku in dictionary form.
Returns:
Resulting Sudoku in dictionary form after eliminating values.
"""
solved_values = [box for box in values.keys() if len(values[box]) == 1]
# print(solved_values)
for box in solved_values:
digit = values[box]
for peer in peers[box]:
values[peer] = values[peer].replace(digit,'')
return values
# In[11]:
def only_choice(values):
"""Finalize all values that are the only choice for a unit.
Go through all the units, and whenever there is a unit with a value
that only fits in one box, assign the value to this box.
Input: Sudoku in dictionary form.
Output: Resulting Sudoku in dictionary form after filling in only choices.
"""
for unit in unitlist:
# print('\ncurrent unit \t- {}'.format(unit))
for digit in '123456789':
# print('current digit \t- {}'.format(digit))
dplaces = [box for box in unit if digit in values[box]]
# print('dplaces in unit \t- {}'.format(dplaces))
# print('\n')
if len(dplaces) == 1:
values[dplaces[0]] = digit
return values
# In[12]:
def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
values(dict): the values dictionary with the naked twins eliminated from peers.
"""
# Find all instances of naked twins
naked_twin_dict = {}
pair_dict = {}
for unit in unitlist:
for box in unit:
# Get box value consists of the 2 numbers (candidate)
if len(values[box]) == 2:
for peer in peers:
if box in peers.get(box):
if not values[box] in pair_dict:
pair_dict[values[box]] = [box]
else:
if not box in pair_dict[values[box]]:
pair_dict[values[box]].append(box)
# Examine the dictionary to validate the candidates present as
# naked twin pairs
for key in pair_dict:
if len(pair_dict[key]) == 2:
if not key in naked_twin_dict:
naked_twin_dict[key] = [unit]
else:
naked_twin_dict[key].append(unit)
# if len(naked_twin_dict) != 0:
# print(naked_twin_dict)
# else:
# print('There is no twins in the sudoku.')
# Eliminate the naked twins as possibilities for their peers
for key in naked_twin_dict:
for unit in naked_twin_dict[key]:
for box in unit:
if values[box] != key:
assign_value(values, box, values[box].replace(key[0], ''))
assign_value(values, box, values[box].replace(key[1], ''))
# if len(naked_twin_dict) == 0:
# print("\nCaution: No changes have been made after naked_twins(values)!!!\n")
return values
#display_table(naked_twins(values))
# In[13]:
def reduce_puzzle(values):
""" Iterate eliminate(), naked_twins() and only_choice(). If at some point, there is a box with no available values, return False.
If the sudoku is solved, return the sudoku.
If after an iteration of both functions, the sudoku remains the same, return the sudoku.
Args:
values(dict): A sudoku in dictionary form.
Returns:
values(dict): The resulting sudoku in dictionary form.
"""
solved_values = [box for box in values.keys() if len(values[box]) == 1]
stalled = False
while not stalled:
solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])
values = eliminate(values)
values = naked_twins(values)# there is no necessity of naked_twins() in this example
values = only_choice(values)
solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])
stalled = solved_values_before == solved_values_after
if len([box for box in values.keys() if len(values[box]) == 0]):
return False
return values
# In[14]:
def search(values):
"Using depth-first search and propagation, try all possible values."
# First, reduce the puzzle using the previous function
values = reduce_puzzle(values)
if values is False:
return False ## Failed earlier
if all(len(values[s]) == 1 for s in boxes):
return values ## Solved!
# Choose one of the unfilled squares with the fewest possibilities
n,s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)
print('n - {}, s - {}, values_s - {}'.format(n,s,values[s]))
# Now use recurrence to solve each one of the resulting sudokus, and
for value in values[s]:
new_sudoku = values.copy()
new_sudoku[s] = value
attempt = search(new_sudoku)
if attempt:
return attempt
# In[15]:
def solve(grid):
"""
Find the solution to a Sudoku grid.
Args:
grid(string): a string representing a sudoku grid.
Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns:
The dictionary representation of the final sudoku grid. False if no solution exists.
"""
values = grid_values(grid)
values = reduce_puzzle(values)
return values
if __name__ == '__main__':
diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
display(solve(diag_sudoku_grid))
try:
from visualize import visualize_assignments
visualize_assignments(assignments)
except:
print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')
# In[ ]:
|
633bbc1ef431a5539df27f486fa11c6291930898 | 1505069266/python- | /组的概念和定义/list.py | 802 | 3.8125 | 4 | arr = [1, 2, 3, 4, 5, 6]
print(type(arr))
arr.append('ddd')
print(arr)
arr1 = [[1, 2], [3, 4], 5]
print(arr1)
print(arr1[0][1])
newMoon = ['新月打击', '苍白之瀑', '月之降临', '月神冲刺']
print(newMoon[0])
print(newMoon[0:])
hero = newMoon + ['点燃', '虚弱']
print(hero)
# 元组
yuan = (1, 2, 3, 4, 5)
print(yuan[2])
print(yuan + (8,9,74))
print(type(yuan))
print(type('hello'))
print(type(1))
# python中一个括号包裹着元素,会判断你是在做数学运算,所以是int和str类型,默认把()去掉了
# 一个元素的元组 (1,) 一个元素的没用的元组 ()
print(type((1,)))
print(type(()))
print(type([1]))
print(3 not in [1, 2, 5, 4])
print(3 in [1, 2, 3, 4, 5])
print(len(yuan))
print(max("yuan"))
print(min(yuan))
print(ord("y")) |
680e15e98660f23973a2366c4ae0c44e19d46a3a | Lukhanyo17/Intro_to_python | /Week3/column.py | 132 | 4.09375 | 4 | um = int(input("Enter a number: "))
if (num > -6) and (num < 2) :
for i in range(num, num + 41, 7):
print("%2d" % i)
|
0a04a1e5c3c631f6d0bc5d15c45eae9279c175fa | joswha/interviewpreparation | /leetcode/7.py | 330 | 3.734375 | 4 | def reverse(x):
"""
:type x: int
:rtype: int
"""
if x < 0:
x = str(x)
x = x[1:]
x = -1 * int(x[::-1])
if x < -2 ** 31:
return 0
return x
x = str(x)
x = int(x[::-1])
if x >= 2 ** 31:
return 0
return x
a = 1534236469
print(reverse(a)) |
4df7d3458420e646c340adb0a60f29fdfbb6be95 | fernado1981/python_ | /POO/List_set_dic/List_set_dict.py | 767 | 4.125 | 4 | tuple = {1, 2, 3, 4, 5, 6, 7, 8, 9}
numero = ["uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve"]
print(tuple)
# conversion de set tuple a lista tuple
tuple = list(tuple)
# modificar el array tuple
count = 1
for i in range(len(tuple)):
if tuple[i] == count:
tuple[i] = numero[i]
count += 1
print(tuple)
# convertir de lista tuple a set tuple
tuple = set(tuple)
print(tuple)
# eliminamos la última posicion del conjunto
tuple.pop()
print(tuple)
# eliminamos la ultima posicion de la lista
numero.pop()
print(numero)
# eliminamos la primera posicion de la lista
numero.pop(0)
print(numero)
del numero[0]
print(numero)
# añadimos a la lista
numero.append("diez")
print(numero)
numero.insert(2, "borriquito")
print(numero) |
f884be3644e1e7cd8001b09d5b872ee11515b386 | ash2osh/Algorithmic-Toolbox | /week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py | 1,241 | 3.703125 | 4 | def get_optimal_value(capacity, weights, values):
result = 0.
remainingCapacity = capacity
prices = []
for i in range(0, len(weights)):
prices.append(values[i] / weights[i])
for _ in range(0, len(weights)):
# get max values and weights
maxPrice = max(prices)
maxIndex = prices.index(maxPrice)
maxVal = values[maxIndex]
maxWeight = weights[maxIndex]
# remove those from arrays
weights.pop(maxIndex)
values.pop(maxIndex)
prices.pop(maxIndex)
# weights.remove(maxWeight)
# values.remove(maxVal)
if remainingCapacity - maxWeight >= 0:
remainingCapacity = remainingCapacity - maxWeight
result += maxVal
else:
result += remainingCapacity / maxWeight * maxVal
remainingCapacity = 0
if remainingCapacity == 0:
break
return result
if __name__ == "__main__":
data = list(map(int, input().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
# print(n, capacity, values, weights)
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))
|
b93272d89c441aac1ccca69e4dd82ca1c1481785 | r3sult/My-AI-Experiment | /sample/scratch/kmeans-3.py | 5,047 | 3.515625 | 4 | """
created by : ridwanbejo
deskripsi : contoh implementasi algoritma K-Means untuk clustering data
"""
# library yang dibutuhkan untuk clustering k-means
import math
import collections
import copy
import numpy as np
import matplotlib.pyplot as plt
# fungsi - fungsi yang terlibat dalam perhitungan clustering k-means
def get_euclidean_distance(point_a, point_b):
temp = math.sqrt((point_a['x'] - point_b['x']) ** 2 + (point_a['y'] - point_b['y']) ** 2)
return temp
def find_min_dict(dicto):
temp_v = 999999999999999
temp_k = {}
for k in dicto:
# print k
if k['distance'] < temp_v :
temp_v = k['distance']
temp_k = k
return temp_k
def do_cluster(centroid, data_cluster):
i = 0
for data in data_cluster:
temp_result = []
for center in centroid:
distance = get_euclidean_distance(data, center)
temp_result.append({ 'distance':distance, 'cluster':center['cluster'] })
# print temp_result
closest_distance = find_min_dict(temp_result)
# print closest_distance
data_cluster[i]['cluster'] = closest_distance['cluster']
# indeks untuk list
i = i + 1
return data_cluster
def generate_centroid(old_centroid, temp_cluster):
temp_centroid = []
for centroid in old_centroid:
num = 0
summation_x = 0.0
summation_y = 0.0
for item in temp_cluster:
if centroid['cluster'] == item['cluster']:
# print item['x'], item['y']
summation_x = summation_x + item['x']
summation_y = summation_y + item['y']
num = num + 1
# print summation_x, summation_y
temp_centroid_x = summation_x / num
temp_centroid_y = summation_y / num
temp_centroid.append({'x':temp_centroid_x, 'y':temp_centroid_y, 'cluster':centroid['cluster']})
return temp_centroid
def check_centroid_similarity(old_centroid, new_centroid):
i = 0
counter = 0
for center in old_centroid:
if center['x'] != new_centroid[i]['x'] or center['y'] != new_centroid[i]['y']:
counter = counter + 1
i = i + 1
return counter
def print_cluster(temp_cluster):
print "\n====== HASIL AKHIR CLUSTER =====\n"
for item in temp_cluster:
print item
# contoh data yang akan dicluster
cluster = 2
prev_centroid = []
new_cluster = []
data_cluster = [
{'x':22.21, 'y':11.64, 'cluster':''},
{'x':43.25, 'y':8.95, 'cluster':''},
{'x':19.71, 'y':10.93, 'cluster':''},
{'x':21.05, 'y':10.38, 'cluster':''},
{'x':17.93, 'y':12.85, 'cluster':''},
{'x':17.72, 'y':12.0, 'cluster':''},
{'x':18.71, 'y':11.53, 'cluster':''},
{'x':25.86, 'y':9.33, 'cluster':''},
{'x':19.15, 'y':11.80, 'cluster':''},
{'x':18.42, 'y':11.20, 'cluster':''},
{'x':22.94, 'y':10.60, 'cluster':''},
{'x':26.89, 'y':10.44, 'cluster':''},
{'x':24.91, 'y':10.63, 'cluster':''},
{'x':22.99, 'y':11.47, 'cluster':''},
{'x':26.81, 'y':9.17, 'cluster':''},
{'x':21.09, 'y':10.67, 'cluster':''},
{'x':18.71, 'y':12.36, 'cluster':''},
{'x':20.58, 'y':10.80, 'cluster':''},
{'x':27.66, 'y':9.94, 'cluster':''},
]
centroid = [
{'x':20.0, 'y':9.0, 'cluster':'c1'},
{'x':23.0, 'y':15.0, 'cluster':'c2'},
{'x':27.0, 'y':11.0, 'cluster':'c3'},
]
colors = ['red', 'blue', 'green', 'yellow']
# main process
prev_centroid = centroid
new_cluster = do_cluster(centroid, data_cluster)
# print new_cluster
print "\n====== PENENTUAN CENTROID =====\n"
while True:
new_centroid = generate_centroid(prev_centroid, new_cluster)
print "new centroid: ", new_centroid
centroid_similarity = check_centroid_similarity(prev_centroid, new_centroid)
print centroid_similarity
if (centroid_similarity <= 0):
break
elif (centroid_similarity > 0):
new_cluster = do_cluster(new_centroid, data_cluster)
print '\nnew cluster: '
print_cluster(new_cluster)
prev_centroid = new_centroid
print "\nprev centroid: ", prev_centroid
print "\n"
print_cluster(new_cluster)
# MENAMPILKAN ke dalam GRAFIK SCATTER 2D
area = np.pi * ( 5 ) ** 2
i = 0
for item in new_centroid:
x_list = []
y_list = []
for data in new_cluster:
if item['cluster'] == data['cluster']:
x_list.append(data['x'])
y_list.append(data['y'])
plt.scatter(x_list, y_list, s=area, c=colors[i], alpha=1)
i = i + 1
plt.show() |
29465b8a5795d088e2c2ad1982917d18703b2ee6 | Aasthaengg/IBMdataset | /Python_codes/p02546/s625626401.py | 361 | 3.5 | 4 | #!/usr/bin/env python3
import sys
import collections as cl
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
target = input()
if target[-1] == "s":
print(target+"es")
return
print(target+"s")
main()
|
2cee21ad7586d43a85c06f20ae9d3ee6566afa94 | minsuk-heo/coding_interview_2021 | /Arrays_and_Strings/is_palindrome.py | 440 | 4.28125 | 4 | """
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
"""
def isPalindrome(x: int) -> bool:
x_str = str(x)
if len(x_str) == 1:
return True
if x_str[0] == "-":
return False
if x_str == x_str[::-1]:
return True
else:
return False
print(isPalindrome(121)) |
bde2361c9a9861f15e92b7f1895849f0b047a817 | cheung1/python | /Class_Dog.py | 430 | 4.03125 | 4 |
#class className:
# methods
#define a class
#Class Dog
class Dog:
#defina a method
#dog is barking
def bark(self):
print 'Wang...Wang..Wang...'
def run(self):
print 'dog is running '
#create a dog
doggie = Dog()
#invoke a methon of Dog
doggie.bark()
doggie.run()
#add properties
doggie.weight = 5
doggie.color = 'white'
#get doggies properties
print doggie.weight
print doggie.color
|
d8a209acfc51284ec30e8025aa43edfb2048f721 | marb61a/Course-Notes | /Artificial Intellingence/Python/Notebooks/PyImageSearch University/Deep Learning 105/minivggnet/minivggnet_cifar10.py | 5,492 | 3.625 | 4 | # USAGE
# python minivggnet_cifar10.py --output output/cifar10_minivggnet_with_bn.png
# The text version of the tutorial is available at the following address
# https://www.pyimagesearch.com/2021/05/22/minivggnet-going-deeper-with-cnns/
# VGGNet was first introduced in a 2014 paper which can be found the following address
# https://arxiv.org/abs/1409.1556
# This paper showed that having an architecture with very small (3×3) filters can still
# be trained to increasingly higher depths (16-19 layers) and obtain state-of-the-art
# classification on the challenging ImageNet classification challenge. This is very
# popular in the deep learning community as it shows what CNN's are capable of achieving
# Some of the datasets and gpus were not as capable which meant that some things that were
# being shown by LeNet were not being digested properly. Other factors such as mixed filter
# sizes being used in network architectures were prevalent, the first layer of a network
# for example was usually between 7x7 and 11x11, it was only the deepest network layers that
# used a 3x3 size.
# This is where VGGNet is unique in that it uses 3×3 kernels throughout the entire architecture.
# The use of these small kernels is arguably what helps VGGNet generalize to classification
# problems outside where the network was originally trained. Anytime that a 3x3 network can be
# seen it is a fair bet that it was inspired by VGGNet, there are 16 and 19 layer variants of
# VGGNet but that is for a more advanced level. With modern advances there is the opportunity
# for networks to be 100s of layers deep.
# The VGG family of Convolutional Neural Networks can be characterized by two key components
# - All CONV layers in the network using only 3×3 filters
# - Stacking multiple CONV => RELU layer sets where the consecutive layer sets increases as the network gets deeper
# This is a great architecture to study as you can learn about training patterns prior to the
# application of any pooling operations. Max pooling is used to reduce the volume size
# In VGGNet, we stack multiple CONV => RELU layers prior to applying a single POOL layer. This
# allows the network to learn more rich features from the CONV layers prior to downsampling the
# spatial input size via the POOL operation. Overfitting can be a problem for VGGNet but using
# a dropout feature should alleviate this issue and is usuall applied near fully connected layers.
# Overall, MiniVGGNet consists of two sets of CONV => RELU => CONV => RELU => POOL layers, followed
# by a set of FC => RELU => FC => SOFTMAX layers. The first two CONV layers will learn 32 filters,
# each of size 3×3. The second two CONV layers will learn 64 filters, again, each of size 3×3.
# minivgg.net is available in the pyimagesearch module, in the nn->conv subfolders. The batch
# normalization import is the first time in the course that a CNN using batch normalisation. Many
# network architectures could make use of batch normalisation as a stabilisation mechanism, it
# may take longer to train but in general can reduce the amount of epochs needed for training.
# set the matplotlib backend so figures can be saved in the background
import matplotlib
matplotlib.use("Agg")
# import the necessary packages
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
from pyimagesearch.nn.conv import MiniVGGNet
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.datasets import cifar10
import matplotlib.pyplot as plt
import numpy as np
import argparse
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", required=True,
help="path to the output loss/accuracy plot")
args = vars(ap.parse_args())
# load the training and testing data, then scale it into the
# range [0, 1]
print("[INFO] loading CIFAR-10 data...")
((trainX, trainY), (testX, testY)) = cifar10.load_data()
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0
# convert the labels from integers to vectors
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
# initialize the label names for the CIFAR-10 dataset
labelNames = ["airplane", "automobile", "bird", "cat", "deer",
"dog", "frog", "horse", "ship", "truck"]
# initialize the optimizer and model
print("[INFO] compiling model...")
opt = SGD(lr=0.01, decay=0.01 / 40, momentum=0.9, nesterov=True)
model = MiniVGGNet.build(width=32, height=32, depth=3, classes=10)
model.compile(loss="categorical_crossentropy", optimizer=opt,
metrics=["accuracy"])
# train the network
print("[INFO] training network...")
H = model.fit(trainX, trainY, validation_data=(testX, testY),
batch_size=64, epochs=40, verbose=1)
# evaluate the network
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=64)
print(classification_report(testY.argmax(axis=1),
predictions.argmax(axis=1), target_names=labelNames))
# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, 40), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, 40), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, 40), H.history["accuracy"], label="train_acc")
plt.plot(np.arange(0, 40), H.history["val_accuracy"], label="val_acc")
plt.title("Training Loss and Accuracy on CIFAR-10")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.savefig(args["output"])
|
f60aa0ba9586451a7beeabc096211e196784834e | udhayprakash/PythonMaterial | /python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/e_Calculator/tests/test_addition.py | 880 | 3.796875 | 4 | """
Purpose: Testing addition functionality in calculator
"""
import sys
import unittest
# import os
# print(os.listdir('..'))
sys.path.insert(0, "..")
from calculator import addition
# for each_path in sys.path:
# print(each_path)
class TestSuiteAddition(unittest.TestCase):
def test01(self):
self.assertEqual(addition(10, 20), 30)
def test02(self):
self.assertEqual(addition(10, 20.0), 30.0)
self.assertEqual(addition(10.0, 20), 30.0)
self.assertEqual(addition(10.0, 20.0), 30.0)
def test03(self):
self.assertEqual(addition(10.0, "20"), 30.0)
self.assertEqual(addition("10", "20"), 30.0)
self.assertEqual(addition("10.0", 20), 30.0)
self.assertEqual(addition("10.0", "20.0"), 30.0)
@unittest.expectedFailure
def test04(self):
self.assertEqual(addition("10.0", True), 30.0)
|
4c493528f683bc0188dc1ec2ce2e7a0e0eee99de | Bjarturblaer/M | /yfirferð/yfirferð.py | 2,299 | 4.15625 | 4 | # Breytur
# int float str type print + * / // % input
# x = 2
# x += 2 # x+2
# x *= 2 # x = x*2
# name = input("Your name: ")
# print("Your name is "+name)
# # Boolean
# # if true/false ops and& or|
#x = True
#y = False
#if x:
# print("Yes")
#elif x:
# print("Yes 2")
#else:
# print("No")
# == > < >= <= !=
#if x != y:
# print()
#if 2 > 5:
# print("Hello")
#if 2 < 5 and x:
# print("World")
"""a0 = int(input("Input a positive int: ")) # Do not change this line
print(a0)
while a0 !=1:
if a0 % 2 == 0:
a0 = int(a0/2)
print(a0)
elif a0 % 2 != 0:
a0 = 3*a0+ 1
print(a0)"""
#bugdet_base_charge = 40
#daily_base_charge = 60
"""like_to_continue = input("Would you like to continue (y/n)? ")
while like_to_continue == "y" or like_to_continue == "n":
if like_to_continue == "y":
code = input("Customer code (b or d): ")
elif like_to_continue == "n":
break
if code == "b":
number_days = input("Number of days: ")
elif code == "d":
number_days = input("Number of days: ")
bugdet_base_charge = 40
daily_base_charge = 60
if code =="b":
base_charge = int(number_days)*int(bugdet_base_charge)
elif code =="d":
base_charge = int(number_days)*int(daily_base_charge)
odometer_at_start = (input("Odometer reading at the start: "))
odometer_at_end = (input("Odometer reading at the end: "))
Miles_driven = int(odometer_at_end)-int(odometer_at_start)
if code == "b":
mileage_charge = float(Miles_driven*0.25)
elif code == "d":
average_miles_per_day = float(Miles_driven))/float(number_days)
if float(average_miles_per_day) <=100:
extra_miles_driven = 0
else:
extra_miles_driven = float(average_miles_per_day)-100
mileage_charge = (float(extra_miles_driven)*0.25)*float(number_days)
Amount_due = float(base_charge) + float(mileage_charge)
print("Welcome to car rentals!")
print("Miles driven:",(Miles_driven))
print("Amount due",round(Amount_due))"""
"""def inc(x):
x += 1
return x
x = 5
print(inc(inc(x)))"""
"""def inc2(x):
x += 2
return x
def apply(func, x):
return func(x)
x = 4
print(apply(inc2, x))"""
def h():
x += 1
x = 3
h()
print(x)
|
c42103f846cb3f58392731c8cf94f2155545605a | ErikVasquez/DataStructure | /U4/RadixSort.py | 1,279 | 3.515625 | 4 | #Delgado Vasquez Erik No.Control 17211515
from math import log10
from random import randint
import random
def listaAleatorios(n):
global alist
alist = [0] * n
for i in range(n):
alist[i] = random.randint(0, 1000)
return alist
def get_digit(number, base, pos):
return (number // base ** pos) % base
def prefix_sum(array):
for i in range(1, len(array)):
array[i] = array[i] + array[i-1]
return array
def radixsort(alist, base=10):
passes = int(log10(max(alist))+1)
output = [0] * len(alist)
for pos in range(passes):
count = [0] * base
for i in alist:
digit = get_digit(i, base, pos)
count[digit] +=1
count = prefix_sum(count)
for i in reversed(alist):
digit = get_digit(i, base, pos)
count[digit] -= 1
new_pos = count[digit]
output[new_pos]=i
alist = list(output)
return output
print("Ingrese cuantos numeros aleatorios desea obtener")
alist=int(input())
aleatorios=listaAleatorios(alist)
print(aleatorios)
input()
#alist=[randint(0,1000) for x in range(50)]
sorted = radixsort(alist)
print("Presione cualquier letra para imprimir la lista ordenada de menor a mayor.")
input()
print (sorted)
|
0e7528eb69b8264d2fa29960b00057958b5bcde1 | coderlubo/Web_base | /01_多任务编程/01_多进程(重点).py | 1,435 | 3.609375 | 4 | # 李禄波
# 2021/2/4 下午4:34
import time
import multiprocessing
import os
def dance():
# 获取子进程id
print("子进程 my_dance id:", os.getpid())
# 获取父进程id
print("dance父进程:", os.getppid())
# 获取进程名
print("dance的进程名是:", multiprocessing.current_process())
for i in range(5):
time.sleep(1)
print("dance", i)
def sing():
# 获取子进程id
print("子进程 my_sing id:", os.getpid())
# 获取父进程id
print("sing父进程:", os.getppid())
# 获取进程名
print("sing的进程名是:", multiprocessing.current_process())
for i in range(5):
time.sleep(1)
print("sing", i)
if __name__ == "__main__":
# 单进程 需要十秒钟完成
# 最少有一个进程 该进程中最少有一个线程
# dance()
# sing()
# 获取主进程id
print("主进程id:", os.getpid())
# 多进程 需要五秒完成
# 三个进程: 1个主进程 两个子进程
# 三个线程: 三个线程 一个进程里有一个线程
# 创建子进程
# Process:
# target:指定执行的任务名(函数名)
# name:子进程的名字
my_dance = multiprocessing.Process(target=dance, name="dance")
my_sing = multiprocessing.Process(target=sing)
# 开启子进程(不开启子进程不会执行)
my_dance.start()
my_sing.start()
|
31b33e242eba231a1fe570511f4bb2c133659519 | prabhupant/python-ds | /data_structures/array/min_product.py | 1,118 | 4.125 | 4 | # Use these facts -
# If there are even number of negative numbers and no zeros,
# then the min product is the product of all except the max
# negative value
# If there are odd number of negative numbers and no zeros,
# the result is simply the product of all
# If there is a zero and all other are positive, then the result is zero
# If there are only positive numbers, the the result is
# the smallest positive number
def find(arr):
if len(arr) == 1:
return arr[0]
count_negative = 0
count_zero = 0
max_neg = float('-inf')
min_pos = float('inf')
prod = 1
for num in arr:
if num == 0:
count_zero += 1
continue
if num < 0:
count_negative += 1
max_neg = max(max_neg, num)
if num > 0:
min_pos = min(min_pos, num)
prod *= num
if count_zero == len(arr) or (count_negative == 0 and count_zero > 0):
return 0
if count_negative == 0:
return min_pos
if count_negative & 1 == 0 and count_negative != 0:
prod = int(prod / max_neg)
return prod
|
f73581df48bcdc074777d9c4291586ea518b3e7a | Dylan-Lebedin/Computer-Science-1 | /Labs/mobiles.py | 9,597 | 3.984375 | 4 | """
file: mobiles.py
language: python3
author: CS.RIT.EDU
author: Dylan Lebedin
description: Build mobiles using a tree data structure.
date: 10/2015, 11/2019
purpose: starter code for the tree mobiles lab
"""
############################################################
# #
# IMPLEMENT THE STRUCTURE DEFINITIONS PER REQUIREMENTS, #
# AND #
# IMPLEMENT THE MOBILE CREATION AND ANALYSIS FUNCTIONS. #
# See the 'define structure here' text below, #
# the 'Create mobiles from mobile files' text, #
# and the heading 'mobile analysis functions'. #
# #
# (See also the 'pass' statements to replace.) #
# #
############################################################
from dataclasses import dataclass
from typing import Union
############################################################
# structure definitions
############################################################
@dataclass
class Ball:
"""
class Ball represents a ball of some weight hanging from a cord.
field description:
cord: length of the hanging cord in inches
weight: weight of the ball in ounces (diameter of ball in a drawing)
"""
# define structure here
__slots__ = 'cord', 'weight'
cord: float
weight: float
@dataclass
class Rod:
"""
class Rod represents a horizontal rod part of a mobile with
a left-side mobile on the end of a left arm of some length,
and a right-side mobile on the end of a right arm of some length.
In the middle between the two arms is a cord of some length
from which the rod instance hangs.
field description:
leftmobile: subordinate mobile is a mobile type.
leftarm: length of the right arm in inches
cord: length of the hanging cord in inches
rightarm: length of the right arm in inches
rightmobile: subordinate mobile is a mobile type.
An assembled mobile has valid left and right subordinate mobiles;
an unassembled mobile does not have valid subordinate mobiles.
"""
# define structure here
__slots__ = 'leftmobile', 'leftarm', 'cord', 'rightarm', 'rightmobile'
leftmobile: Union[Ball, 'Rod']
leftarm: float
cord: float
rightarm:float
rightmobile: Union[Ball, 'Rod']
#########################################################
# Create mobiles from mobile files
#########################################################
def read_mobile(file):
"""
read_mobile : OpenFileObject -> Dictionary( Ball | Rod )
read_mobile reads the open file's content and
builds a mobile 'parts dictionary' from the specification in the file.
The parts dictionary returned has components for assembling the mobile.
If the mobile is a simple mobile, the returned value is
a parts dictionary containing a Ball instance.
If the mobile is complex, the returned value is a parts list of
the Rod instance representing the top-most mobile component and
the other parts.
The connection point for each part is a string that identifies
the key name of the part to be attached at that point.
If there is an error in the mobile specification, then
return an empty parts dictionary.
# an example of the file format. 'B10' is key for the 10 oz ball.
# blank lines and '#' comment lines are permitted.
B10 40 10
top B10 240 66 80 B30
B30 55 30
"""
# declare parts dictionary
parts = {}
#with open(file) as filename:
for line in file:
# if file contains # print out line
if "#" in line:
print(line, end="")
key = line.split()
# if length of key is 3, add ball instance
if len(key) == 3:
parts[key[0]] = Ball(float(key[1]), float(key[2]))
# if length of key is 6, add Rod instance
elif len(key) == 6:
parts[key[0]] = Rod(key[1], float(key[2]), float(key[3]), float(key[4]), key[5])
#else:
#return None
# return parts dictionary
return parts
def construct(dict, part):
"""
Return the mobile fully constructed based off the instances in the dictionary
:param dict: dictionary of parts
:param part: part instance, either rod or ball
:return: the mobile fully constructed
"""
# declare the mobile starting at part in dictionary
the_mobile = dict[part]
# if instance of ball return the mobile
if isinstance(the_mobile, Ball):
return the_mobile
# if instance of Rod, return Rod instance recursively calling the left mobile arm and right mobile arm
elif isinstance(the_mobile, Rod):
construct_left = the_mobile.leftmobile
construct_right = the_mobile.rightmobile
return Rod(construct(dict, construct_left), the_mobile.leftarm, the_mobile.cord, the_mobile.rightarm, construct(dict, construct_right))
else:
raise Exception("Error: Not a valid mobile\n\t" + str(the_mobile))
def construct_mobile(parts):
"""
construct_mobile : Dictionary( Rod | Ball ) -> Ball | Rod | NoneType
construct_mobile reads the parts to put together the
mobile's components and return a completed mobile object.
The construct_mobile operation 'patches entries' in the parts.
The parts dictionary has the components for assembling the mobile.
Each Rod in parts has a key name of its left and right
subordinate mobiles. construct_mobile reads the key to
get the subordinate part and attach it at the slot where
the key was located within the component.
The top mounting point of the mobile has key 'top' in parts.
If the completed mobile object is a simple mobile, then
the top returned value is a Ball instance.
If the completed mobile is a complex mobile, then
the top returned value is a Rod instance.
If the parts dictionary contains no recognizable mobile specification,
or there is an error in the mobile specification, then
return None.
"""
# call construct function with the part name being top to start at top and work downwards
return construct(parts, "top")
############################################################
# mobile analysis functions
############################################################
def is_balanced(the_mobile):
"""
is_balanced : Mobile -> Boolean
is_balanced is trivially True if the_mobile is a simple ball.
Otherwise the_mobile is balanced if the product of the left side
arm length and the left side is approximately equal to the
product of the right side arm length and the right side, AND
both the right and left subordinate mobiles are also balanced.
The approximation of balance is measured by checking
that the absolute value of the difference between
the two products is less than 1.0.
If the_mobile is not valid, then produce an exception
with the message 'Error: Not a valid mobile\n\t{mobile}',
pre-conditions: the_mobile is a proper mobile instance.
"""
# if mobile only contains ball, return true
if isinstance(the_mobile, Ball):
return True
# if mobile contains rod, determine if the forces are balanced
elif isinstance(the_mobile, Rod):
left_side = height(the_mobile.leftmobile) * weight(the_mobile.leftmobile)
right_side = height(the_mobile.rightmobile) * weight(the_mobile.rightmobile)
if abs(left_side - right_side <= 1) and is_balanced(the_mobile.leftmobile) == True and is_balanced(the_mobile.rightmobile) == True:
return True
else:
return False
else:
raise Exception("Error: Not a valid mobile\n\t" + str(the_mobile))
def weight(the_mobile):
"""
weight : Mobile -> Number
weight of the the_mobile is the total weight of all its Balls.
If the_mobile is not valid, then produce an exception
with the message 'Error: Not a valid mobile\n\t{mobile}',
pre-conditions: the_mobile is a proper mobile instance.
"""
# if only ball, return the weight
if isinstance(the_mobile, Ball):
return the_mobile.weight
# if rod return weight of left mobile and right mobile
elif isinstance(the_mobile, Rod):
return weight(the_mobile.rightmobile) + weight(the_mobile.leftmobile)
else:
raise Exception("Error: Not a valid mobile\n\t" + str(the_mobile))
def height(the_mobile):
"""
height : the_mobile -> Number
height of the the_mobile is the height of all tallest side.
If the_mobile is not valid, then produce an exception
with the message 'Error: Not a valid mobile\n\t{mobile}',
pre-conditions: the_mobile is a proper mobile instance.
"""
# if only ball return the height of the cord and the diameter of the ball
if isinstance(the_mobile, Ball):
return the_mobile.weight + the_mobile.cord
# if rod return cord plus max of right side or left side
elif isinstance(the_mobile, Rod):
return the_mobile.cord + max(height(the_mobile.leftmobile), height(the_mobile.rightmobile))
else:
raise Exception("Error: Not a valid mobile\n\t" + str(the_mobile))
|
2d8a9a5b2f4028dc196001d2cc6a87978592be34 | wcl19940217/python-projects | /head_sort.py | 1,608 | 3.765625 | 4 | import math
def print_tree(array):
index = 1
depth = math.ceil(math.log2(len(array)))
print(depth)
sep = ' '
for i in range(depth):
offset = 2 ** i
print(sep * (2**(depth-i-1)-1), end='')
line = array[index:index+offset]
for j, x in enumerate(line):
print("{:>{}}".format(x, len(sep)), end='')
interval = 0 if i == 0 else 2 ** (depth-i) - 1
if j < len(line) - 1:
print(sep * interval, end='')
index += offset
print()
origin = [0, 30, 20, 80, 40, 50, 10, 60, 70, 90]
total = len(origin) - 1
print(origin)
print_tree(origin)
print('++++++++')
def heap_adjust(n, i, array: list):
while 2 * i <= n:
lchile_index = 2 * i
max_child_index = lchile_index
if n> lchile_index and array[lchile_index + 1] > array[lchile_index]:
max_child_index = lchile_index + 1
if array[max_child_index] > array[i]:
array[i], array[max_child_index] = array[max_child_index], array[i]
i = max_child_index
else:
break
def max_heap(total, array:list):
for i in range(total//2, 0, -1):
heap_adjust(total, i, array)
return array
print_tree(max_heap(total, origin))
print('--------------------')
def sort(total, array:list):
while total > 1:
array[1], array[total] = array[total], array[1]
total -= 1
if total == 2 and array[total] >= array[total-1]:
break
heap_adjust(total, 1, array)
return array
print_tree(sort(total, origin))
print(origin) |
61643131644eeece0e9b753ad224ea6f3c4105ab | Kushal1412/Competitive-Programming-and-Interview-Prep | /LeetCode/Python/0700_Search_in_a_Binary_Search_Tree_#1.py | 636 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def searchBST(self, root: TreeNode, target: int) -> TreeNode:
if not root:
return
if root.val == target:
return root
if target > root.val and root.right:
return self.searchBST(root.right, target)
if target < root.val and root.left:
return self.searchBST(root.left, target)
else:
return
|
983680a21e9980539d0e8674b93df4e2cd39c004 | gnurenga/python-learn | /unittest/add_ing_v2.py | 1,589 | 4.5 | 4 | """This is a program to add verb+ing form.
1. For word end with `e` drop `e`
2. For word ends in consonent-vowel-consonent
double the last letter
3. For other words just add `ing` at the end
The issue found in the previous version is fixed
in this version. In order to understand Unittest
this code is written
"""
def isVerbends_with_e(word):
""" This function will find the give word ends with `e`
Args:
word (str): english verb
Returns:
True or False (bool): It the verb ends with `e`
it will return True or else false
"""
if len(word) > 3:
if word[-1] == 'e':
return True
else:
return False
def isVerbConsonent(word):
""" This function will find the given wors is in
consonent-vowel-consonent format.
Args:
word (str): english verb
Returns:
True or False (bool): It the verb is of
consonent-vowel-consonent format then
it will return True or else false
"""
vowels = "aeiou"
vowels = "aeiou"
if len(word) != 3:
return False
if word[0] not in vowels and word[2] not in vowels:
if word[1] in vowels:
return True
else:
return False
def add_ing(word):
"""This function will add `ing` format to the given word
Args:
word (str): Verb
Returns:
This function will add `ing` and return the verb
"""
if isVerbends_with_e(word):
return word[:-1] + "ing"
if isVerbConsonent(word):
return word + word[-1] + "ing"
return word + "ing"
|
9781a2621cd2920e2d2a4a64c517f768608221a4 | MatthewBell1/RandomCodes | /Email Slicer.py | 338 | 3.984375 | 4 | # Email splicer
ind = 0
email = input("")
for i in range(0,len(email)):
ind += 1
if email[i] == "@":
print("Your username is", email[0:ind-1], "and the domain is", email[ind:len(email)])
break
elif ind == len(email):
print("Invalid email address")
break
else:
continue
|
c492b964ceac09e356483d6bf0c70ce7c198f2e6 | chrisleo34/FSDI-111-Class-1-Assignment-1 | /lab 1/calc.py | 1,360 | 3.625 | 4 | """
Author: Christian Astarita
Title: Symple Python
"""
# global vars
# functions
def print_separator():
print('_' * 30)
def print_menu():
print_separator()
print('Python Calc')
print_separator()
print("[1] Sum")
print("[2] Subtract")
print("[3] Multiply")
print("[4] Divide")
print("[x] Exit")
print_separator()
def clear():
# HomeWork clear screen python script
lst1 = [[1], [2], [3], [4]]
lst2 = lst1
del lst1[:]
print("\n\n\n")
# direct instrunctions
opc = ''
while(opc != 'x'):
print_menu()
# input creates a pause, until you press enter( reads as a string)
opc = input('Please choose an option: ')
# print(opc) use this code to check if the code is working
if(opc == 'x'):
break
num1 = float(input('Provide num 1: '))
num2 = float(input('Provide num 2: '))
if(opc == '1'):
print(num1 + num2)
elif(opc == '2'):
print(num1 - num2)
elif(opc == '3'):
print(num1 * num2)
elif(opc == '4'):
if(num2 == 0):
print("error, zero divison not allowed")
else:
print(num1 / num2)
else:
print("Please choose a valid option")
input("Press Enter to continue...")
clear()
print('Good Bye!!')
|
0d6a2edb536e7ac5bcc40d273f4ecc807511adad | zachleong/sddchallenges | /semiprime.py | 2,559 | 4.5 | 4 | #run with python 3
from primepriv import isprime #importing my isprime function from another file
import math
#Testing if input is valid or not
while True:
try:
lower = int(input("lower range: "))
upper = int(input("upper range: "))
#if the user puts in valid numbers
if upper > 0 and lower > 0 and upper > lower:
#only continue if the user puts in valid input
break
else:
print("Please put in positive numbers and make sure that the upper range is larger than the lower range")
except:
#Throw an exception if the users does not put in an input
print("Please put in numbers")
#semi prime function
def semiprime (upper, lower, primes):
#array which will hold the semi primes
semiprimes = []
#squarert is the square root of the upper value given
squarert = math.sqrt(upper)
#iterate from 0 to the amount of primes that we have calculated
for x in range(0, len(primes)):
#if we are at a primes that is larger than the square root of the upper, we can stop calculating (rest of them will be above the given range)
if (primes[x] > squarert):
break
#find the upper range of primes that we need for this particular number and round down so we are inclusive
upperprimerange = upper // primes[x]
#find the lower range of primes that we need for this number (add 1 because we need to round up to)
lowerprimerange = lower // primes[x] + 1
#iterate through from the current prime to the rest of them
for i in range(x, len (primes)):
#if this prime is above the range, we can continue to the next number
if primes[i] > upperprimerange:
break
#if the prime is in the range, calculate the semi prime and add it to the list
if primes[i] >= lowerprimerange:
#calculate the semiprime
product = primes[x] * primes[i]
semiprimes.append(product)
return semiprimes
#largestprime is the largest possible prime that we need for this calculation (half of the upper range)
largestprime = math.floor(upper/2)
#primes is a list of the primes that we need in the calculation
primes = isprime(largestprime)#isprime function takes a parameter of the upper range of primes
#call semiprimes function
semiprimes = semiprime(upper, lower, primes)
#sort the semiprimes in ascending order
semiprimes.sort()
#print the semi primes
print("Number of semi primes in range: " + str(len(semiprimes)))
print ("Semi primes in range are: " + str(semiprimes)) |
dc1a668a8f0c7a3f882c97f6913f2dd36a49c436 | smanurung/dcal | /Event.py | 661 | 3.5 | 4 | class Event:
def __init__(self,name,place,start,end,desc):
self.name = name
self.place = place
self.start = start
self.end = end
self.desc = desc
def getName(self):
return self.name
def setName(self,newname):
self.name = newname
def getPlace(self):
return self.place
def getStart(self):
return self.start
def getEnd(self):
return self.end
def getDesc(self):
return self.desc
def toString(self):
tmp = []
tmp.append(self.name)
tmp.append('%%')
tmp.append(self.place)
tmp.append('%%')
tmp.append(self.start)
tmp.append('%%')
tmp.append(self.end)
tmp.append('%%')
tmp.append(self.desc)
return ''.join(tmp) |
07d6d3873250b66c0d36e96ac46edc18ac285240 | 233-wang-233/python | /day15/15day_7.py | 1,682 | 4 | 4 | from abc import ABCMeta,abstractmethod
class Employee(metaclass=ABCMeta):
'''员工(抽象类)'''
def __init__(self,name):
self.name=name
@abstractmethod
def get_salary(self):
'''结算月薪(抽象方法)'''
pass
class Manger(Employee):
'''部门经理'''
def get_salary(self):
return 15000.0
class Programmer(Employee):
'''程序员'''
def __init__(self,name,working_hours=0):
self.working_hours=working_hours
super().__init__(name)
def get_salary(self):
return 200.0*self.working_hours
class Salesman(Employee):
'''销售员'''
def __init__(self,name,sales=0.0):
self.sales=sales
super().__init__(name)
def get_salary(self):
return 1800.0+self.sales*0.05
class EmployeeFactory():
'''创建员工工厂'''
@staticmethod
def create(emp_type,*arg,**kwargs):
'''创建员工'''
emp_type=emp_type.upper()#将小写字母转化为大写字母
emp=None
if emp_type=='M':
emp=Manger(*arg,**kwargs)
elif emp_type == 'P':
emp = Programmer(*arg, **kwargs)
elif emp_type == 'S':
emp = Salesman(*arg, **kwargs)
return emp
def main():
"""主函数"""
emps = [
EmployeeFactory.create('M', '曹操'),
EmployeeFactory.create('P', '荀彧', 120),
EmployeeFactory.create('P', '郭嘉', 85),
EmployeeFactory.create('S', '典韦', 123000),
]
for emp in emps:
print('%s: %.2f元' % (emp.name, emp.get_salary()))
if __name__ == '__main__':
main() |
15d1858b6174d37aee723b8b6abd9acf237f7f71 | patrickspencer/instacart | /src/generate_full_orders.py | 1,710 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
generate_full_orders.py
~~~~~~~~~~~~~~~~~~~~~~~
The `orders` table does not include information about the individual products
that go into each order. `orders` records the relationship between a user and
the order.
The tables `orders_prior` and `orders_train` relate the individual products
(represented by product ids) to the orders. These two tables also record the
order in which the item was added to the order and it this item is a reorder.
These tables have the following features:
- *order_id*
- *product_id*
- *add_to_cart_order*: what order the item was added to the cart. Was it the
first added? The last?
- *reordered*: Has this person ordered this item in the past?
In order to get a large dataframe which includes all the information about the
individual orders and the order itself we would have to concatenate the
`orders_prior` and the `orders_train` table and then merge the new table with
the orders table on the `order_id` column. We want to include all the orders,
even if there are not products in the order, so we would left join the
`orders_prior + orders_train` on the `orders` table. This script does
the left join.
This take a while and produces a file called orders_full.csv which is about 1.9
gb.
"""
import pandas as pd
if __name__ == '__main__':
data_dir = '~/instacart_data/'
orders = pd.read_csv(data_dir + 'orders.csv')
orders_prior = pd.read_csv(data_dir + 'order_products__prior.csv')
orders_train = pd.read_csv(data_dir + 'order_products__train.csv')
df = pd.concat((orders_train, orders_prior), axis=0)
df = orders.merge(df, on='order_id', how='left')
df.to_csv(data_dir + 'orders_full.csv', index=False)
|
d7cf96036bf83ecba6f37927bd76ba2ed9d9c184 | mareced/predavanje_9 | /if_else.py | 297 | 3.625 | 4 | ime = "Franci"
if ime == "Miha":
print("Pozdravljeni, Miha!")
elif ime == "Franci":
print("Pozdravljen, Franci!")
else:
print("Pozdravljen, neznanec")
starost = 30
if starost > 25:
print("star si več kot 25")
elif starost >=18:
print("Odrasel si")
else:
print("Mlad si") |
296c64a89468abd68a4d705b5ec73f12e177c1bf | vlschilling/python-data-structures | /avg2.py | 211 | 4.09375 | 4 | numlist = list()
while (True):
usrinp = raw_input("Enter a number: ")
if usrinp == "done" : break
value = float(usrinp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print "Average:", average
|
fa6d29893080689c31e394963213b7c65a0409d4 | marko37/Fisica-Computacional | /cellular_automaton.py | 3,036 | 3.953125 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import sys, hashlib
def dec_to_any_base(n, base, width=0):
"""Convert from decimal to any base and return an array.
width : The minimum number of elements in the returned array,
with zero-padding if necessary.
"""
if n == 0 and width <= 0: return []
return dec_to_any_base(n//base, base, width-1) + [n%base]
def cellular_automaton(rule=30, n=100, mode=1):
"""Return a matrix representing the evolution of the
cellular automaton n times.
rule : The code of the next generation cell state table.
n : The size of initial state array is 2*n + 1.
The number of iterations that create new generations is n.
mode : 1 for Elementary Cellular Automaton
2 for Totalistic Cellular Automaton
"""
# Creating of the initial state (generation zero).
ca = np.zeros((n+1, 2*n + 3), dtype=int)
# If is Elementary Cellular Automaton.
if mode == 1:
# Setting the state of the middle cell in the initial state.
ca[0, ca.shape[1]//2] = 1 # // is floor division.
# Converting rule to binary and
# creating the next generation cell state table.
# [::-1] reverses the list order.
comb = dec_to_any_base(rule, 2, 8)[::-1]
# In the iteration, multiplying the state of the three cells
# by these values, we convert a number from binary to decimal.
p1, p2 = 2, 4
# If is Totalistic Cellular Automaton.
else:
ca[0, ca.shape[1]//2] = 1
# Converting rule to ternary and
# creating the next generation cell state table.
comb = dec_to_any_base(rule, 3, 7)[::-1]
# In the iteration, multiplying the state of the three cells
# by these values, we obtain the sum.
p1, p2 = 1, 1
# The iteration that finds the state of the cells.
for i in range(n):
for j in range(1, ca.shape[1]-1):
index = ca[i, j-1]*p2 + ca[i, j]*p1 + ca[i, j+1]
ca[i+1, j] = comb[index]
return ca
if len(sys.argv) > 1:
# Getting the arguments from the command line.
size = int(sys.argv[1])
mode = int(sys.argv[2])
rule = int(sys.argv[3])
else:
# We will get the final size, or a time step, then choose the
# elementary cellular automaton (Modo1) or the totallistic cellular
# automaton (Modo2).
size = int(input('What is the size of the grid? '))
mode = int(input('1 (ECA) or 2 (TCA)? '))
if mode == 1:
rule = int(input('Type de rule for the Elementary Cellular ' +
'Automaton, from 0 to 255: '))
else:
rule = int(input('Type de rule for the Totalistic Cellular ' +
'Automaton, from 0 to 2187: '))
ca = cellular_automaton(rule, size, mode)
#print (hashlib.md5(ca.tostring()).hexdigest())
fig, ax = plt.subplots(1, 1, dpi=120)
ax.imshow(ca, cmap=plt.cm.Greys, interpolation='nearest')
plt.show()
|
c65f358380f0189717032666991f396bde4c06ec | rakeshsukla53/interview-preparation | /Rakesh/matrix_arithmetic/rotate in place algorithm.py | 515 | 3.765625 | 4 |
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
matrix[::] = zip(*matrix[::-1])
class Solution:
def rotate(self, A):
n = len(A)
for i in range(n/2):
for j in range(n-n/2):
A[i][j], A[~j][i], A[~i][~j], A[j][~i] = \
A[~j][i], A[~i][~j], A[j][~i], A[i][j]
# best solution you can think of |
e3adaf17f1f3a6b440e392e727f653a0398b623e | palak-ag/CS-Algorithms-and-Programs-that-every-programmer-should-know | /BinarytoDecimal.py | 183 | 4.09375 | 4 | num=int(input("enter the binary number"))
decimal=0
i=0
while(num!=0):
r=num%10
decimal=decimal+r*(pow(2,i))
num=num//10
i=i+1
print("the decimal number is:",decimal)
|
5ebf849519abc4b919e27560586d6787cc5819be | Lisandro79/DataScience | /Python/Arrays/IncrementArbitraryPrecisionInt_5-2.py | 1,499 | 3.9375 | 4 | import numpy as np
# takes as input an array representing a non-negative integer
# E.g.: <1, 2, 9>
# returns an array representing that integer + 1
# E.g. <1, 3, 0>
# Brute force approach:
# - loop through the array, transform each element into a string and concatenate each char
# - transform the string into an int
# - add 1 to the int
# - convert back to string
# - loop through each char, convert into int and store in an array
# O(2n) time complexity
# O(n)
# Intuition
# sum each element and add pow((0, n), 10) -> 0, 10, 100, 1000 ...
def increment_array_string(arr: list) -> list:
# O(n) time complexity
# O(n) space complexity
arr = arr[::-1]
decimal = pow(10, np.arange(1, len(arr)))
integer_sum = 0
for i in range(len(arr)):
if i == 0:
integer_sum += arr[i]
else:
integer_sum += arr[i] * decimal[i-1]
string_sum = str(integer_sum + 1)
arr_sum = []
for i in range(len(string_sum)):
arr_sum.append(int(string_sum[i]))
return arr_sum
def increment_array_decimal(a: list) -> list:
# O(n) time complexity
# O(1) space complexity
a[-1] += 1 # add 1 to the digit
for i in reversed(range(1, len(a))):
if a[i] != 10:
break
a[i] = 0
a[i - 1] += 1
# else:
# remainder = 0
if a[0] == 10:
a[0] = 1
a.append(0)
return a
A = [9, 9, 9]
print(increment_array_string(A))
print(increment_array_decimal(A))
|
2fe9ce908c4ad01543016767f06f958bfad8c5f4 | roger-pan/python-labs | /03_more_datatypes/2_lists/03_06_product_largest.py | 1,056 | 4.28125 | 4 | '''
Take in 10 numbers from the user. Place the numbers in a list.
Find the largest number in the list.
Print the results.
CHALLENGE: Calculate the product of all of the numbers in the list.
(you will need to use "looping" - a concept common to list operations
that we haven't looked at yet. See if you can figure it out, otherwise
come back to this task after you have learned about loops)
'''
'''
number_1 = int(input("Input number: "))
number_2 = int(input("Input number: "))
number_3 = int(input("Input number: "))
number_4 = int(input("Input number: "))
number_5 = int(input("Input number: "))
number_6 = int(input("Input number: "))
number_7 = int(input("Input number: "))
number_8 = int(input("Input number: "))
number_9 = int(input("Input number: "))
number_10 = int(input("Input number: "))
number_list = [number_1,number_2,number_3,number_4,number_5,number_6,number_7,number_8,number_9,number_10]
'''
number_list = [1,2,3,4,5,6,7,8,9,10]
number_product = 1
for x in number_list:
number_product = number_product * x
print(number_product) |
191ab119c5c5f5e5dc57a289a5287bfca27a026e | dwhickox/NCHS-Programming-1-Python-Programs | /Chap 4/NamePrgmFixed.py | 399 | 4.03125 | 4 | #David Hickox
#Mar 11 17
#Name slice prgm
#variables
# name = my name
print("Welcome to the name program")
name = "David William Hickox"
if "z" in name:
print("You have a unique name")
else:
print('You do not have a z in your name')
print("Intials =\t"+name[0]+name[6]+name[14])
print("First name:\t"+name[:5])
print("Last name:\t"+name[6:13])
print("Last name:\t"+name[14:])
input("Press enter to exit.")
|
639f45413a682919f66028c789751a71427d511a | MoisesFlores-1/HIP_HW | /REGISTER.py | 1,564 | 4.46875 | 4 | sales_tax = .95
#sales tax is defined here and can be changed
price = int(input ("Enter Price: ") )
result = 0
#The user inputs the price of the item here.
while (price > 0) :
#As long as the price is greater than 0,
# then the program will loop until 0 is the input from the user
price = float(input("Enter Price :"))
#the price is converted to float from string
total = price % 10
result = result + total
price = price //10
Final_Tax = float(price*sales_tax)
#Here is where the final total plus the tax is calculated.
#However I believe this may be useless if the function below does the same thing.
def calculateCountyTax(price):
return price:float * sales_tax:float
#Once again this is where tax is calculated with the cost of items
input("Is Sales Tax Applicable? Y/N :" )
#User is asked if sales tax is applicable.
#I am having trouble with the "if" statements because when the user inputs
#"N" the program does not run the section for a taxless price.
if True:
#if true is meant to represent if tax IS applicable
print(" Your Final TAX Total is:", Final_Tax:float + price:float )
#The taxed total is described here
float(input("Enter Amount Paid :"))
print("Change today is: ", input - Final_Tax:float + price:float )
#Here is where the change of the customer's money is displayed
if not True:
#if not true would represent if tax is NOT applicable
print ("Your NON TAX Total is:", price:float )
#The total cost without tax is presented
input("Enter Amount Paid :")
print("Change today is: ", input-price:float) |
bd58595a5dd0ff91851693e55e072e2522ed64fc | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4000/codes/1636_869.py | 293 | 3.625 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
valor = float(input("Qual o valor: "))
if (valor>=200):
preco = valor - (5/100) * valor
else:
preco = valor
print(round(preco, 2)) |
513a2392be1b2e8a3a9638440f844ddee740bddd | shadd-anderson/Exercism-Exercises | /python/anagram/anagram.py | 346 | 3.875 | 4 | def find_anagrams(word, candidates):
anagrams = []
word = word.lower()
for candidate in candidates:
lower_candidate = candidate.lower()
if word == lower_candidate:
continue
else:
if sorted(word) == sorted(lower_candidate):
anagrams.append(candidate)
return anagrams
|
bcd2b9c5004fccf9c92b62ea86b6c3a9f320ab45 | ninja-programming/python-basic-series | /writing_file_examples.py | 775 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 4 10:39:53 2021
@author: mjach
"""
'''
how to write in a file with write() and writelines() function
'''
# with open('writing_my_file.txt', 'w') as my_writing_file:
# #writing_file = my_writing_file.writelines('we are learning python basic.')
# writing_file = my_writing_file.write('we are learning python basic and how to writing to a file.')
# my_writing_file.close()
'''
how to append in a file with write() and writelines() function
'''
with open('writing_my_file.txt', 'a') as my_writing_file:
#writing_file = my_writing_file.writelines('\nwe are learning python basic.')
writing_file = my_writing_file.write('\nwe are learning python basic and how to writing to a file.')
my_writing_file.close() |
3b4a1e6058e0eedc97517e9dce35522854bb1323 | weijuwei/python_new | /排序算法/bubbleSort.py | 382 | 4.15625 | 4 | # 冒泡排序
def bubble_sort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-1,i,-1):
if arr[j] < arr[j-1]:
arr[j],arr[j-1] = arr[j-1],arr[j]
return arr
if __name__ == "__main__":
arr = [55, 23, 53, 36, 56, 10, 28, 100, 59, 98, 78]
print("排序前:",arr)
arr1 = bubble_sort(arr)
print("排序后:",arr1) |
bbc04b31245b9834bc4276b54b3cf1131b45eef8 | mcardia98/2019-Network-Security-Internship-Scripts | /log_parser.py | 5,122 | 3.578125 | 4 | '''
Sensitive information replaced with XXXX
Takes a .csv as input and outputs a .csv with information that the network security team can
use to determine health of various elements
'''
import csv
from datetime import datetime
#for formatting purposes to make the output csv look pretty
def add_rows(num_rows, modify_list):
rows = len(modify_list)
row_dif = num_rows - rows
if row_dif == 0:
return
while True:
if rows == num_rows:
break
row = [' ', ' ']
modify_list.append(row)
rows += 1
return
'''
file_input = 'input.csv'
file_output = 'output.csv'
'''
file_input = input("Enter name of file (include extension): ")
if('.csv' not in file_input):
print('Error, please include file extension')
quit()
file_output = input("Enter name of output file (include extension): ")
if('.csv' not in file_output):
print('Error, please include file extension')
quit()
#variables names modified to be more general
element1_list = [['Header 1', ' '], ['Host', 'Last Seen']]
element2_list = [['Header 2', ' '], ['Host', 'Last Seen']]
element3_list = [['Header 3', ' '],['Host', 'Last Seen']]
element4_list = [['Header 4', ' '],['Host', 'Last Seen']]
element5_list = [['Header 5', ' '],['Host', 'Last Seen']]
element6_list = [['Header 6', ' '],['Host', 'Last Seen']]
element7_list = [['Header 7', ' '],['Host', 'Last Seen']]
element8_list = [['Header 8', ' '],['Host', 'Last Seen']]
element9_list = [['Header 9', ' '],['Host', 'Last Seen']]
with open(file_input, mode = 'r') as f:
csv_reader = csv.DictReader(f, delimiter=',')
for row in csv_reader:
log_host = row['Host']
if('XXXX' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element1_list.append(formatting)
if('XXXX-' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element2_list.append(formatting)
if('XXXX' in log_host or 'XXXX' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element3_list.append(formatting)
if('XXXX' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element4_list.append(formatting)
if('XXXX' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element5_list.append(formatting)
if('XXXX' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element6_list.append(formatting)
if('entdns' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element7_list.append(formatting)
if('XXXX' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element8_list.append(formatting)
if('XXXX' in log_host):
time = row['Last Message']
time = time.split(' ')
date = time[0]
formatting = [log_host, date]
element9_list.append(formatting)
element1_list[2:] = sorted(element1_list[2:], key = lambda x: x[1])
element2_list[2:] = sorted(element2_list[2:], key = lambda x: x[1])
element3_list[2:] = sorted(element3_list[2:], key = lambda x: x[1])
element4_list[2:] = sorted(element4_list[2:], key = lambda x: x[1])
element5_list[2:] = sorted(element5_list[2:], key = lambda x: x[1])
element6_list[2:] = sorted(element6_list[2:], key = lambda x: x[1])
element7_list[2:] = sorted(element7_list[2:], key = lambda x: x[1])
element8_list[2:] = sorted(element8_list[2:], key = lambda x: x[1])
element9_list[2:] = sorted(element9_list[2:], key = lambda x: x[1])
max_len = max(len(element1_list), len(element2_list), len(element3_list), len(element4_list),
len(element5_list), len(element6_list), len(element7_list), len(element8_list), len(element9_list))
list_of_lists = [element1_list, element2_list, element3_list, element4_list, element5_list, element6_list,
element7_list, element8_list, element9_list]
for x in list_of_lists:
add_rows(max_len, x)
idx = 0
final_list = []
while idx != max_len:
formatting = [element1_list[idx][0], element1_list[idx][1], element2_list[idx][0], element2_list[idx][1],
element3_list[idx][0], element3_list[idx][1], element4_list[idx][0], element4_list[idx][1], element5_list[idx][0], element5_list[idx][1],
element6_list[idx][0], element6_list[idx][1], element7_list[idx][0], element7_list[idx][1],
element8_list[idx][0], element8_list[idx][1], element9_list[idx][0], element9_list[idx][1]]
final_list.append(formatting)
idx += 1
with open(file_output, 'w', newline="") as csvFile:
writer = csv.writer(csvFile)
writer.writerows(final_list)
csvFile.close()
|
bd3d0a51ea1128fd564e2d50ec9865791303ff3c | thcborges/estrutura-de-dados-com-python3 | /Algoritmos_e_Estrutura_de_Dados/deque_collections.py | 311 | 3.984375 | 4 | from collections import deque
def show(d):
for i in d:
print(i, end=' ')
print()
d = deque()
d.append(1) # adiciona do lado direito
d.appendleft(2) # adiciona do lado esquerdo
d.append(3)
d.appendleft(4)
show(d)
print(d.pop())
show(d)
print(d.popleft())
show(d)
d.remove(1)
show(d)
|
22a2bcc93cd372798d25252aa09e2da75d198adc | Deeachain/Nowcoder-Leetcode | /剑指/字符流中第一个不重复的字符.py | 918 | 4.09375 | 4 | # -*- coding:utf-8 -*-
"""
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,
第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
"""
class Solution:
# 返回对应char
def __init__(self):
self.s = ''
def FirstAppearingOnce(self):
# write code here
result = []
for i in self.s:
if i not in result:
result.append(i)
else:
result.remove(i)
if result == []:
return '#'
else:
return result[0]
def Insert(self, char):
# write code here
self.s += char
if __name__ == '__main__':
Solution = Solution()
Solution.Insert('google')
print(Solution.FirstAppearingOnce()) |
55c3452133a3d517f5fda64b1950c27da3dfbd94 | tBuLi/symfit | /examples/global_fitting.py | 1,882 | 3.609375 | 4 | """
A minimal example of global fitting in symfit.
Two datasets are first generated from the same function.
.. math::
f(x) = a * x^2 + b * x + y_0
All dataset will share the parameter :math:`y_0`, which measures the background,
but :math:`a` and :math:`b` will be unique for each. Additionally, dataset 2
will contain less datapoints than 1 to demonstrate that this will still work.
"""
import numpy as np
from symfit import *
from symfit.core.support import *
import matplotlib.pyplot as plt
import seaborn as sns
palette = sns.color_palette()
x_1, x_2, y_1, y_2 = variables('x_1, x_2, y_1, y_2')
y0, a_1, a_2, b_1, b_2 = parameters('y0, a_1, a_2, b_1, b_2')
# The following vector valued function links all the equations together
# as stated in the intro.
model = Model({
y_1: a_1 * x_1**2 + b_1 * x_1 + y0,
y_2: a_2 * x_2**2 + b_2 * x_2 + y0,
})
# Generate data from this model
xdata1 = np.linspace(0, 10)
xdata2 = xdata1[::2] # Only every other point.
ydata1, ydata2 = model(x_1=xdata1, x_2=xdata2, a_1=101.3, b_1=0.5, a_2=56.3, b_2=1.1111, y0=10.8)
# Add some noise to make it appear like real data
np.random.seed(1)
ydata1 += np.random.normal(0, 2, size=ydata1.shape)
ydata2 += np.random.normal(0, 2, size=ydata2.shape)
xdata = [xdata1, xdata2]
ydata = [ydata1, ydata2]
# Guesses
a_1.value = 100
a_2.value = 50
b_1.value = 1
b_2.value = 1
y0.value = 10
sigma_y = np.concatenate((np.ones(20), [2., 4., 5, 7, 3]))
fit = Fit(
model, x_1=xdata[0], x_2=xdata[1], y_1=ydata[0], y_2=ydata[1], sigma_y_2=sigma_y
)
fit_result = fit.execute()
print(fit_result)
fit_curves = model(x_1=xdata[0], x_2=xdata[1], **fit_result.params)
for xd, yd, curve, color in zip(xdata, ydata, fit_curves, palette):
plt.plot(xd, curve, color=color, alpha=0.5)
plt.scatter(xd, yd, color=color)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Global Fitting, MWE')
plt.show() |
dfdbeff2c17f0cf239fb3ba8fe38aad7b0a2d23f | jmeza44/SevenAndHalf | /Principal.py | 501 | 3.578125 | 4 | # Clase Main de ejecución
from Recursos import iniciar_juego, mostrar_menu_princ, recibir_eleccion_num
if __name__ == "__main__":
while True: # Ciclo de ejecución del algoritmo (Solo termina al seleccionar la opción 3 en el menú principal)
mostrar_menu_princ()
eleccion = recibir_eleccion_num(3)
if eleccion == 1:
iniciar_juego()
elif eleccion == 2:
print("Eleccion dos")
else:
print("Eleccion 3")
break |
f44c0f080765fc7b21ae6d5b344cdd3d78f59ece | DarkstarIV/Mini-Python-Projects | /Time Telling/main.py | 220 | 4.03125 | 4 | import datetime
e = datetime.datetime.now()
print ("Current date and time = %s" % e)
print ("Today's date: = %s/%s/%s" % (e.month, e.day, e.year))
print ("The time is now: = %s:%s:%s" % (e.hour, e.minute, e.second)) |
d7757cf6382fa7c5f42a385258b62e138b9e3e7a | neilshah101/daily-practise | /weekly_journal/week_2/day4/json activity /activity1-writning-to-a-json-file.py | 204 | 3.75 | 4 | import json
name = input("enter the name : ")
age = input("enter the age: ")
with open("person.json" ,"w") as file_object:
person = {"name": name , "age" : age}
json.dump(person,file_object)
|
f8e630194a54eeeee7cb1508b01d9de5c1e443dd | Alpha-W0lf/w3resourcePracticeProblems-Python | /Basic Part 1 Exercises/basic part 1 exercise 17-1.py | 569 | 4.15625 | 4 | # Write a Python program to test whether a number is within 100 of 1000 or 2000.
given = int(input("Enter a number: "))
range = 100
number1 = 1000
number2 = 2000
lowerBound1 = number1 - range
upperBound1 = number1 + range
lowerBound2 = number2 - range
upperBound2 = number2 + range
if given >= lowerBound1 and given <= upperBound1:
print(given, "is within", range, "of", number1)
elif given >= lowerBound2 and given <= upperBound2:
print(given, "is within", range, "of", number2)
else:
print(given, "is not within", range, "of", number1, "or", number2) |
44eb7cd0e4bfcca8b85da7033a9547e14702a5f6 | KobiBeef/learnpythonthehardway | /ex39_test.py | 1,751 | 4.25 | 4 | import hashmap
# creata a mapping of state to abbbreviation
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')
# create a basic set of states and some cities in them
cities = hashmap.new()
hashmap.set(cities, 'CA', 'San Francisco')
hashmap.set(cities, 'MI', 'Detroit')
hashmap.set(cities, 'FL', 'Jacksonville')
# add some more cities
hashmap.set(cities, 'NY', 'New York')
hashmap.set(cities, 'OR', 'Portland')
# print out some cities
print '-' * 10
print "NY states has: %s" % hashmap.get(cities, 'NY')
print "OR states has: %s" % hashmap.get(cities, 'OR')
# print some states
print '-' * 10
print "Michigan's abbbreviation is: %s" % hashmap.get(states, 'Michigan')
print "Florida's abbbreviation is: %s" % hashmap.get(states, 'Florida')
# do it by using the states then citis dict
print '-' * 10
print "Michigan has: %s" % hashmap.get(cities, hashmap.get(states, 'Michigan'))
print "Florida has: %s" % hashmap.get(cities, hashmap.get(states, 'Florida'))
# print every state abbbreviation
print '-' * 10
hashmap.list(states)
# print every city in state
print '-' * 10
hashmap.list(cities)
# now do both at the same time
# print '-' * 10
# for state, abbrev in states.items():
# print "%s state is abbriviated %s and has city %s" % (state, abbrev, cities[abbrev])
print '-' * 10
# safely get a abbbreviation by state that might not be there
state = hashmap.get(states, 'Texas')
if not state:
print "Sorry, no Texas."
# get a city with a defaul value
city = hashmap.get(cities, 'TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
print states
print cities |
d247392051fbfc30e84eab8f65b9ee0e4c19c212 | stefansilverio/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 538 | 4.1875 | 4 | #!/usr/bin/python3
"""
This function prints out text
Returns:
text to stdout
"""
def text_indentation(text):
"""prints text to stdout
Returns text
"""
sym_list = ['.', ':', '?', ]
string = ""
if isinstance(text, str) is not True:
raise TypeError("text must be a string")
for i in text:
string = string + i
if i in sym_list:
string = string.strip()
print(string)
print()
string = ""
string = string.strip()
print(string, end="")
|
f05c7da6e54cd7315cf0ca20618f3405b4051212 | devscheffer/SenacRS-Algoritmos-Programacao-1 | /01 - 2019-03-28 - Estacionamento lista/Task - 01.py | 6,865 | 3.71875 | 4 | # Trabalho - Estacionament
# Autor: Gerson Scheffer
menu = '''
=================
Menu
=================
1- Registrar entrada
2- Registrar saida e pagamento
3- Relatorio
4- Mapa
Escolha: '''
#List
list_lp = [] #license plate dos carros
list_box_car = [] #Box usado pelo carro
list_hin = [] #Horario de entrada
list_hout = [] #Horario de saida
list_pay = [] #Pagamento
list_duration = [] #Tempo do carro no box
list_map = ["Livre"]*20 #Lista de localizacao onde os box vazios sao livres e os ocupados tem seu valor igual a placa do carro
list_box = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] #Numero dos box
list_box_free = [True]*20 #Lista de check se o box esta ocupado ou nao
#Variables
tax = 15 #Taxa paga pelo carro R$/h
hin = ""
lp = ""
box = ""
hout = ""
#Functions
def check_h(h): #Funcao para validar o horario que o usuario inputou, nao funciona se o usuario colocar valores nao numericos
len_h = len(h)
hh = int(h[0:2])
mm = int(h[-2:])
if len_h > 4 or len_h < 4:
print('Hora invalida')
h = input('Digite novamente a hora - formato (24h 0000): ')
return check_h(h)
elif hh > 24 or hh < 00:
print('Hora invalida')
h = input('Digite novamente a hora - formato (24h 0000): ')
return check_h(h)
elif mm > 59 or mm < 00:
print('Hora invalida')
h = input('Digite novamente a hora - formato (24h 0000): ')
return check_h(h)
else:
return
def check_lp1(lp): #Funcao para checar se a placa do carro inputada tem 7 caracteres, nao define que os 3 primeiros caracteres precisam ser alpha e os 4 ultimos numericos
if len(lp) != 7:
print("Placa invalida")
lp = input('''Digite novamente a placa - formato (AAA0000):''')
return check_lp1(lp)
else:
return
def check_lp2(lp): #Funcao para checar se o carro ja esta dentro do estacionamento
if lp in list_lp:
list_lpr = list(reversed(list_lp))
list_houtr = list(reversed(list_hout))
loc_lp = list_lpr.index(lp)
if list_houtr[loc_lp] == "na":
print("Este veiculo ja se encontra no estacionamento")
lp = input('''Digite novamente a placa - formato (AAA0000):''')
return check_lp2(lp)
else:
return
def check_box_in(box_n): #Funcao para checar se o box ja esta sendo usado
box_loc = list_box.index(box_n)
if list_box_free[box_loc] == False:
print("Box indisponivel\n")
op4()
box_n = int(input('\nDigite novamente o numero do box usado: '))
return check_box_in(box_n)
else:
print("Box ocupado")
list_box_free[box_loc] = False
def op1(): #Funcao para registro da opcao 1
print("="*20)
print("Registrar entrada")
print("="*20)
hin = input('Horario de entrada - formato (24h 0000): ')
check_h(hin)
list_hin.append(hin)
lp = input('Placa do carro - formato (AAA0000):')
check_lp1(lp)
check_lp2(lp)
list_lp.append(lp)
box = int(input('Numero do box usado: '))
check_box_in(box)
list_box_car.append(box)
hout = "XXXX"
list_hout.append(hout)
duration = 0
list_duration.append(duration)
pay = 0
list_pay.append(pay)
def pay(hin, hout, tax,lp): #Funcao para definir o quanto deve ser pago no horario de saida
hhin = int(hin[0:2])
mmin = int(hin[-2:])
hhout = int(hout[0:2])
mmout = int(hout[-2:])
if hhout*60+mmout > hhin*60+mmin:
duration = ((((hhout*60+mmout)-(hhin*60+mmin))/60)//1+1)
else:
duration = (((((24*60-hhin*60+mmin)+hhout*60+mmout))/60)//1+1)
loc_lp = list_lp.index(lp)
list_duration[loc_lp] = duration
pay = tax*duration
list_pay[loc_lp] = pay
print("Duracao: {} h".format(list_duration[loc_lp]))
print("Valor a ser pago (R$): ", pay)
def check_box_out(box_n): #Funcao para checar se o box digitado na saida estava realmente ocupado pelo carro que esta saindo
box_loc = list_box.index(box_n)
if list_box_free[box_loc] == False:
print("Box desocupado")
list_box_free[box_loc] = True
else:
print("Box de saida invalido")
def op2(lp): #Funcao opcao 2
print("="*20)
print("Registrar saida")
print("="*20)
check_lp1(lp)
if lp not in list_lp:
print("Placa nao registrada")
lp = input('Digite novamente a placa - formato (AAA0000):')
return op2(lp)
else:
loc_lpr = list(reversed(list_lp)).index(lp)
list_hinr = list(reversed(list_hin))
list_box_carr = list(reversed(list_box_car))
print("Placa: ", lp)
print("Hora de entrada: ", list_hinr[loc_lpr])
print("Box ocupado: ", list_box_carr[loc_lpr])
hout = input('Horario de saida\nformato (24h 0000): ')
check_h(hout)
pay(list_hinr[loc_lpr], hout, tax,lp)
check_box_out(list_box_carr[loc_lpr])
def op3(): #Funcao para gerar o relatorio
print("="*20)
print("Report")
print("="*20)
print(
"""
Placa | Hora de entrada (24h) | Hora de saida (24h) | Tempo (hh) | Box ocupado | Valor pago (R$) |
""",
end="")
print("_"*135)
for i in range(len(list_lp)):
print(
"""
{} | {:2s}:{:2s} | {:2s}:{:2s} | {:3d} | {:2d} | {:6.2f} |
"""
.format(
list_lp[i],
list_hin[i][0:2],
list_hin[i][-2:],
list_hout[i][0:2],
list_hout[i][-2:],
list_duration[i],
list_box_car[i],
list_pay[i],
end=""))
total=0
for i in range(len(list_lp)):
total = total+list_pay[i]
print("Valor total: {}".format(total))
print("Taxa (R$/h): {:.2f}".format(tax))
print("Total de veiculos: {}".format(len(list_lp)))
print("="*20)
def op4(): #Funcao para gerar o mapa do estacioinamento
list_lpr = list(reversed(list_lp))
list_box_carr = list(reversed(list_box_car))
for i in list_box:
if list_box_free[i] == True:
print("box: {:2d} Placa: [ {} ]".format(i, list_map[i]))
else:
list_map[i] = list_lpr[list_box_carr.index(list_box[i])]
print("box: {:2d} Placa: [ {} ]".format(i, list_map[i]))
#Main
while True: #Programa do estacionamento
op = input(menu)
if op == "1":
op1()
elif op == "2":
lp = input('Localizar placa - formato (AAA0000):')
op2(lp)
elif op == "3":
op3()
elif op == "4":
op4()
else:
print("Erro no menu")
#End
|
42eb3c018504a8478d33b37cd40d4af0d664029e | artemschabanov/domash | /task_3_3.py | 117 | 3.6875 | 4 | x = input ("ввведите строку")
f =len(x)
if(f>10):
print(x[0:-1],"!!!")
elif(f<10):
print(x[1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.