blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
25c667d6d414f5dca0b03231086151c86134c04d | nnim99/Introduction-to-Programming-Python- | /Lab8/Task 2.py | 541 | 4 | 4 | def main():
number = int(input("Enter number of enteries: "))
list01 = []
for var in range(0,number):
number01 = int(input("Enter a number: "))
list01.append(number01)
length = len(list01)
index = 0
if list01[index] < list01[index+1]:
smallestNumber = list01[index]
else:
smallestNumber =list01[index+1]
for index in range(1,length-1):
if smallestNumber < list01[index]:
smallestNumber =smallestNumber
else:
smallestNumber = list01[index]
index+=1
print("The minimum value is: ",smallestNumber)
main()
|
7ed570a75ceb5034a461ea83141458dd424b04c8 | RiverStormWinds/flaskPra | /prac_code/yield_prac.py | 2,993 | 3.640625 | 4 | # coding:utf-8
'''
def consumer():
r = ''
while True:
n = yield r
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
r = '200 OK'
def produce(c):
# c.send(None) # c.send(None)启动生成器
c.__next__() # 由此可见,c.send(None)和c.__next__()是一样的作用
n = 0
while n < 5:
n = n + 1
print('[PRODUCER] Producing %s...' % n)
r = c.send(n)
print('[PRODUCER] Consumer return: %s' % r)
c.close()
c = consumer() # consumer()是一个生成器
produce(c) # 将生成器传入produce函数
'''
# 代码解释:c.send(None)之后,生成器consumer接收到send(None)的预激,
# 因为没有c.send(None)发送为None,所以生成器consumer
# 只会执行到n=yield r这一步,但是不会执行n=yield r这一行,完成预激
# 如果没有c.send(None)预激过程,python则会报错:
# can't send non-None value to a just-started generator
# 不能向刚刚启动的生成器发送一个非空的值,也就是说生成器第一步必须进行预激
# 不进行预激则会报错
'''
def consumer():
r = 0
for i in range(3):
yield r
r = '200 OK' + str(i)
c = consumer()
n1 = c.__next__()
# 生成器第一次进行执行,此时r=0,yield r后,n1得到r(即得到0),生成器停止运转
print(n1) # 此次打印n1,0
n2 = c.__next__()
# __next__()再次启动生成器,生成器consumer随即继续运转,得到r='200 OK0'
# 然后进入for循环yield '200 OK0',随即停止运转,n2拿到'200 OK0',随即进行打印
print(n2)
n3 = c.__next__()
# __next__()第三次启动生成器,生成器consumer随即又一次运转,得到r='200 OK1'
# 然后进入for循环yield '200 OK1',随即停止运转,n3拿到'200 OK1',随即进行打印
print(n3)
'''
# 协程由生成器进行实现,最大特点就是单线程中,正在执行的方法可以随即停止切入到其他方法,
# 不用进行线程切换就实现多个方法同时执行。也被成为微线程
# -----------------------------__next__()和send()区别--------------------------
# 实际上next()和send()作用在一定意义上是相似的,区别是send(*args, **kwargs)可以进行
# 参数传递,但是next()无法进行参数传递,也就是说send(None)和next()作用是一致的
def print_num():
for i in range(10):
if i or i==0:
yield i
else:
return
def print_word():
word_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
for j in word_list:
if j:
yield j
else:
return
def data_print():
data_num = print_num()
print(data_num.send(None))
data_word = print_word()
print(data_word.send(None))
i = 0
while i < 9:
print(data_num.send(None)) # 协程取值
print(data_word.send(None)) # 协程取值
i = i + 1
if __name__ == '__main__':
data_print()
|
905f5eded12f932615a3c3a4b096da1d0a67359f | Sirrie/112work | /homework1/test1.py | 879 | 3.515625 | 4 | # Enter these expressions and statements into the interpreter.
# Predict the results of each line before advancing to the next line.
# Be precise.
print 3*3/4, 3/4*3, 3**3/4
x = 1000*1000*1000*1000 # one trillion
x
print x
type(x)
x /= 1000*1000*1000 # divide by one billion
x
x/1000
x
x = 123
x.bit_length()
import sys
x = sys.maxint # 2^31-1, or 2147483647
x.bit_length()
x
x+1
-x
-(x+1)
-x-1
-x-2
not 43
not 43/99
43/99 or 99/43 or 99
print 0xff
print hex(255)
print 255 == 0xff
print 255 == hex(255)
print "-----------------"
x = 5
print 42 if (x == 5) else 99
print ((x == 5) and 42) or 99
print ((x == 5) * 42) + ((x != 5) * 99)
print 42 + (x/6)*(99-42)
print 42 + ((x-5)*(99-42))
print "-----------------"
x = 6
print 42 if (x == 5) else 99
print ((x == 5) and 42) or 99
print ((x == 5) * 42) + ((x != 5) * 99)
print 42 + (x/6)*(99-42)
print 42 + ((x-5)*(99-42)) |
66d55b0da82671ccf12836947f8c63e0165496ff | kburchfiel/cbs_course_review_analysis | /course_ratings_scraper.py | 9,074 | 3.609375 | 4 | # Course Ratings Scraper
# This Python program scrapes ratings information for recent Columbia Business School courses from cbscoursereview.com, stores them in a DataFrame, adds difficulty percentile information, then stores them in a CSV file for further analysis.
# By Kenneth Burchfiel (first uploaded to GitHub on 2/19/2021)
# As a relative newcomer to Python, I borrowed heavily from various resources in order to put this code together, including:
# https://stackoverflow.com/a/60165588/13097194
# https://www.scrapingbee.com/blog/selenium-python/
# https://stackoverflow.com/questions/3030487/is-there-a-way-to-get-the-xpath-in-google-chrome
# Lecture materials from my Python professor (Mattan Griffel)
import requests
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import seaborn as sns
import lxml
import time
import numpy as np
from scipy import stats
# The first step is to determine which course IDs to look up on cbscoursereview.com. I can accomplish this by creating a list (course_ids), then filling that list with IDs for all courses listed on the CBS website in the last 3 semesters.
course_ids = []
# In order to fill the list, I will create a list of soups, then go through this list in order to gather course IDs.
souplist = []
response1 = requests.get('https://www8.gsb.columbia.edu/courses/mba/2021/Spring')
soup1 = BeautifulSoup(response1.text, features='lxml')
time.sleep(2)
response2 = requests.get('https://www8.gsb.columbia.edu/courses/mba/2020/Fall')
soup2 = BeautifulSoup(response2.text, features='lxml')
time.sleep(2)
response3 = requests.get('https://www8.gsb.columbia.edu/courses/mba/2020/Summer')
soup3 = BeautifulSoup(response3.text, features='lxml')
souplist.extend([soup1, soup2, soup3])
# Now that I have my list of soups, I can go through each soup and add all new course ids to my course_ids list.
for soup in souplist:
courses = soup.find_all(class_='mba-course')
for i in range(0,len(courses)):
course_id_result = courses[i].find('a').text
course_id = course_id_result.split('-')[0] # Keeps only the first part of course_id_result, which contains the actual course ID.
if course_id not in course_ids: # Prevents the program from adding duplicate ids into the list
course_ids.append(course_id)
# print(course_id)
print(f"{(len(course_ids))} courses loaded into course list.")
# Now that I have my list of course ids, I can use them to look up various courses on cbscoursereview.com.
# Because cbscoursereview.com is password protected, I needed to use Selenium in order to enable the program to log into the website.
driver = webdriver.Firefox() # I needed to download geckodriver.exe and add it to my PATH folder in Windows for this to work.
driver.get('http://cbscoursereview.com/index.php?page=login')
# Getting my cbscoursereview.com username and password from another folder
with open('..\\pwds\\em.txt') as file:
email = file.read()
with open('..\\pwds\\pw.txt') as file:
password = file.read()
# Logging into cbscoursereview.com using Selenium
login = driver.find_element_by_name("userid").send_keys(email)
password = driver.find_element_by_name("password").send_keys(password)
submit = driver.find_element_by_xpath('//*[@id="content"]/div[1]/div[2]/form/ul/li[3]/input[2]').click() # Used Web Inspector in Chrome to copy the XPath (for the Login button)
# Now that the program has logged into Selenium, it can begin to access ratings information. For each course ID in my list, the for loop below accesses the course's corresponding URL; adds course information into a dictionary; and then adds that dictionary into a list of dictionaries (called ratings_table) that will be converted into a DataFrame.
ratings_table = []
for i in range(0,len(course_ids)): # Using an integer makes it easier to test changes to the loop, as it's possible to set the range to just 3 or 4 courses rather than all of them.
driver.get('http://cbscoursereview.com/index.php?page=courseinfo&courseid='+course_ids[i]) # Conveniently, each course's URL ends with its course ID, so accessing the URL is relatively simple.
time.sleep(2) # Helps ensure that the scraper does not overload the server
ratings_info = {} # This dictionary will store the information gathered for this URL. Each ratings_info dictionary will become a row in the DataFrame.
textblock = driver.find_element_by_xpath("/html/body/div/div[1]/div[3]/p").text # This is the path that contains the text "This course has not yet been rated" in courses that don't yet have ratings data on cbscoursereview.
if "not yet been rated" in textblock: # Without this line, the scraper will stop once it fails to find the elements below for courses that don't yet have ratings information.
print("Not enough ratings--moving on to next course")
continue # Goes back to the for loop so that the code can access the next course
else: # i.e. if ratings information is indeed present on the webpage
print(f"Now analyzing {course_ids[i]} (course {i} of {len(course_ids)})") # This program takes a while to run (about 20 minutes on my computer), so it's helpful to output a progress update in the terminal.
course_name = driver.find_element_by_xpath('/html/body/div/div[1]/div[3]/h2').text # I used a web inspector to figure out where relevant text was located on each page.
course_name = course_name.split(':') # Course names appear on the website as course_id: course name: additional part of course name (if present). Since I only want to store the course name, I added in code to remove the course_id from the course name. First, I split the name wherever a colon appeared.
course_name = course_name[1:] # Next, I stored only the text after the course ID within the course name.
delimiter = ':'
course_name = delimiter.join(course_name) # I then joined together all parts of the course name into one string.
course_name = course_name.strip() # Finally, I removed extra spaces from the course name.
course_rating_text = driver.find_element_by_xpath("/html/body/div/div[1]/div[3]/table[1]/tbody/tr[1]/td[2]").text # Xpath is for the <img src="graphs..."> element, within which is the course ratings data
course_difficulty_text = driver.find_element_by_xpath("/html/body/div/div[1]/div[3]/table[1]/tbody/tr[3]/td[2]").text
course_rating_components = course_rating_text.split('/') # Removes extra text from course_rating
course_rating = course_rating_components[0].strip()
course_difficulty_components = course_difficulty_text.split('/') # Removes extra text from course_difficulty
course_difficulty = course_difficulty_components[0].strip()
# print(course_rating) # for debugging
# print(course_difficulty) # for debugging
ratings_info['course_id']=course_ids[i] # Now that I've gathered the course information I wanted from the webpage, I can store it in the ratings_info dictionary for that course.
ratings_info['course_name']=course_name
ratings_info['course_rating']=float(course_rating) # The course_rating and course_difficulty values aren't stored as numbers by default, hence the float() operation.
ratings_info['course_difficulty']=float(course_difficulty)
ratings_table.append(ratings_info) # Adds this course's dictionary into our table of all course information
# Debug code:
# print(ratings_table)
# for rating in ratings_table:
# print(rating)
# print(rating['course_rating']*10) # Makes sure the course rating is now a float
# print(rating['course_difficulty']*10)
df_ratings = pd.DataFrame(ratings_table) # Converts the ratings table into a DataFrame
df_ratings.set_index('course_id',inplace=True)
pd.set_option('display.max_rows',1000) # Instructs the terminal to display more rows than normal
# I also wanted to determine the difficulty percentile for each course. The following code compares each course_difficulty value with all the values in the course_difficulty column to determine its percentile, then adds that percentile to a list (difficulty_percentiles). Finally, it adds those percentiles to the DataFrame as a new column.
difficulty_percentiles = []
for difficulty in df_ratings['course_difficulty']:
percentile_value = stats.percentileofscore(df_ratings['course_difficulty'],difficulty,kind='mean') # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.percentileofscore.html
print(percentile_value)
difficulty_percentiles.append(percentile_value)
df_ratings['difficulty_percentile'] = difficulty_percentiles
print(df_ratings)
df_ratings.to_csv('course_ratings.csv')
# It would not be ideal to perform further data analysis on df_ratings in this program, since I would need to run the scraper again, wasting time and bandwidth. Instead, I created a new program to analyze this data. |
78d9d09b166fc1d38170f119fb337659bc5dbecd | modal/tktoolbox | /tktoolbox/examples/canvas/bitmap.py | 494 | 3.546875 | 4 | from tkinter import *
canvas_width = 300
canvas_height = 80
master = Tk()
canvas = Canvas(master,
width=canvas_width,
height=canvas_height)
canvas.pack()
bitmaps = ["error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info",
"questhead", "question", "warning"]
nsteps = len(bitmaps)
step_x = int(canvas_width / nsteps)
for i in range(0, nsteps):
canvas.create_bitmap((i + 1) * step_x - step_x / 2, 50, bitmap=bitmaps[i])
mainloop()
|
0fd42dcb8c7913275e78635506f1edec569b2ba5 | TahaKhan8899/Coding-Practice | /TwitterChallenge2020/isPossible.py | 1,010 | 3.625 | 4 | #
# Complete the 'isPossible' function below.
#
# The function is expected to return a BOOLEAN.
# The function accepts following parameters:
# 1. INTEGER_ARRAY calCounts
# 2. INTEGER requiredCals
#
def isPossible(calCounts, requiredCals):
calCounts.sort()
for i in range(0, len(calCounts)-1):
# Find pair in subarray A[i + 1..n-1]
# with sum equal to sum - A[i]
s = {}
curr_sum = requiredCals - calCounts[i]
print("Required: ", requiredCals, "calCounts ",
calCounts[i], "curr_sum: ", curr_sum)
for j in range(i + 1, len(calCounts)):
print("calCounts[j] = ", calCounts[j], "s = ", s)
if (curr_sum - calCounts[j]) in s:
print("Triplet is", calCounts[i],
", ", calCounts[j], ", ", curr_sum-calCounts[j])
return True
s[calCounts[j]] = 1
return False
calCounts = [3, 9, 5, 1, 6]
required = 12
ans = isPossible(calCounts, required)
print(ans)
|
cef9233d5ea6ceb0168ec5959f4aa2ad17db88e9 | samantaavijit/Python_Tutorial | /Function.py | 399 | 4.0625 | 4 | def add(a, b):
print(a + b)
def addition():
a = int(input("Enter a "))
b = int(input("Enter b "))
print(a + b)
def fun1(a, b):
"""This is a function which calculate addition of two number and return the result"""
return a + b
add(int(input("Enter a ")), int(input("Enter b ")))
addition()
print(fun1.__doc__)
print(fun1(int(input("Enter a ")), int(input("Enter b "))))
|
26412fc8084349ecfe6e4be3a5f8636ebabd1e6d | jalondono/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 485 | 3.765625 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
t = (0, 0)
sizea = len(tuple_a)
sizeb = len(tuple_b)
if sizea == 1:
a = tuple_a[0]
c = 0
elif sizea == 0:
a = 0
c = 0
else:
a = tuple_a[0]
c = tuple_a[1]
if sizeb == 1:
b = tuple_b[0]
d = 0
elif sizeb == 0:
b = 0
d = 0
else:
b = tuple_b[0]
d = tuple_b[1]
t = ((a + b), (c + d))
return t
|
b4a9a0ef58ad66bd7ee2aa24ffa473e6b6171a1a | suryavipin42/PythonProjects | /LanguageFundamentals/identifiers.py | 330 | 3.765625 | 4 | # variable name= value
# variable represents the memory location
#start with character, no length limit,but use max upto 4
# identifier = name of class,function ,variable,method
# no= 2
# print(no,"is the value in no.")
brand = "Apple"
exchangeRate = 1.235235245
message = "The price of this %s laptop is" % brand
print (message) |
ff51f23adba85bf19dbdc2fa0f58c44c471d18c3 | ktny/atcoder | /ABC105/c.py | 502 | 3.515625 | 4 | N = int(input())
if N == 0:
print(0)
exit()
# 1桁目から見ていって奇数なら1があるはずなので1桁目は1とやっていく
ans = []
i = 1
while N:
if N % 2 == 0:
ans.append('0')
else:
ans.append('1')
if i % 2 == 0:
N += 1
else:
N -= 1
N //= 2
i += 1
zero = True
for b in reversed(ans):
if zero and b == 0:
continue
elif b == 1:
zero = False
print(b, sep='', end='')
print() |
8e7b16355aaa20085a40ddd5caa3a04e983032fb | Hriman-Mahanta/PythonPrograms | /ArraySum.py | 117 | 3.921875 | 4 | # 8.Program to find the sum of array elements.
A=[1,2,3,4,5]
sum=0
for i in range(0,len(A)):
sum+=A[i]
print(sum) |
bf3eb756fe7bcfca6c84f65ea59bc48dab1085b3 | ychaiu/calculator-2 | /calculator.py | 1,496 | 4.1875 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
from functools import reduce
def my_reduce(function, input_list):
init = input_list[0]
#init = None
for item in input_list[1:]:
init = function(init,item)
return init
print(my_reduce(lambda x,y:divide(x,y), [1,2,3]))
# # No setup
# repeat forever:
def my_calculator():
while True:
raw_input = input(">")
split_input = raw_input.split(" ")
for i in range(1,len(split_input)):
split_input[i] = float(split_input[i])
if split_input[0] == "q":
break
else:
if split_input[0] == "+":
print (reduce(lambda x,y:add(x,y),split_input[1:]))
elif split_input[0] == "-":
print (subtract(split_input[1], split_input[2]))
elif split_input[0] == "*":
print (multiply(split_input[1], split_input[2]))
elif split_input[0] == "/":
print (divide(split_input[1], split_input[2]))
elif split_input[0] == "square":
print (square(split_input[1]))
elif split_input[0] == "cube":
print (cube(split_input[1]))
elif split_input[0] == "pow":
print (power(split_input[1], split_input[2]))
elif split_input[0] == "mod":
print (mod(split_input[1], split_input[2]))
#my_calculator()
# read input
# tokenize input
# if the first token is "q":
# quit
# else:
# decide which math function to call based on first token
# Your code goes here
|
7f2f2d2f725edc9e5b4a28858a221cbc2057d508 | philips-ni/ecfs | /leetcode/091_decode_ways/python/decode_ways.py | 2,565 | 3.921875 | 4 | """
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
"""
"""
class Solution {
public:
int numDecodings(string s) {
vector<int> memo(s.length(), -1);
return helper(s, memo, 0);
}
int helper(string &s, vector<int> &memo, int i)
{
if(i>=s.length())
return 1;
if(memo[i]>=0)
return memo[i];
int r = 0;
if (s[i] != '0')
r += helper(s, memo, i+1);
if(i < s.length() - 1 && ((s[i] == '2' && s[i+1]<'7') || s[i]=='1'))
r+= helper(s, memo, i+2);
memo[i] = r;
return memo[i];
}
};
"""
class Solution(object):
def numDecodings(self, s):
memo = [-1] * len(s)
return self._numDecodings(s, memo, 0)
def _numDecodings(self,s, memo, i):
if i >= len(s):
return 1
if memo[i] > 0:
return memo[i]
ret = 0
if s[i] != '0':
ret += self._numDecodings(s, memo, i+1)
if i < len(s) - 1 and (( s[i] == '2' and s[i+1] < '7') or s[i] == '1'):
ret += self._numDecodings(s, memo, i+2)
memo[i] = ret
return memo[i]
def numDecodings2(self, s):
comps = self.getComps(s)
print comps
counter = 0
for comp in comps:
if self.isValidComp(comp):
counter += 1
return counter
def getComps(self, s):
if len(s) == 0:
return [[]]
if len(s) == 1:
return [[s]]
tmp = self.getComps(s[:-1])
ret = []
for item in tmp:
merged = self.merge(item, s[-1])
for m in merged:
ret.append(m)
return ret
def merge(self, item, c):
ret = [item + [c]]
if len(item[-1]) == 1:
x = item[-1] + c
item[-1] = x
ret.append(item)
return ret
def isValidComp(self, comp):
for i in comp:
if len(i) > 1 and i[0] == "0":
return False
if int(i) > 26 or int(i) < 1:
return False
return True
|
bda89fc0bd4cc4f7acd4118fb562ffbaea80cdf4 | Anh-Quan-07/CAUTRUCDULIEUVAGIAITHUAT | /CTDLGT_Python/BT13. Cài đặt đồ thị có hướng.py | 1,167 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 14 21:30:32 2021
@author: quann
"""
# libraries
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# Build a dataframe with your connections
# This time a pair can appear 2 times, in one side or in the other!
df = pd.DataFrame({'from': ['D', 'A', 'B', 'C', 'A'], 'to': ['A', 'D', 'A', 'E', 'C']})
# Build your graph. Note that we use the DiGraph function to create the graph!
G = nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.DiGraph())
# Make the graph
nx.draw(G, with_labels=True, node_size=1500, alpha=0.3, arrows=True)
plt.title("Directed")
plt.show()
# Build a dataframe with your connections
# This time a pair can appear 2 times, in one side or in the other!
df = pd.DataFrame({'from': ['D', 'A', 'B', 'C', 'A'], 'to': ['A', 'D', 'A', 'E', 'C']})
# Build your graph. Note that we use the Graph function to create the graph!
G = nx.from_pandas_edgelist(df, 'from', 'to', create_using=nx.Graph())
# Make the graph
nx.draw(G, with_labels=True, node_size=1500, alpha=0.3, arrows=True)
plt.title("UN-Directed")
plt.show() |
b08dfb7293f608344ff54d1c8a8d8307d8d58b99 | dharmesh-coder/Full-Coding | /Codevita/Round 2/C.py | 325 | 3.625 | 4 | def countWays(n) :
res = [0] * (n + 2)
res[0] = 1
res[1] = 1
res[2] = 2
for i in range(3, n + 1) :
res[i] = res[i - 1] + res[i - 2] + res[i - 3]
return res[n]
t=int(input())
ans=[]
for i in range(t):
x=int(input())
ans.append(countWays(x+1))
for i in ans:
print(i,end="\n") |
1535a9d70692cc626dd44cd46b51245b8cc84306 | ting-python/Python0709 | /d08/Lambda4.py | 546 | 3.796875 | 4 | def calc(score):
if score >=90:
print("A")
if 90>=score>=80:
print("B")
if 80>=score>=70:
print("C")
if 70>=score>=60:
print("D")
if 60>=score>=50:
print("E")
if score<50:
print("E")
dict = {'level':lambda cin: calc(cin)}
if __name__ == '__main__':
dict.get('level')(95) # 得到A
dict.get('level')(85) # 得到B
dict.get('level')(75) # 得到B
dict.get('level')(65) # 得到D
dict.get('level')(55) # 得到E
dict.get('level')(25) # 得到E
|
6d153ce6956483be57823353f23e6873e21833cf | LFYG/leetcode-acm-euler-other | /project-euler/problem 6.py | 233 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
(1+2+...+n)^2 =((1+n)^2 * n^2)/4
1^2 + 2^2 + ... + n^2 = n*(n+1)*(2n+1)/6
'''
def pep6(n):
return (3*(n**4)+2*(n**3)-3*(n**2)-2*n)/12
if __name__ == '__main__':
print pep6(100) |
c84b8c759631ab6189bc0c7cc7766a8dc1d7e3f5 | AidenLong/python | /base/lesson_02/lesson_02_condition_loop.py | 529 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# if判断
a = 100
b = 200
c = 300
if c == a:
print(a)
elif c == b:
print(b)
else:
print(c)
# None的判断
x = None
if x is None:
print('x is None')
if not x:
print('x is None')
# for循环
s = 0
for i in range(0, 101):
s += i
print(s)
# while循环
s = 0
i = 0
while i <= 100:
s += i
i += 1
print(s)
# continue/pass/break
for i in range(0, 100):
if i < 10:
pass
elif i < 30:
continue
elif i < 35:
print(i)
else:
break
|
41f9b3675518a083dca22d8af61b19072f500722 | DaviMarinho/PythonCEV | /ex055.py | 438 | 3.890625 | 4 | #Exercício Python 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 = float(0)
menor = float(9999)
for i in range(0,5):
peso = float(input(f'Escreva o peso da {i+1}ª pessoa:\n'))
if peso > maior:
maior = peso
elif peso < menor:
menor = peso
print(f'O maior peso listado foi {maior:.2f}!')
print(f'O menor peso listado foi {menor:.2f}!') |
ac35618edd53d70fea53a8fa0ea38d9a6a591988 | Riadhoq/DSA | /algorithms/searching/binary-search-recursive.py | 1,724 | 4.125 | 4 | """
Binary Search Recursive
"""
# This was the first try
# this does not remember the actual index
#
# def binary_search_first(list, item_to_find):
# if len(list) == 0:
# return -1
# mid = len(list) // 2
# # print(list)
# if list[mid] == item_to_find:
# # print(mid)
# return mid
# elif list[mid] > item_to_find:
# binary_search(list[:mid], item_to_find)
# else:
# binary_search(list[mid:], item_to_find)
def binary_search(list, item_to_find):
return binary_search_recursive(list, 0, len(list) - 1, item_to_find)
def binary_search_recursive(list, left, right, item_to_find):
if left > right:
return -1
mid = (left + right) // 2
# print(mid)
if list[mid] == item_to_find:
return mid
elif list[mid] > item_to_find:
# forgot to put return
return binary_search_recursive(list, left, mid - 1, item_to_find)
else:
# forgot to put return
return binary_search_recursive(list, mid + 1, right, item_to_find)
if __name__ == "__main__":
# find an item that exists in the array
find = 62
list = [13,124,352,find,15,73,25,27]
list = sorted(list)
print(list)
print(binary_search(list, find))
# find an item that exists in the array and its the last item of the array
find = 352
list = [13,124,352,15,73,25,27]
list = sorted(list)
print(list)
print(binary_search(list, find))
# find an item that exists in the array and its the first item of the array
find = 13
list = [13,124,352,15,73,25,27]
list = sorted(list)
print(list)
print(binary_search(list, find))
# find an item that doesn't exists in the array
find = 12
list = [13,124,352,15,73,25,27]
list = sorted(list)
print(list)
print(binary_search(list, find)) |
92e154f615e7a3320338d294b995bada9027b77a | Linuzs/Pythonwork | /baskteball.py | 2,673 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author:Linuz
"""
team_a_list=[]
team_b_list=[]
team_a = input("初始化球队1名称:")
team_b = input("初始化球队2名称:")
team = ""
score_a = 0
score_b = 0
while team != 'game over':
if team_a.strip() != team_b.strip() and team_a.strip() != "game over" and team_b.strip() != "game over" and team_a.strip() != "" and team_b.strip() != "":
#a球队与b球队名称不能相等,并且名称不能为“game over”,过滤首位空格,过滤空名称
team = input("输入球队名称:")
if team == team_a:
#只有输入的队伍名与初始化的队伍名相等才会继续下面的操作,否则直接退出
team_a_score = input("输入球队分数:")
if team_a_score.isdigit() == True and int(team_a_score) <= 3:
#分数需要纯数字,并且小于等于3分,否则提示错误
score_a = 0
team_a_list.append(int(team_a_score))
team_a_list.append(team)
#先插入队伍分数,后插入队伍名
for i in team_a_list[::2]:
#指定格式追加到列表,分数步长为2,所以可以把所有的分数遍历相加
score_a = score_a + i
print("球队<%s>的分数为:%d\n球队<%s>的分数为:%d"%(team_a, score_a, team_b, score_b))
else:
print("请输入正确的分数!")
elif team == team_b:
team_b_score = input("输入球队分数:")
if team_b_score.isdigit() == True and int(team_b_score) <= 3:
score_b = 0
team_b_list.append(int(team_b_score))
team_b_list.append(team)
for i in team_b_list[::2]:
score_b = score_b + i
print("球队<%s>的分数为:%d\n球队<%s>的分数为:%d"%(team_b, score_b, team_a, score_a))
else:
print("请输入正确的分数!")
elif team == 'game over':
pass
else:
print("该球队名称未定义!")
else:
print("球队名称有误,请重新输入!")
break
else:
if score_a > score_b:
print("球队<%s>赢了!总分为:%d\n球队<%s>的总分为:%d"%(team_a, score_a, team_b, score_b))
elif score_a < score_b:
print("球队<%s>赢了!总分为:%d\n球队<%s>的总分为:%d"%(team_b, score_b, team_a, score_a))
else:
print("平局!\n球队<%s>的总分为:%d\n球队<%s>的总分为:%d"%(team_a, score_a, team_b, score_b))
|
e03b05f8b981a1f6d404d441afa6f8effab13a92 | KatherineCG/TargetOffer | /37-两个链表的第一个公共结点.py | 1,368 | 3.640625 | 4 | # -*- coding:utf-8 -*-
import re
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
if pHead1 == None or pHead2 == None:
return
p1 = pHead1
p2 = pHead2
while p1.next != None and p2.next != None:
p1 = p1.next
p2 = p2.next
temphead1 = pHead1
temphead2 = pHead2
while p1.next != None:
temphead1 = temphead1.next
p1 = p1.next
while p2.next != None:
temphead2 = temphead2.next
p2 = p2.next
while temphead1.next != None:
if temphead1.val == temphead2.val:
return temphead1.val
else:
temphead1 = temphead1.next
temphead2 = temphead2.next
def HandleInput(array):
pHead = ListNode(array[0])
pTemp = pHead
for ch in array[1:]:
pTemp.next = ListNode(ch)
pTemp = pTemp.next
return pHead
array1 = raw_input()
array1 = re.sub('[{}]', '', array1).split(',')
array2 = raw_input()
array2 = re.sub('[{}]', '', array2).split(',')
pHead1 = HandleInput(array1)
pHead2 = HandleInput(array2)
test = Solution()
print test.FindFirstCommonNode(pHead1, pHead2) |
11e0543fb6906dab233301502612f789fa2e5293 | Hezel254/python_projects | /list.py | 104 | 3.90625 | 4 | numbers=[2,4,18,1,9]
max=numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
|
2502b81b581ed7a5106c73475caed8b957a663a6 | kashyapa/interview-prep | /revise-daily/educative.io/depth-first-search/7_path_with_maximum_sum.py | 1,642 | 4.125 | 4 | # Find the path with the maximum sum in a given binary tree. Write a function that returns the maximum sum.
#
# A path can be defined as a sequence of nodes between any two nodes and doesn’t necessarily pass through the root.
# The path must contain at least one node.
import math
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class MaxSum:
def __init__(self):
self.max_sum = -math.inf
def find_maximum_path_sum(root):
def find_max_sum_path(root):
if root is None:
return 0
lsum = find_max_sum_path(root.left)
rsum = find_max_sum_path(root.right)
max_sum.max_sum = max(max_sum.max_sum, max(lsum + root.val, rsum + root.val))
max_sum.max_sum = max(max_sum.max_sum, lsum + root.val + rsum)
return max(lsum+root.val, rsum+root.val)
max_sum = MaxSum()
find_max_sum_path(root)
return max_sum.max_sum
def main():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
print("Maximum Path Sum: " + str(find_maximum_path_sum(root)))
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(5)
root.right.right = TreeNode(6)
root.right.left.left = TreeNode(7)
root.right.left.right = TreeNode(8)
root.right.right.left = TreeNode(9)
print("Maximum Path Sum: " + str(find_maximum_path_sum(root)))
root = TreeNode(-1)
root.left = TreeNode(-3)
print("Maximum Path Sum: " + str(find_maximum_path_sum(root)))
if __name__ == '__main__':
main()
|
881d5f87a7550b4e2858aed9fdead6de1c6af5fc | elit-altum/Python-Basics | /range.py | 132 | 4 | 4 | # works with the built-in range() fn.
for i in range(0, 10, 2):
print(i)
# reversing range
for i in range(10, 0, -1):
print(i) |
be67f5d67911b65f88c7393e42ecad82ca8a946e | nsiicm0/project_euler | /8/primality_test.py | 523 | 4.03125 | 4 | import math
def is_prime(n:int) -> bool:
if n == 1: return False
if n < 4: return True # 2 and 3 are prime
if n % 2 == 0: return False # there are no even primes at this point
if n < 9: return True # 4, 6 and 8 have already been excluded
if n % 3 == 0: return False
r = math.floor(math.sqrt(n)) # satisifes the condition of r*r <= n
f = 5
while f <= r:
if n % f == 0: return False
if n % (f+2) == 0: return False
f=f+6
return True
print(is_prime(67280421310721)) |
f4f82ffd34c0d2c12352e78bc7e72981c8c70402 | Haraboo0814/AtCoder | /Manabi/union_find.py | 1,860 | 3.875 | 4 | class UnionFind():
'''
グループ分けを木構造で管理するデータ構造
以下の二点を高速で行うことができるのがメリット.
・要素xと要素yが同じグループに属するかどうかを判定したい
→ 要素xの根と要素yの根が同じならば同じグループ,
要素xの根と要素yの根が同じでないならば異なるグループ
にあることが分かる.
・要素xと要素yが別のグループに属する場合,
要素xの属するグループと要素yの属するグループを併合する.
'''
def __init__(self, n):
self.n = n
# parents[x] = y: xの親がy
# aが親なら -size(初期値-1)
self.parents = [-1] * n
# グループの根を探索
def find(self, x):
if self.parents[x] < 0: # xが木の根の場合
return x
# 親へ再帰
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
# グループの併合
def unite(self, x, y):
# x, yの根を探索
x = self.find(x)
y = self.find(y)
if x == y: # 同じ木に属する場合
return
# 計算速度のため、小さい方の根を大きい方の根につける
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y] # サイズを加算
self.parents[y] = x # 親の張り替え
# 同じグループに属するか判定
def same(self, x, y):
# 根を比較し同じならtrue
return self.find(x) == self.find(y)
def size(self, x):
return -self.parents[self.find(x)] # 負で保存してあるため
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
|
6019e1447da545ca8e7b1389e929f390b5020b83 | aktech/pydsa | /pydsa/queue.py | 786 | 4 | 4 | class queue(object):
"""
A queue is a container of objects (a linear collection)
that are inserted and removed according to the
first-in first-out (FIFO) principle.
>>> from pydsa import queue
>>> q = queue()
>>> q.enqueue(5)
>>> q.enqueue(8)
>>> q.enqueue(19)
>>> q.dequeue()
5
"""
def __init__(self):
self.List = []
def isEmpty(self):
return self.List == []
def enqueue(self, item):
"""
Insert element in queue.
"""
self.List.append(item)
def dequeue(self):
"""
Remove element from front of the Queue.
"""
return self.List.pop(0)
def size(self):
"""
Return size of Queue.
"""
return len(self.List)
|
859a332bb24a36941d9228f28713aaf586c94cd6 | wanderleibittencourt/Python_banco_dados | /Modulo-2/Aula2-2-Classes/aula5.py | 1,334 | 3.65625 | 4 | from time import sleep
class Escritor:
#METODO CONSTRUTOR
def __init__(self,nome,livros) -> None:
self.__nome = nome
self.__titulos = livros
#Getter
def get_nome(self):
return self.__nome
#Getter
def get_titulos(self):
for livros in self.__titulos: #["livro1","livro2","livro3"]
sleep(1) # quantidade de segunto a imprimir
print(livros)
#Setter
def set_nome(self,valor):
self.__nome = valor
#Variavel Instancia da classe Escritor - valores que estou passando para dentro da classe
escritor = Escritor("shakspeare", ["livro1","livro2","livro3"])
print(escritor.get_nome())
escritor.set_nome("Machado de assis")
print(escritor.get_nome())
escritor.get_titulos()
class Escritor:
#METODO CONSTRUTOR
def __init__(self,nome,livros) -> None:
self.__nome = nome
self.__titulos = livros
@property
def nome(self):
return self.__nome
@nome.setter
def nome(self, valor):
self.__nome = valor
@property
def titulos(self):
return self.__titulos
@titulos.setter
def titulos(self, abacaxi):
self.__titulos = abacaxi
escritor = Escritor("shakspeare", ["livro1","livro2","livro3"])
print(escritor.nome)
escritor.nome = "Machado de Assis"
print(escritor.nome) |
12fc0bae7ae1f3a8bd377f2d598e269dd92dca8f | hsm207/2018-dsb | /src/utils/layers.py | 7,984 | 3.53125 | 4 | import tensorflow as tf
from tensorflow.python.keras.activations import sigmoid, softmax
from tensorflow.python.keras.layers import Conv2D, BatchNormalization, LeakyReLU, MaxPooling2D, GlobalAveragePooling2D
class ConvBlock:
def __init__(self, filters, kernel_size, data_format='channels_first', padding='same', strides=1, alpha=0.1,
is_final=False,
use_edges=False):
"""
A layer that performs the following sequence of operations:
1. 2D Convolution with no activation function
2. Batchnorm
3. Leaky ReLu activation function
If is_final is set to True, then layer will perform the following sequence of operations:
1. Batchnorm
2. 2D Convolution with no activation function
3. Sigmoid activation function if use_edges is False, otherwise softmax channel-wise
:param filters: The number of filters for the 2D convolutional layer
:param kernel_size: The kernel size for the 2D convolutional layer
:param data_format: The data format of the input to the 2D convolutional layer
:param padding: The padding to use for the convolutional layer
:param strides: The strides to use for the convolutional layer
:param alpha: The parameter of the leaky ReLu activation
:param is_final: Boolean flag to signal if this block is an intermediary or final block
:param use_edges: Boolean flag to signal the type of activation function to use if this block is a
final block
"""
channel_axis = 1 if data_format == 'channels_first' else -1
self.is_final = is_final
self.conv = Conv2D(filters,
kernel_size,
strides,
padding,
data_format,
activation='linear',
kernel_initializer='glorot_uniform',
bias_initializer='glorot_uniform')
self.bn = BatchNormalization(axis=channel_axis)
if not is_final:
self.activation = LeakyReLU(alpha=alpha)
else:
if use_edges:
# if edges are used and it is a final layer, then number of channels must be 3
# and we want to normalize channel-wise
self.activation = lambda x: softmax(x, axis=channel_axis)
else:
self.activation = sigmoid
def _forward_pass_regular(self, features):
x = self.conv(features)
x = self.bn(x)
x = self.activation(x)
return x
def _forward_pass_final(self, features):
x = self.bn(features)
x = self.conv(x)
x = self.activation(x)
return x
def __call__(self, features):
if not self.is_final:
x = self._forward_pass_regular(features)
else:
x = self._forward_pass_final(features)
return x
class RibBlock:
def __init__(self, filters, kernel_size, strides=1, alpha=0.1, data_format='channels_first', conv_padding='same',
maxpool_padding='valid'):
"""
A layer that performs the following sequence of operations:
1. 2D Convolution without an activation function
2. Batchnorm
3. Leaky ReLu activation function
4. 2D max pool with (2, 2) stride and kernel size
:param filters: Number of filters for the convolution layer
:param kernel_size: Kernel size for the conovlution layer
:param strides: Strides for the convolution layer
:param alpha: The parameter for the leaky ReLu activation function
:param data_format: The data format of the input to the convolution and max pool layer
:param conv_padding: The padding used for the convolution layer
:param maxpool_padding: The padding used for the max pool layer
"""
channel_axis = 1 if data_format == 'channels_first' else -1
self.conv = Conv2D(filters, kernel_size, strides, padding=conv_padding, data_format=data_format,
activation='linear', use_bias=False, kernel_initializer='glorot_uniform')
self.bn = BatchNormalization(axis=channel_axis)
self.relu = LeakyReLU(alpha=alpha)
self.maxpool = MaxPooling2D(pool_size=2, strides=2, padding=maxpool_padding, data_format=data_format)
def __call__(self, features):
x = self.conv(features)
x = self.bn(x)
x = self.relu(x)
x = self.maxpool(x)
return x
class RibCage:
def __init__(self, filters, kernel_size, strides=1, alpha=0.1, data_format='channels_first', conv_padding='same',
maxpool_padding='valid'):
"""
A Ribcage layer is a layer that consist of 3 Rib Blocks named left, right, and center
The input to the left and right Rib Blocks are distinct while the input to the center Rib Block is the
concatenation of the inputs of the left and right Rib Blocks on the channel axis.
The output of a Ribcage layer is a tuple of 3 tensors, namely:
(output from left rib block,
output from right rib block,
concatenation of output form left, right and center rib block on the channel axis)
:param filters: Number of filters for the convolution layer
:param kernel_size: Kernel size for the conovlution layer
:param strides: Strides for the convolution layer
:param alpha: The parameter for the leaky ReLu activation function
:param data_format: The data format of the input to the convolution and max pool layer
:param conv_padding: The padding used for the convolution layer
:param maxpool_padding: The padding used for the max pool layer
"""
self.channel_axis = 1 if data_format == 'channels_first' else -1
self.left = tf.make_template('left_rib',
RibBlock(filters, kernel_size, strides, alpha, data_format, conv_padding,
maxpool_padding))
self.center = tf.make_template('spine',
RibBlock(filters // 2, kernel_size, strides, alpha, data_format, conv_padding,
maxpool_padding))
self.right = tf.make_template('right_rib',
RibBlock(filters, kernel_size, strides, alpha, data_format, conv_padding,
maxpool_padding))
def __call__(self, images, masks, concat_images_masks):
left_output = self.left(images)
right_output = self.right(masks)
center_output = tf.concat([left_output,
right_output,
self.center(concat_images_masks)], axis=self.channel_axis)
return left_output, right_output, center_output
class ConvToFcAdapter:
def __init__(self, output, data_format='channels_first'):
"""
A layer to substitute flattening the output of a convolutional layer to connect it to a dense layer.
This layer enables the convolution to be performed on arbitrarily size images.
The sequence of operations performed are:
1. 1x1 convolution with output number of filters and no activation function
2. Global average pooling
:param output: The number of neurons this layer should output
:param data_format: The data format of the input passed to the convolution layer
"""
self.conv = Conv2D(filters=output, kernel_size=1, activation='linear', data_format=data_format)
self.global_avg_pool = GlobalAveragePooling2D(data_format=data_format)
def __call__(self, features):
x = self.conv(features)
x = self.global_avg_pool(x)
return x
|
6ef67a38cd7ed0e8244d77b34e92017119cb872a | wurka/molvi | /editor/mentab.py | 445 | 3.953125 | 4 | import sys
elements = {
'H': 0,
'h': 0,
'He': 1,
'he': 1,
'Li': 2,
'li': 2,
'Be': 3,
'be': 3,
'B': 4,
'b': 4,
'c': 5,
'C': 5
}
if __name__ == "__main__":
if len(sys.argv) < 2:
print("say element name, e.g. <python mentab.py H> for hydrogenius")
else:
if not sys.argv[1] in elements:
print("no such element ({}) in table".format(sys.argv[1]))
else:
print("{} index is: {}".format(sys.argv[1], elements[sys.argv[1]]))
|
d2a91e4194dbc893a4b044b242e2a568cb324768 | zryne/languages | /python/main.py | 1,082 | 4.03125 | 4 | from circle import Circle
from sphere import Sphere
from ball import Ball
def main():
c = Circle()
c.set_radius(5)
print('Circle:')
print(' Radius = ' + str(c.get_radius()))
print(' Diameter = ' + str(c.get_diameter()))
print(' Circumference = ' + str(c.get_circumference()))
print(' Area = ' + str(c.get_area()))
s = Sphere()
s.set_radius(5)
print('Sphere:')
print(' Radius = ' + str(s.get_radius()))
print(' Diameter = ' + str(s.get_diameter()))
print(' Circumference = ' + str(s.get_circumference()))
print(' Area = ' + str(s.get_area()))
print(' Volume = ' + str(s.get_volume()))
b = Ball()
b.set_radius(6)
b.set_weight(5.5)
print('Ball:')
print(' Radius = ' + str(b.get_radius()))
print(' Diameter = ' + str(b.get_diameter()))
print(' Circumference = ' + str(b.get_circumference()))
print(' Area = ' + str(b.get_area()))
print(' Volume = ' + str(b.get_volume()))
print(' Weight = ' + str(b.get_weight()))
if __name__=='__main__':
main()
|
171f926906bf71f24bd92540a99c28561e0267e4 | Marmoth85/ExercicesCodinGame | /easy/Python3/defibrillators.py | 662 | 3.53125 | 4 | import sys
import math
lon = input()
lat = input()
n = int(input())
lon_rad, lat_rad = math.radians(float(".".join(lon.split(",")))), math.radians(float(".".join(lat.split(","))))
dist = 10 ** 10
name_defib = ""
for i in range(n):
defib = input()
defib_id, name, address, num, longit, latit = defib.split(";")
longit_drad, latit_drad = math.radians(float(".".join(longit.split(",")))), math.radians(float(".".join(latit.split(","))))
x = (longit_drad - lon_rad) * math.cos(.5 * (lat_rad + latit_drad))
y = latit_drad - lat_rad
d = 6371 * math.sqrt(x ** 2 + y ** 2)
if d < dist:
dist, name_defib = d, name
print(name_defib) |
47603f47c07c76049ededb70428b7d081138365d | Amnesia-f/Code-base | /Python/冒泡排序.py | 352 | 4.03125 | 4 | def bubble_sort(lists):
for i in range(len(lists) - 1):
for j in range(len(lists) - i - 1):
if lists[j] > lists[j + 1]:
lists[j], lists[j + 1] = lists[j + 1], lists[j]
return lists
lists = [98, 90, 82, 95, 88]
print("要排序的列表:", lists)
print("冒泡排序结果:", bubble_sort(lists))
|
59e2fe7ffcbb8f0d84179be6fdc93115d9db271f | Girin7716/KNU-Algorithm-Study | /src/kimkihyun/week_13/BOJ_1990/1990.py | 1,102 | 3.5625 | 4 | # 소수인팰린드롬
import math
a,b = map(int,input().split())
def check(num):
if num == num[::-1]:
return True
return False
def isPrime(num):
if num <= 1:
return False
if num % 2 == 0:
return False
for i in range(3,int(math.sqrt(num)),2):
if num % i == 0:
return False
return True
for i in range(a,b+1):
if check(str(i)):
if isPrime(i):
print(i)
print(-1)
# def prime_list(a,n):
# # 에라토스테네스의 체 초기화 : n개 요소에 True 설정(소수로 간주)
# sieve = [True] * (n+1) #sieve : 체
#
# # n의 최대 약수가 sqrt(n) 이하이므로 i=sqrt(n)까지 검사
# m = int(n ** 0.5)
# for i in range(2,m+1):
# if sieve[i] == True: # i가 소수인 경우
# for j in range(i+i,n,i): #i 이후 i의 배수들을 False로 판정
# sieve[j] = False
# # 소수 목록 산출
# return [i for i in range(a,n+1) if sieve[i] == True and str(i) == str(i)[::-1]]
#
# for i in prime_list(a,b):
# print(i)
# print(-1) |
147480fe64f59452e7a64fe06a521cbc7f91ad85 | hpplayer/LeetCode | /src/p230_sol5.py | 748 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {integer} k
# @return {integer}
def kthSmallest(self, root, k):
stack = []
curr = root
while stack or curr:
if curr:
stack.append(curr)#add current node to last
curr = curr.left
else:
temp = stack.pop()#pop last node from stack
k -= 1
if k == 0:
return temp.val
curr = temp.right
a = []
a.append(1)
a.append(2)
print(a)
a.pop()
print(a) |
a8abc94bf5381b30400918c548040d515fe4c7aa | cmajorsolo/Python_Algorithms | /DirectedGraph.py | 1,101 | 3.796875 | 4 | from collections import defaultdict
graph = defaultdict(list)
def addEdge(graph, u, v):
graph[u].append(v)
def generate_edges(graph):
edges = []
for node in graph:
for neigbours in graph[node]:
edges.append((node, neigbours))
return edges
addEdge(graph,'1','2')
addEdge(graph,'1','3')
addEdge(graph,'2','4')
addEdge(graph,'2','5')
addEdge(graph,'3','1')
addEdge(graph,'3','5')
addEdge(graph,'4','2')
addEdge(graph,'5','2')
addEdge(graph,'5','3')
pathCollection = generate_edges(graph)
print(pathCollection)
print(graph)
# detecting f a graph has a cycle with DFS
def dfs(graph, start, end):
stack = [(start, [])]
while stack:
currentNode, path = stack.pop()
if path and currentNode == end:
yield path
continue
for next_neighbour in graph[currentNode]:
if next_neighbour in path:
continue
stack.append((next_neighbour, path+[next_neighbour]))
for node in graph:
for path in dfs(graph, node, node):
cycles = [node] + path
print(cycles)
|
6e651ec8942e63597234e922fbc3c573beb1fcbf | santhosh2sai/python4me | /containsxo.py | 785 | 3.875 | 4 | #Check to see if a string has the same amount of 'x's and 'o's. The method must
#return a boolean and be case insensitive. The string can contain any char.
#XO("ooxx") => true
#XO("xooxx") => false
#XO("ooxXm") => true
#XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
#XO("zzoo") => false
#Program
def xo(s):
co = 0
xo = 0
for i in s:
if(i is 'o' or i is 'O' ):
co = co + 1
elif(i is 'x' or i is 'X'):
xo = xo + 1
print('count of o & x is',co,xo)
if(xo is co):
print('True')
else:
print('False')
#xo('XxOO')
xo('xo(XXXodhXopoQXoXoXoXXoXCoNomofLXGJooXSXoXobErXAXkoXoo)')
xo('xxxoo')
# another solution
#def xo(s):
# s = s.lower()
# return s.count('x') == s.count('o')
#
|
1777d9b1df83dddd3b5707b765a818584964aca8 | jedzej/tietopythontraining-basic | /students/swietczak_monika/lesson_01_basics/sum_of_three_numbers.py | 190 | 4.1875 | 4 | # This program reads two numbers and prints their sum:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print(a + b + c)
|
0e016e34e46435270dc0bba650016e7ba56a2ced | akshaali/Competitive-Programming- | /Hackerrank/gridChallenge.py | 2,281 | 4.15625 | 4 | """
Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not.
For example, given:
a b c
a d e
e f g
The rows are already in alphabetical order. The columns a a e, b d f and c e g are also in alphabetical order, so the answer would be YES. Only elements within the same row can be rearranged. They cannot be moved to a different row.
Function Description
Complete the gridChallenge function in the editor below. It should return a string, either YES or NO.
gridChallenge has the following parameter(s):
grid: an array of strings
Input Format
The first line contains , the number of testcases.
Each of the next sets of lines are described as follows:
- The first line contains , the number of rows and columns in the grid.
- The next lines contains a string of length
Constraints
Each string consists of lowercase letters in the range ascii[a-z]
Output Format
For each test case, on a separate line print YES if it is possible to rearrange the grid alphabetically ascending in both its rows and columns, or NO otherwise.
Sample Input
1
5
ebacd
fghij
olmkn
trpqs
xywuv
Sample Output
YES
Explanation
The x grid in the test case can be reordered to
abcde
fghij
klmno
pqrst
uvwxy
This fulfills the condition since the rows 1, 2, ..., 5 and the columns 1, 2, ..., 5 are all lexicographically sorted.
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the gridChallenge function below.
def gridChallenge(grid):
row = len(grid)
column = len(grid[0])
for i in range(row):
grid[i] = sorted(grid[i], key=ord)
for i in range(column):
for j in range(row-1):
if ord(grid[j][i]) > ord(grid[j+1][i]):
return("NO")
return("YES")
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
grid = []
for _ in range(n):
grid_item = input()
grid.append(grid_item)
result = gridChallenge(grid)
fptr.write(result + '\n')
fptr.close()
|
9ab0d2938d5e334a3a1060059a2a4b48cea53946 | cosmicRover/algoGrind | /tries/TriesImplementation.py | 3,060 | 4.25 | 4 | #leetcode trie insert and search
# An example of Trie implementation
# It takes into account the english alphabets as input
class TrieNode:
def __init__(self):
#init 26 children as none
self.children = [None] * 26
#a bool representing if it's an end of the word
# it gets set to True if there are no more children on a particular branch
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
#returns new Trie node with 26 children init to None
return TrieNode()
#helper func that maps a provided char to an index
#based on their unicode which can be found using ord()
def _charToIndex(self, ch):
return ord(ch)-ord('a')
def insert(self, key):
# set prefixCrawl to thge root and get length of the input key
prefixCrawl = self.root
length = len(key)
# a for loop through the length of key
for level in range(length):
# get the index of the chars
index = self._charToIndex(key[level])
# if current node isn't present, init a new branch of TriNode() on a child branch
if not prefixCrawl.children[index]:
prefixCrawl.children[index] = self.getNode()
#set prefixCraw to the next node on the tree
prefixCrawl = prefixCrawl.children[index]
# mark the last node as the end
prefixCrawl.isEndOfWord = True
def search(self, key):
# start from the root and loop through elemnts in key and search
prefixCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
# if key doesn't exist in the tree, return False
if not prefixCrawl.children[index]:
return False
#set prefixCraw to the next node on the tree
prefixCrawl = prefixCrawl.children[index]
return prefixCrawl != None and prefixCrawl.isEndOfWord
#looking for chars in the tree that match the key
#exactly the same as search but we only check for prefixCrawl != None
def startsWith(self, key):
prefixCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not prefixCrawl.children[index]:
return False
prefixCrawl = prefixCrawl.children[index]
return prefixCrawl != None
# Input keys (use only 'a' through 'z' and lower case)
keys = ["the","a","there","anaswe","any",
"by","their"]
output = ["Not present in trie",
"Present in trie"]
# Trie object
t = Trie()
# Construct trie
for key in keys:
t.insert(key)
# Search for different keys
print("{} ---- {}".format("the",output[t.search("the")]))
print("{} ---- {}".format("these",output[t.search("these")]))
print("{} ---- {}".format("an startWith",output[t.startsWith("an")]))
|
e8d30b4e4b6f63a328e69796ffa62a96d400f8ca | harrietty/python-katas | /katas/persistence.py | 589 | 3.84375 | 4 | # Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
from functools import reduce
def persistence(num):
if num < 10: return 0
def multiply(arr):
return reduce(lambda total,n: total * n, arr)
loops = 0
while num >= 10:
loops += 1
# Create array of individual integers from the number
s = [int(n) for n in str(num)]
# num = Multiply all integers together
num = multiply(s)
return loops |
8e7bfe127c7488c89391d4fb056f26008701c10f | Katzeminze/A2L_Parser | /Parser_a2l.py | 5,898 | 3.59375 | 4 | import os
import re
class FileA2L:
def __init__(self, path):
self.path = path
self.current_position = 0
self.obligatory_lines_number = 5
if not os.path.exists(self.path):
print("File does not exist")
def write(self, content):
with open(self.path, 'w') as f:
return f.write(content)
def read(self):
with open(self.path, 'r') as f:
return f.read()
def __search_string_in_file(self, string_to_search):
"""search for the given string in file and return list of variables,
which belong to the provided value (string)"""
list_of_results = []
string_measurement_begin = "/begin MEASUREMENT"
string_measurement_end = "/end MEASUREMENT"
# Open the file in read only mode
with open(self.path, 'r') as read_obj:
# Read the file line by line till the EOF
while True:
line = read_obj.readline()
if len(line) == 0:
break
# If the beginning of MEASUREMENT was found read the next
# line and compare it to the input string
if string_measurement_begin in line:
line = read_obj.readline()
if string_to_search in line:
# Read and save to list till the string of the end MEASUREMENT appears
while True:
list_of_results.append(line.strip())
line = read_obj.readline()
if string_measurement_end in line:
break
# Check if all obligatory lines present
try:
if len(list_of_results) < self.obligatory_lines_number:
raise Exception("Minimal data structure of the variable {} was not provided".format(string_to_search))
except Exception as err:
print("Exception: " + err.message)
return list_of_results
def dictionary_measurement_create(self, string_to_search):
"""fill dictionary with data from file according to specified measure variables"""
cursor = 0
data_type = ["UBYTE", "SBYTE", "UWORD", "SWORD", "ULONG",
"SLONG", "A_UINT64", "A_INT64"]
secondary_keywords = ["IF_DATA", "BIT_MASK", "FUNCTION_LIST"]
# Create common string of all elements of list
lines_list = self.__search_string_in_file(string_to_search)
data_string = ""
# for i in lines_list:
# data_string = data_string + " " + i
# Or alternatively
data_string = ' '.join(lines_list)
# Check if the first string has more than 1 element
data_string_name = data_string.partition('\"')[0].strip()
if data_string_name != "":
variable_name = data_string_name
data_string_values = data_string.partition('\"')[2].partition('\"')[2].strip()
final_values_string = data_string_values.split(" ")
# Extract Long identifier
long_identifier = re.findall('"([^"]*)"', data_string)
possible_key = data_type + secondary_keywords
key = []
# Create and fill 2 first elements of dictionary
dictionary_measurement = dict()
dictionary_measurement["Variable name"] = variable_name.strip()
dictionary_measurement["Long identifier"] = long_identifier[0]
# Parse the string till the last word
while cursor < len(final_values_string):
try:
if final_values_string[cursor] in possible_key:
if final_values_string[cursor] in data_type:
# Write obligatory elements into dictionary
dictionary_measurement["Data type"] = final_values_string[cursor]
dictionary_measurement["Type"] = final_values_string[cursor + 1]
dictionary_measurement["Value_1"] = (
int(final_values_string[cursor + 2]), int(final_values_string[cursor + 3]))
dictionary_measurement["Value_2"] = (
float(final_values_string[cursor + 4]), float(final_values_string[cursor + 5]))
cursor += 6
# Catch additional elements that start with a secondary keyword
elif final_values_string[cursor] in secondary_keywords:
key = final_values_string[cursor]
dictionary_measurement[key] = []
cursor += 1
# Write additional elements into dictionary
elif key:
# Parse HEX values
if "0x" in final_values_string[cursor]:
hex_value = hex(int(final_values_string[cursor], 16))
dictionary_measurement[key] = dictionary_measurement[key] + [hex_value]
else:
dictionary_measurement[key] = dictionary_measurement[key] + [final_values_string[cursor]]
cursor += 1
else:
raise IndexError
except IndexError:
print("Exception: Not enough elements were provided")
break
return dictionary_measurement
def parser(measure_variable):
path = "Demo03.a2l"
file1 = FileA2L(path)
return file1.dictionary_measurement_create(measure_variable)
# Get measurements of the specified value
print(parser("B_YELLOW"))
# >>>{'Variable name': 'B_YELLOW', 'FUNCTION_LIST': ['_DEMO_LED'],
# 'IF_DATA': ['DIM', '0x5b', 'INTERN', 'BYTE'], 'Type': 'B_TRUE',
# 'Value_1': (0, 0), 'Value_2': (0.0, 1.0), 'Data type': 'UBYTE',
# 'Long identifier': "Yellow LED's. This is a logical on/off value", 'BIT_MASK': ['0x4']}
|
9c41c48b4c9fb941aef4038ef859593c3e3032ad | gsrr/leetcode | /hackerrank/Moody_Analytics_Women_in_Engineering_Hackathon/01_strong_correlation.py | 610 | 3.515625 | 4 | #!/bin/python
import sys
def minus(val):
if val == 0:
return "equal"
elif val > 0:
return "big"
else:
return "small"
def solve(n, p, d):
# Complete this function
parr = [ minus(p[i] - p[i - 1]) for i in xrange(1, len(p))]
darr = [ minus(d[i] - d[i - 1]) for i in xrange(1, len(d))]
if parr == darr:
return "Yes"
else:
return "No"
if __name__ == "__main__":
n = int(raw_input().strip())
p = map(int, raw_input().strip().split(' '))
d = map(int, raw_input().strip().split(' '))
result = solve(n, p, d)
print result
|
4b7a7d4453b23c6715278f6ab7472f3bc72b36ec | techadddict/Python-programmingRG | /user_input & conditional programming/getUserInput6.py | 1,256 | 4.71875 | 5 | #A string Str1 is a *prefix* of a string Str2 if Str2 can be obtained by adding symbols
#to the right of Str1. For instance the string `abbc' is a prefix of the string `abbcadd' and not a prefix
#of the string `abbdab'. Symmetrically, Str1 is a *suffix* of a string Str2 if Str2 can be obtained by adding
#symbols to the left of Str1. For instance `abbc' is a suffix of `adbabbc' and not a suffix of `ddbbc'.
#Write a program that requests from the user two strings and tells the user whether the second string
#is a prefix of the first one, a suffix of the first one or neither of them.
myStr1=input('Enter a string')
myStr2=input('Enter a string')
len1=len(myStr1)
len2=len(myStr2)
isPrexix=0
for i in range(0,len1):
if ( myStr1 == myStr2[0:len1]):
isPrexix=1
break
if ( isPrexix==1):
print(myStr1 + ' is a prefix of '+ myStr2)
else:
print(myStr1 + ' is not a prefix of '+ myStr2)
myStr1=input('Enter a string')
myStr2=input('Enter a string')
len1=len(myStr1)
len2=len(myStr2)
isSuffix=0
for i in range(0,len1):
if ( myStr1 == myStr2[len1-1:]):
isSuffix=1
break
if (isSuffix==1):
print(myStr1 + ' is a Suffix of '+ myStr2)
else:
print(myStr1 + ' is not a Suffix of '+ myStr2)
|
c6c5c2f16e29ac025415e698fe78791330be7f93 | Ankit-Developer143/Programming-Python | /Regular Expression/demo2.py | 630 | 3.796875 | 4 | """ These methods include group which returns the string matched,
start and end which return the start and ending positions of the first match,
span which returns the start and end positions of the first match as a tuple.
"""
import re
pattern = r"pam"
match = re.search(pattern, "eggspamsausage")
if match:
print(match.group())
print(match.start())
print(match.end())
print(match.span())
"""
op:-
pam
4
7
(4, 7)
"""
#Search And Replace
str = "My name is David. Hi David."
pattern = r"David"
newstr = re.sub(pattern, "Amy", str) #re.sub(old,new,str)
print(newstr)
#My name is Amy. Hi Amy.
|
4615ba7bf8e4e3b7766414cb2ec0c4578d465622 | Florins13/How-to-Think-Like-a-Computer-Scientist | /namespace_test.py | 661 | 3.875 | 4 | import mymodule1
import mymodule2
print((mymodule2.myage - mymodule1.myage) ==
(mymodule2.year - mymodule1.year))
print("My name is", __name__)
mymodule1.main()
# Ex 5
# So, this print __name__ actually prints the name of the module. If you are
# printing the current module (the one you are in) you will get an __main__
# because you are in main, make sense.
# If you print another module you will just simply get the name of that module.
#
# Whats interesting here is that this condition if __name__ == "__main__": let's
# us set functions that will run only if you are in main, or if you call them directly.
# example mymodule1.main()
|
44446f249d37b061f0ed4af0be9644b1c4546365 | john-okey/testrepo | /test_file03.py | 489 | 3.734375 | 4 | import sys
print{" "}
for i in range(1,int((sys.argv[1]))):
if i == 1:
print("Deze nummer is de {}st keer ik 'jij ben geweldig' moet schrijven".format(i))
elif i == 2:
print("Deze nummer is de {}nd keer ik 'jij ben geweldig' moet schrijven".format(i))
elif i == 3:
print("Deze nummer is de {}rd keer ik 'jij ben geweldig' moet schrijven".format(i))
else:
print("Deze nummer is de {}th keer ik 'jij ben geweldig' moet schrijven".format(i))
|
f6d3678d91d680bcc692d3d305d5475f1c68c1e4 | thelabdc/OVSJG-SUSO-public | /src/suso/ab_test.py | 4,314 | 3.6875 | 4 | """
This file contains tools for doing A/B Testing.
@author Kevin H. Wilson <kevin.wilson@dc.gov>
"""
import numpy as np
from scipy import special
from scipy.stats import binom
def degree_of_certainty(successes_a, failures_a, successes_b, failures_b):
"""
Compute the "degree of certainty" that the B side of an A/B test is better
than the A side when the outcome is binary. Literally, this returns::
Pr(p_b > p_a)
where `p_g` is the probability of a "success" in condition `g \in {a, b}`.
Here, we assume that `p_a` and `p_b` are random variables over [0, 1]. We
assume they are independent (indeed, really over entirely distinct probability
spaces). We take a prior that `p_g` is distributed as `Beta(1, 1)`, i.e., the
uniform distribution. Thus, after `successes_g` successes and `failures_g`
failures, the posterior of `p_g` is::
p_g ~ Beta(successes_g + 1, failures_g + 1).
This allows us to compute `Pr(p_b > p_a)`. This works out to be::
sum_{j = 0}^{successes_b + 1}
B(1 + successes_a + j, failures_a + failures_b + 2)
-----------------------------------------------------------------------------
(1 + failures_b + j) B(1 + j, 1 + failures_b) B(success_a + 1, failures_a + 1)
where B(a, b) is the beta function.
For more details, see
http://www.evanmiller.org/bayesian-ab-testing.html
Args:
successes_a (int): The number of successes in condition A
failures_a (int): The number of failures in condition A
successes_b (int): The number of successes in condition B
failures_b (int): The number of failures in condition B
"""
the_range = np.arange(successes_b + 1)
conditional_a = special.betaln(successes_a + 1, failures_a + 1)
return np.sum(
np.exp(
special.betaln(1 + successes_a + the_range, failures_a + failures_b + 2)
- np.log(1 + failures_b + the_range)
- special.betaln(1 + the_range, 1 + failures_b)
- conditional_a
)
)
def degree_of_certainty_draws(
base_rate,
treatment_rate,
num_participants=None,
num_control=None,
num_treatment=None,
num_draws=1000,
):
"""
Draw num_draws from the distribution of the degree of certainty given an assumed
base rate and treatment rate. You must provide either num_partipicants OR num_control
and num_treatment.
Args:
base_rate (float): The assumed rate at which the control group registers a success
treatment_rate (float): The assumed rate at which the treatment group registers a success
num_participants (int|None): The number of participants in the experiment. Assumes both
control and treatment have equal numbers of participants. If None, must provide BOTH
num_control and num_treatment
num_control (int|None): The number of participants in the control group. If provided,
must also provide num_treatment
num_treatment (int|None): The number of participants in the treatment group. If provided,
must also provide num_control
num_draws (int): The number of draws from the degree of certainty distribution
Returns:
np.ndarray[float]: The drawn degrees of certainty
"""
if num_participants:
num_control = num_participants // 2
num_treatment = num_participants - num_control
else:
if not (num_base and num_treatment):
raise ValueError(
"If you provide num_control or num_treatment you must provide the other"
)
# num_control = num_participants // 2
# num_treatment = num_participants - num_control
successes_control = binom.rvs(num_control, base_rate, size=num_draws)
failures_control = num_participants - successes_control
successes_treatment = binom.rvs(num_treatment, treatment_rate, size=num_draws)
failures_treatment = num_participants - successes_treatment
return np.array(
[
degree_of_certainty(s_control, f_control, s_treatment, f_treatment)
for s_control, f_control, s_treatment, f_treatment in zip(
successes_control,
failures_control,
successes_treatment,
failures_treatment,
)
]
)
|
db5e38551af864be9c48f2d1befe3c53253ccddd | seanchen513/leetcode | /design/0146_lru_cache.py | 9,629 | 3.96875 | 4 | """
146. LRU Cache
Medium
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
"""
import sys
sys.path.insert(1, '../../leetcode/linked_list/')
from linked_list import ListNode
import collections
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
###############################################################################
"""
Solution 1: use dict to hold key/value pairs, and use doubly linked list to
hold order of keys.
Can do:
- Can use dummy head and tail for linked list.
- Linked list helper methods.
get(): O(1) time
put(): O(1)
O(capacity) extra space: for dict and doubly linked list
Runtime: 204 ms, faster than 66.84% of Python3 online submissions
Memory Usage: 22.5 MB, less than 6.06% of Python3 online submissions
"""
# class ListNode():
# def __init__(self, val=None, next=None, prev=None):
# self.val = val
# self.next = next
# self.prev = prev
class LRUCache:
def __init__(self, capacity: int): # Assume capacity > 0
self.d = {}
self.head = None
self.tail = None
self.capacity = capacity
def __repr__(self):
arr = []
curr = self.head
while curr:
arr.append(str(curr.val))
curr = curr.next
return '->'.join(arr)
def get(self, key: int) -> int:
if key not in self.d:
return -1
val, node = self.d[key]
if self.tail == node:
return val
if self.head == node and node.next:
self.head = node.next
# Remove node from doubly linked list.
temp = node.prev
if node.prev:
node.prev.next = node.next
if node.next:
node.next.prev = temp
# Add node to end of doubly linked list.
self.tail.next = node
node.prev = self.tail
self.tail = node
return val
def put(self, key: int, value: int) -> None:
if key in self.d:
self.get(key) # desired side effect of moving node to end of DLL
self.d[key][0] = value
return
if len(self.d) == self.capacity: # Assume > 0
k = self.head.val
del self.d[k]
self.head = self.head.next
if self.head:
self.head.prev = None
node = ListNode(key)
if not self.tail: # linked list is empty
self.head = self.tail = node
else: # add node to end of linked list
self.tail.next = node
node.prev = self.tail
self.tail = node
self.d[key] = [value, node]
"""
Solution 1b: same as sol 1, but use self as dummy head and tail of doubly
linked list.
"""
class LRUCache1b:
def __init__(self, capacity: int): # Assume capacity > 0
self.d = {}
self.prev = self.next = self # self as dummy head and tail of DLL
self.capacity = capacity
def __repr__(self):
arr = []
curr = self.next
while curr != self:
arr.append(str(curr.val))
curr = curr.next
return '->'.join(arr)
def get(self, key: int) -> int:
if key not in self.d:
return -1
val, node = self.d[key]
if self.prev != node: # if node isn't already tail of DLL
# Move node with key value to end of DLL.
self._remove(node)
self._add(node)
return val
def put(self, key: int, value: int) -> None:
if key in self.d:
_, node = self.d[key]
if self.prev != node: # if node isn't already tail of DLL
# Move node with key value to end of DLL.
self._remove(node)
self._add(node)
self.d[key][0] = value
return
if len(self.d) == self.capacity: # Assume > 0
node = self.next # first node of DLL
del self.d[node.val]
self._remove(node) # remove first node of DLL
node.val = key
else:
node = ListNode(key)
self._add(node)
self.d[key] = [value, node]
"""
Add given node to end of doubly linked list.
p - node - self
"""
def _add(self, node):
p = self.prev
p.next = node
node.prev = p
node.next = self
self.prev = node
"""
Remove given node from doubly linked list.
p - node - n
"""
def _remove(self, node):
p = node.prev
n = node.next
p.next = n
n.prev = p
###############################################################################
"""
Solution 2: use dict to hold key/value pairs, and use deque to hold order of
keys.
get(): O(n) time if key already in cache, else O(1)
put(): O(n) time if key already in cache, else O(1)
O(capacity) extra space: for dict and deque
Runtime: 604 ms, faster than 10.39% of Python3 online submissions
Memory Usage: 22.3 MB, less than 6.06% of Python3 online submissions
"""
class LRUCache2:
def __init__(self, capacity: int): # Assume capacity > 0
self.d = {}
self.keys = collections.deque([])
self.capacity = capacity
def __repr__(self):
return '->'.join(map(str, self.keys))
def get(self, key: int) -> int:
if key in self.d:
self.keys.remove(key)
self.keys.append(key)
return self.d[key]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.d:
self.keys.remove(key)
elif len(self.d) == self.capacity: # Assume > 0
k = self.keys.popleft()
del self.d[k]
self.d[key] = value
self.keys.append(key)
###############################################################################
"""
Solution 3: use collections.OrderedDict().
O(1) time for get() and put()
O(capacity) extra space
Runtime: 176 ms, faster than 93.35% of Python3 online submissions
Memory Usage: 22.2 MB, less than 9.09% of Python3 online submissions
"""
class LRUCache3:
def __init__(self, capacity: int): # Assume capacity > 0
self.d = collections.OrderedDict()
self.capacity = capacity
def __repr__(self):
return '->'.join(map(str, self.d))
def get(self, key: int) -> int:
if key in self.d:
self.d.move_to_end(key)
return self.d[key]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.d:
self.d.move_to_end(key)
elif len(self.d) == self.capacity: # Assume > 0
self.d.popitem(last=False)
self.d[key] = value
"""
Solution 3b: same as sol 3, but inherit from OrderedDict instead of having
an instance of it as a class member.
Runtime: 172 ms, faster than 97.24% of Python3 online submissions
Memory Usage: 22.2 MB, less than 7.57% of Python3 online submissions
"""
class LRUCache3b(collections.OrderedDict):
def __init__(self, capacity: int): # Assume capacity > 0
self.capacity = capacity
def __repr__(self):
return '->'.join(map(str, self))
def get(self, key: int) -> int:
if key in self:
self.move_to_end(key)
return self[key]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self:
self.move_to_end(key)
elif len(self) == self.capacity: # Assume > 0
self.popitem(last=False)
self[key] = value
###############################################################################
if __name__ == "__main__":
#cache = LRUCache(2) # use dict and doubly linked list
cache = LRUCache1b(2) # use dict and DLL; self of DLL is dummy head/tail
#cache = LRUCache2(2) # use dict and deque
#cache = LRUCache3(2) # use collections.OrderedDict
#cache = LRUCache3b(2) # inherit from OrderedDict
### LC146 example
cache.put(1, 10)
print(f"\nput(1,10): {cache}") # Only shows keys in LRU order.
cache.put(2, 20)
print(f"\nput(2,20): {cache}")
res = cache.get(1)
print(f"get(1): {res} (expect 10)")
cache.put(3, 30)
print(f"\nput(3,30): {cache}")
res = cache.get(2)
print(f"get(2): {res} (expect -1)")
cache.put(4, 40)
print(f"\nput(4,40): {cache}")
res = cache.get(1)
print(f"get(1): {res} (expect -1)")
res = cache.get(3)
print(f"get(3): {res} (expect 30)")
res = cache.get(4)
print(f"get(4): {res} (expect 40)")
|
2ef8a2626ce197fd6e23790494fdaf1c42b90ea8 | zkuser2002/Library_Application_Form_With_Tkinter | /frountend.py | 3,091 | 3.8125 | 4 | from tkinter import *
import backend
def clear_list():
list1.delete(0,END)
def fill_list(books):
for book in books:
list1.insert(END,book)
window=Tk()
window.title('Book Store')
#=================Labels=================
lbl1=Label(window,text='Title')
lbl1.grid(row=0,column=0)
lbl2=Label(window,text='Autor')
lbl2.grid(row=0,column=2)
lbl3=Label(window,text='Year')
lbl3.grid(row=1,column=0)
lbl4=Label(window,text='ISBM')
lbl4.grid(row=1,column=2)
#=================Entries=================
title_text=StringVar()
ent1=Entry(window,textvariable=title_text)
ent1.grid(row=0,column=1)
author_text=StringVar()
ent2=Entry(window,textvariable=author_text)
ent2.grid(row=0,column=3)
year_text=StringVar()
ent3=Entry(window,textvariable=year_text)
ent3.grid(row=1,column=1)
ISBM_text=StringVar()
ent4=Entry(window,textvariable=ISBM_text)
ent4.grid(row=1,column=3)
#=================Listbox=================
list1=Listbox(window,width=30,height=5)
list1.grid(row=2,column=0,rowspan=5,columnspan=2)
scrol1=Scrollbar(window)
scrol1.grid(row=2,column=2,rowspan=6)
list1.configure(yscrollcommand=scrol1.set)
scrol1.configure(command=list1.yview)
def get_selected_row(event):
global selected_book
if len(list1.curselection())>0:
index=list1.curselection()[0]
selected_book=list1.get(index)
#title
ent1.delete(0,END)
ent1.insert(END,selected_book[1])
#author
ent2.delete(0,END)
ent2.insert(END,selected_book[2])
#year
ent3.delete(0,END)
ent3.insert(END,selected_book[3])
#isbn
ent4.delete(0,END)
ent4.insert(END,selected_book[4])
list1.bind('<<ListboxSelect>>',get_selected_row)
#=================Button=================
def view_command():
clear_list()
books=backend.view()
fill_list(books)
btn1=Button(window,text='View All',width=12,command=lambda:view_command())
btn1.grid(row=2,column=3)
def search_command():
clear_list()
books=backend.search(title_text.get(),author_text.get(),year_text.get(),ISBM_text.get())
fill_list(books)
btn2=Button(window,text='Search Entry',width=12,command=search_command)
btn2.grid(row=3,column=3)
def add_command():
backend.insert(title_text.get(),author_text.get(),year_text.get(),ISBM_text.get())
view_command()
btn3=Button(window,text='Add Entry',width=12,command=lambda:add_command())
btn3.grid(row=4,column=3)
def update_command():
backend.update(selected_book[0],title_text.get(),author_text.get(),year_text.get(),ISBM_text.get())
view_command()
btn4=Button(window,text='Update Selected',width=12,command=update_command)
btn4.grid(row=5,column=3)
def delete_command():
backend.delete(selected_book[0])
view_command()
btn5=Button(window,text='Delete Selected',width=12,command=delete_command)
btn5.grid(row=6,column=3)
btn6=Button(window,text='Close',width=12,command=window.destroy)
btn6.grid(row=7,column=3)
view_command()
window.mainloop() |
0b1c59f9280ebb164202708f11dc7827d2de26c7 | Sanich11/QAP-6 | /PycharmProjects/Mod18/Task18_2_3.py | 590 | 3.546875 | 4 | """
Напишите программу, которая отправляет запрос на генерацию случайных текстов (используйте этот сервис -
https://baconipsum.com/api/). Выведите первый из сгенерированных текстов.
"""
import requests
import json
r = requests.get('https://baconipsum.com/api/?type=meat-and-filler')
r = json.loads(r.content)
# делаем из полученных байтов python объект для удобной работы
print(type(r))
print(r[0])
|
ac8d9e7836f84a6dec72bb0d808649aabe9f408c | devanshbhatia26/Library | /Trees/SegementTrees.py | 846 | 3.53125 | 4 | def build(node, start, end):
if start==end:
tree[node] = A[start]
else:
mid = (start+end)/2
build(2*node, start, mid)
build(2*node, mid+1, end)
tree[node] = tree[2*node]+tree[2*node+1]
def update(node, start, end, idx, val):
if start==end:
tree[node] += val
A[idx] += val
else:
mid = (start+end)/2
if idx>=start and idx<=mid:
update(2*node, start, mid, idx, val)
else:
update(2*node+1, mid+1, end, idx, val)
tree[node] = tree[2*node]+tree[2*node+1]
def query(node, start, end, l, r):
if r<start or end<l:
return 0
elif l<=start and end<=r:
return tree[node]
mid = (start+end)/2
p1 = query(2*node, start, mid, l, r)
p2 = query(2*node+1, mid+1, end, l r)
return p1+p2
|
7d6341cbbf098898504065360e3035f8291b3e8e | dorrabbkhan/sideprojects | /Alien Invasion/button.py | 1,392 | 3.6875 | 4 | """
Class file for button in Alien Invasion game
"""
import pygame.font
class Button:
"""
Class for button in Alien Invasion game
"""
def __init__(self, ai_game, msg):
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
# initialize screen
self.width, self.height = 500, 200
self.button_color = (100, 100, 100)
self.text_color = (240, 240, 240)
self.font = pygame.font.SysFont(None, 48)
# set the styling for the button and text
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.rect.center = self.screen_rect.center
# create button and position it
self._prep_msg(msg)
# add message to it
def _prep_msg(self, msg):
"""
Render text as image and add to button
"""
self.msg_image = self.font.render(
msg, True, self.text_color, self.button_color)
# render the msg text
self.msg_image_rect = self.msg_image.get_rect()
self.msg_image_rect.center = self.rect.center
# get the text's rect and position it to center of button
def draw_button(self):
"""
Draw button on screen
"""
self.screen.fill(self.button_color, self.rect)
self.screen.blit(self.msg_image, self.msg_image_rect)
# draw button on screen
|
f0dffdf4255710bdcd1dd23d93f7b55d404b6ffb | TdotA/Python_for_CS1 | /MyScripts/functions.py | 1,445 | 3.75 | 4 | import math
def area(n,a):
area = (a**2 * n )/4* math.tan(math.pi/n)
return area
#print(str(area(4,2)))
#print(str(area(3,2)))
#print(str(area(6,2)))
def is_leap_year (y):
if (y % 4) == 0 :
if (y % 100) == 0 :
if (y % 400) == 0 :
return True
else :
return False
else :
return True
else:
return False
#print(str(is_leap_year(2000)))
#print(str(is_leap_year(1900)))
def cake(m , f, s):
mf = f // 2
mm = m // 0.8
ms = s // 1.5
return min(mf,mm, ms)
#print(str(cake(5, 7, 3.5)))
def is_prime (n):
i = 2
if n == 2 :
return True
else:
while i <= math.floor(math.sqrt(n)) :
if (n % i) == 0 :
return (False)
break
elif n % i != 0 and i == n-1:
return True
break
else :
i+=1
#print (is_prime(17))
#print (is_prime(16))
def nth_prime (n):
if n == 1:
return 2
count = 1
i = 3
while count <= n:
if is_prime(i) == True :
count = count + 1
if count == n :
return i
i+=2
#print(str(nth_prime(10)))
def next_prime(n):
i = n + 1
while is_prime(i) == False :
if i % 2 == 0 :
i+=1
else :
i+=2
return i
#print (str(next_prime(20))) |
5a9f334f6f08aff691d55c38ba97a7b5eed3a78d | dominiquecuevas/hackbright-markov-chains | /markov.py | 3,390 | 4.125 | 4 | """Generate Markov text from text files."""
from random import choice
def open_and_read_file(file_path):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
# your code goes here
text_string = open(file_path).read()
# print(text_string)
# print(type(text_string))
# return "Contents of your file as one long string"
return text_string
def make_chains(text_string):
"""Take input text as string; return dictionary of Markov chains.
A chain will be a key that consists of a tuple of (word1, word2)
and the value would be a list of the word(s) that follow those two
words in the input text.
For example:
>>> chains = make_chains("hi there mary hi there juanita")
Each bigram (except the last) will be a key in chains:
>>> sorted(chains.keys())
[('hi', 'there'), ('mary', 'hi'), ('there', 'mary')]
Each item in chains is a list of all possible following words:
>>> chains[('hi', 'there')]
['mary', 'juanita']
>>> chains[('there','juanita')]
[None]
"""
chains = {}
# your code goes here
# use split() to get list of words
# loop over list
# assign tuple as keys and value as a list with next word
# use .get() to check if key in chains
# if key not in chains dictionary, make the value an empty list
# if key in chains dictionary, append to list
text_list = text_string.split()
for i in range(0, len(text_list) -2):
# makes bigram as tuple key
tuple_key = (text_list[i], text_list[i +1])
# next word after bigram
next_word_value = (text_list[i + 2])
### WORKING CODE USING IF-ELSE
# if tuple_key in chains:
# chains[tuple_key].append(next_word_value)
# else:
# chains[tuple_key] = [next_word_value]
### TEST CODE USING .GET()
chains[tuple_key] = chains.get(tuple_key, [])
chains[tuple_key].append(next_word_value)
return chains
def make_text(chains):
"""Return text from chains."""
words = list(choice(list(chains.keys()))) # get a list-like of keys, make the tuple-keys a list.
# choose random tuple-key and put its words in the words list
# your code goes here
while tuple(words[-2:]) in chains: # keeps looping until the last 2 words in words list aren't tuples in chains dictionary
next_tuple_key = (words[-2], words[-1]) # get the last 2 words from list and put in a tuple
next_value_as_list = chains[next_tuple_key] # use above tuple to return the chains dictionary's list/value
next_random_word_from_list = choice(next_value_as_list) # get random word from the returned list
words.append(next_random_word_from_list) # append the random word to words list
return " ".join(words)
input_path = "green-eggs.txt"
# Open the file and turn it into one long string
input_text = open_and_read_file(input_path)
# Get a Markov chain
chains = make_chains(input_text)
# Produce random text
random_text = make_text(chains)
print(random_text)
|
1b9d86514ac35b10e889d86c824fa366d019fa18 | novneetnov/Principles-Of-Computing---I | /week1/merge.py | 719 | 3.5625 | 4 | # url : http://www.codeskulptor.org/#user39_MMUT83KjKI_8.py
"""
Merge function for 2048 game.
"""
import test_merge
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
return_line = [0]
merge_flag = False
for elem in line:
if elem != 0:
if return_line[-1] == elem and merge_flag is False:
return_line[-1] = 2 * elem
merge_flag = True
continue
else:
return_line.append(elem)
merge_flag = False
return_line.pop(0)
zeros_lst = [0] * (len(line) - len(return_line))
return_line.extend(zeros_lst)
return return_line
test_merge.run_suite(merge) |
2faa13bcdf4fab5f3a7d03844666ba0d3a42464a | raquelmcoelho/object-oriented-programming | /Atividade02/Fila.py | 507 | 4.1875 | 4 | #Fila - FIFO(first in first out)
fila = []
n = int(input("quantos elementos terá sua fila? "))
#adicionar no tail
while len(fila) < n:
elemento = input("adicione o elemento: ")
fila.append(elemento)
print("sua fila agora está assim:")
[print(x) for x in fila]
#retirar na head
n1 = int(input("quantos elementos você deseja retirar?"))
for x in range(0, n1):
print("estamos retirando o elemento: ", fila[0])
fila.pop(0)
print("\nagora sua fila está assim")
[print(x) for x in fila] |
c5e4d0d68866a0114c78fabe23c3cce599e9d229 | KimNgan96/Fossil_Test | /question_3.py | 644 | 3.640625 | 4 | import threading
lock = threading.Lock()
class Car(threading.Thread):
def __init__(self, max_speed, door=4,wheel=5, seat=4):
threading.Thread.__init__(self)
self.door = door
self.wheel = wheel
self.seat = seat
self.max_speed = max_speed
def run(self):
lock.acquire()
for i in range(0, 10):
print(self.max_speed)
lock.release()
def info(self):
print('wheel = ' + str(self.wheel))
print('door = ' + str(self.seat))
print('seat = ' + str(self.seat))
return True
toyota = Car(100)
toyota.start()
bmw = Car(200)
bmw.start()
|
765b2e06f4c24d2619341977ef3a6d837f45f5a3 | sunminky/algorythmStudy | /알고리즘 스터디/개인공부/heap/Fueling.py | 765 | 3.625 | 4 | # https://www.acmicpc.net/problem/1826
import sys
import heapq
if __name__ == '__main__':
n_gasstation = int(sys.stdin.readline())
gasstations = sorted([tuple(map(int, sys.stdin.readline().split())) for _ in range(n_gasstation)],
key=lambda x: x[0])
destination, cur_fuel = map(int, sys.stdin.readline().split())
answer = 0
queue = []
gasstations.append((destination, 0))
for _distance, _fuel in gasstations:
while queue and cur_fuel < _distance:
answer += 1
_pop_fuel, _ = heapq.heappop(queue)
cur_fuel += -_pop_fuel
if cur_fuel < _distance:
answer = -1
break
heapq.heappush(queue, (-_fuel, _distance))
print(answer)
|
a7e390f55bb316c22ff6202c886090ba16bd3981 | rwieckowski/project-euler-python | /euler364.py | 802 | 3.625 | 4 | """
There are <var>N</var> seats in a row <var>N</var> people come after
each other to fill the seats according to the following rules
<ol type="1"><li>If there is any seat whose adjacent seats are not
occupied take such a seat</li><li>If there is no such seat and there
is any seat for which only one adjacent seat is occupied take such a
seat</li><li>Otherwise take one of the remaining available seats </li>
</ol>Let T<var>N</var> be the number of possibilities that <var>N
</var> seats are occupied by <var>N</var> people with the given rules
<BR /> The following figure shows T48<div align='center'>
<img src="project/images/p364_comf_dist.gif" />
"""
def euler364():
"""
>>> euler364()
'to-do'
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod() |
150d4e2d01df92118756aeadc72e28b21b4a6faa | Bollegala/bollegala.github.io | /lect/dm/python_basics.py | 1,024 | 3.53125 | 4 | import math
def get_vector(s):
words = s.split()
v = {}
for w in words:
v[w] = v.get(w, 0) + 1
return v
def cos(x, y):
total = 0
for word in x:
total += x[word] ** 2
x_norm = math.sqrt(total)
total = 0
for word in y:
total += y[word] ** 2
y_norm = math.sqrt(total)
overalp = 0
for word in x:
if word in y:
overalp += x[word] * y[word]
res = overalp / (x_norm * y_norm)
return res
def main():
L = [(1, "this is very exiting"), \
(-1, "boring movie. never watch again"), \
(1, "good animations"), \
(-1, "too crowded bad choice")]
fv = []
for (label, txt) in L:
fv.append((label, get_vector(txt)))
test = "this is a good movie"
test_vect = get_vector(test)
for (label, v) in fv:
print label, cos(v, test_vect)
F = open("myfile.txt")
txt = F.read()
F.close()
print txt
print fv
if __name__ == "__main__":
main()
|
b08cbd85c5a36a21b63ed25b5da6c6f34fc0dcdc | etangreal/compiler | /test/tests/05class/6496-test_class-object_006.py | 383 | 3.5 | 4 | class A(object):
def __init__( self ):
self.attr=776
def func( self ):
print self.attr
class B(object):
def __init__( self ):
self.attr=777
def func( self ):
print self.attr
class C(object):
def __init__( self ):
self.attr=778
def func( self ):
print self.attr
a=A()
a.func()
b=B()
b.func()
c=C()
c.func()
|
383e5708995d4e0486e661e2fe365677533ff6b6 | zhangda7/leetcode | /solution/_100_same_tree.py | 2,985 | 3.84375 | 4 | #-*- coding:utf-8 -*-
'''
Created on 2015/8/24
@author: dazhang
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#easy but ugly solution
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p == None and q == None:
return True
if p == None or q == None:
return False
if p.val != q.val:
return False
pnodes = []
pnodes.append(p)
qnodes = []
qnodes.append(q)
while(len(pnodes) > 0 and len(qnodes) > 0):
pnewNodes = []
pretVal = []
while(len(pnodes) > 0):
node = pnodes.pop(0)
if node == None:
continue
if node.left != None:
pnewNodes.append(node.left)
pretVal.append(node.left.val)
else:
pnewNodes.append(None)
pretVal.append(None)
if node.right != None:
pnewNodes.append(node.right)
pretVal.append(node.right.val)
else:
pnewNodes.append(None)
pretVal.append(None)
qnewNodes = []
qretVal = []
while(len(qnodes) > 0):
node = qnodes.pop(0)
if node == None:
continue
if node.left != None:
qnewNodes.append(node.left)
qretVal.append(node.left.val)
else:
qnewNodes.append(None)
qretVal.append(None)
if node.right != None:
qnewNodes.append(node.right)
qretVal.append(node.right.val)
else:
qnewNodes.append(None)
qretVal.append(None)
#print pretVal, qretVal
if len(pretVal) != len(qretVal):
return False
for i in range(len(pretVal)):
if pretVal[i] != qretVal[i]:
return False
pnodes = pnewNodes
qnodes = qnewNodes
if len(pnodes) != len(qnodes):
return False
return True
if __name__ == '__main__':
root = TreeNode(0)
l1 = TreeNode(1)
l2 = TreeNode(1)
l3 = TreeNode(2)
l4 = TreeNode(2)
l5 = TreeNode(5)
l6 = TreeNode(6)
root.left = l1
root.right = l2
l1.right = l3
l2.right = l4
#l2.right = None
#l5.left = l6
s = Solution()
print(s.isSameTree(root, l1))
pass |
7007162486b50ef838a5e69bae26c319f9436782 | yagnyasridhar/Python | /Training/1.py | 1,714 | 4.25 | 4 | '''
print("Hello, World!")
'''
#comment
#print("Hello, World!")
#indentation
'''
i = 12
if type(i) == type(1):
print("wow")
'''
#variable
'''
i = "sample"
y = 10
print(y+i)
'''
'''
i = "awesome"
def func():
global i
i = "value"
print(i)
func()
print(i)
'''
#pass
'''
def func():
pass
func()
'''
# data type
'''
print(type(12.3))
print(type(12j))
print(type("sasas"))
'''
#casting
'''
i = "sample"
y = 10
print(str(y)+" "+i)
'''
#string
a = "Hello, World!"
b = "hello world"
print(a.upper())
print(b.title())
print(a[0])
print(a[:4])
print(a[0:-2])
print(a.split(","))
print(a[::-1])
#list
'''
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
print(thislist[0:2])
thislist.append("mango")
print(thislist)
thislist.insert(1, "grapes")
print(thislist)
thislist.pop()
print(thislist)
thislist.remove("banana")
print(thislist)
list2 = ["orange"]
thislist.extend(list2)
print(thislist)
'''
#tuple
'''
thistuple = ("apple", "banana", "cherry")
print(thistuple)
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
print(thistuple[2:3])
'''
#range
'''
x = range(3, 20, 2)
for n in x:
print(n)
'''
#input
'''
username = input("Enter username:")
print("Username is: " + username)
'''
#formating
'''
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
'''
#palindrome
'''
str = input("Enter a string: ")
if(str == str[::-1]):
print("palindrome")
else:
print("not palindrome")
'''
|
9e1c37b5c05cb2cc6e018ff4a25e6075796cd32a | sacsachin/programing | /repeat_and_missing_num.py | 470 | 3.546875 | 4 | # !/usr/bin/python3
"""
https://www.interviewbit.com/problems/repeat-and-missing-number-array/
Repeat and Missing Number Array
"""
def solve(A):
n = len(A)
for i in range(n):
if A[abs(A[i])-1] > 0:
A[abs(A[i])-1] = -A[abs(A[i])-1]
else:
missing = abs(A[i])
print(A)
return [missing, A.index(max(A))+1]
if __name__ == "__main__":
A = [(lambda x: int(x))(x) for x in input().split(", ")]
print(solve(A))
|
a882ec79859cfb4030881e1e6dbcdb9cdc9b8a3b | ayazhemani/interview_prep | /minesweeper/minesweeper.py | 5,338 | 3.546875 | 4 | """Solution for Minesweeper Game
"""
from random import randint
import os
class Minesweeper:
def __init__(self, width, height):
self.difficulty = 0.05
self.height = height
self.width = width
self.board = [[None] * width for x in xrange(height)]
self.unhidden_board = [[None] * width for x in xrange(height)]
self.game_won = False
self.game_ended = False
self.create_board()
return
def is_game_won(self):
for i in xrange(self.width):
for j in xrange(self.height):
if self.board[i][j] == '*' and self.unhidden_board[i][j] != 'f':
self.game_won = False
return self.game_won
self.game_won = True
self.game_ended = True
return self.game_won
def print_board(self):
output = ''
for line in self.board:
for block in line:
if block == 0:
output = output + '- '
else:
output = output + str(block) + ' '
output = output + '\n'
print output
return output
def print_secret_board(self):
"""Print values for unhidden board
User indicated "Flagged" mine with 'F'
User indicates "Cleared" block with 'C'
"""
print '-'*(self.width*2+2)
for i in xrange(self.width):
print '|',
for j in xrange(self.height):
if self.unhidden_board[i][j] == 'c':
if self.board[i][j] == 0:
print '-',
else:
print self.board[i][j],
elif self.unhidden_board[i][j] == 'f':
print self.unhidden_board[i][j],
else:
print ' ',
print '|'
print '-'*(self.width*2+2)
def clear_zeroed_neighbors(self, x, y):
#check if block has of value 0 and set view to cleared
self.unhidden_board[x][y] = 'c'
for i in xrange(-1, 2):
for j in xrange(-1, 2):
new_x = x + i
new_y = y + j
if (new_x == x and new_y == y) or \
(new_x >= self.width or new_x < 0) or \
(new_y >= self.height or new_y < 0):
continue
else:
if self.unhidden_board[new_x][new_y] != 'c':
self.unhidden_board[new_x][new_y] = 'c'
if self.board[new_x][new_y] == 0:
self.clear_zeroed_neighbors(new_x, new_y)
return
def create_board(self):
"""Populate board with Hidden Mines according to difficulty
Ensure at least one mine is present in game
Returns:
board: Description
"""
#Determine number and placement of mines
num_of_mines = int(self.difficulty * self.height * self.width + 1)
for i in xrange(num_of_mines):
self.board[randint(0, self.width - 1)][randint(0, self.width - 1)] = '*'
#Populate board with number hints
for x in xrange(self.width):
for y in xrange(self.height):
score = 0
for i in xrange(-1, 2):
for j in xrange(-1, 2):
new_x = x + i
new_y = y + j
if (new_x == x and new_y == y) or \
(new_x >= self.width or new_x < 0) or \
(new_y >= self.height or new_y < 0):
continue
if self.board[new_x][new_y] == '*':
score += 1
if self.board[x][y] != '*':
self.board[x][y] = score
return self.board
def minesweeper_game(game):
"""Main loop for minesweeper game
"""
x, y, val = 0, 0, None
warning = False
while not game.game_ended:
os.system("clear")
print "Guess can be 'c' to clear or 'f' to flag a mine"
if warning:
print "INVALID GUESS!! PLEASE TRY AGAIN"
warning = False
game.print_secret_board()
guess = list(raw_input("Enter the [y, x, guess] values:").split(','))
if guess[2] != 'c' and guess[2] != 'f':
warning = True
else:
game.unhidden_board[int(guess[0])][int(guess[1])] = guess[2]
if guess[2] == 'c' and game.board[int(guess[0])][int(guess[1])] == 0:
game.clear_zeroed_neighbors(int(guess[0]), int(guess[1]))
elif guess[2] == 'c' and game.board[int(guess[0])][int(guess[1])] == '*':
game.game_ended = True
game.is_game_won()
if game.game_won:
os.system("clear")
print "YOU WON THE GAME!!"
else:
os.system("clear")
print "YOU LOSE! :'("
return
def main():
"""Receives input from stdin, provides output to stdout.
"""
height = 10
width = 10
try:
width, height = map(int,raw_input("Input the size of the board (width, height):").split(','))
except:
pass
new_game = Minesweeper(width, height)
minesweeper_game(new_game)
if __name__ == '__main__':
main()
|
a21a4a5504f7796b4525c73cab8d797ebd2d53b9 | yakobie/homework | /exercise 10/tenth.py | 337 | 3.890625 | 4 | import random
user = raw_input("Guess a number between 1 and 20, type exit to exit: ")
while user != "exit":
a = random.randint(1, 5)
user = raw_input("Guess a number between 1 and 20, type exit to exit: ")
if user == a:
print('You win! :)')
a = random.randint(1, 5)
else:
print('Nope...')
a = random.randint(1, 5)
|
ec69309fb64895e8b857f5cea9882c7b950e0978 | garciaha/DE_daily_challenges | /2020-07-20/num_char.py | 1,435 | 4.15625 | 4 | """Numbers First, Letters Second
Write a function that sorts list while keeping the list structure. Numbers should be first then letters both in ascending order.
Examples
num_then_char([
[1, 2, 4, 3, "a", "b"],
[6, "c", 5], [7, "d"],
["f", "e", 8]
]) -> [
[1, 2, 3, 4, 5, 6],
[7, 8, "a"],
["b", "c"], ["d", "e", "f"]
]
Notes
Test cases will containg integer and float numbers and single letters.
"""
def num_then_char(arrays):
lengths = [len(x) for x in arrays]
sorted_array = sum(arrays, [])
sorted_array = sorted([x for x in sorted_array if type(x) is not str]) + sorted([x for x in sorted_array if type(x) is str])
result = []
for x in lengths:
current = []
for x in range(x):
current.append(sorted_array.pop(0))
result.append(current)
return result
if __name__ == '__main__':
assert num_then_char([
[1, 2, 4, 3, "a", "b"],
[6, "c", 5], [7, "d"],
["f", "e", 8]
]) == [
[1, 2, 3, 4, 5, 6],
[7, 8, "a"],
["b", "c"], ["d", "e", "f"]
]
assert num_then_char([
[1, 2, 4.4, "f", "a", "b"],
[0], [0.5, "d", "X", 3, "s"],
["f", "e", 8],
["p", "Y", "Z"],
[12, 18]
]) == [
[0, 0.5, 1, 2, 3, 4.4],
[8],
[12, 18, "X", "Y", "Z"],
["a", "b", "d"],
["e", "f", "f"],
["p", "s"]
]
print("All cases passed!")
|
21a3503024d4dc3c7411ee15ee37bb34b5b5471e | peterhchen/runBookAuto | /code/example/13_ListGen/04_Comprehen.py | 159 | 3.796875 | 4 | #!/usr/bin/python3
'''
Generate a lis of 10 values
Multiple them by 2
Return multiples of 8
'''
print ([x for x in [i * 2 for i in range(10)] if x % 8 == 0])
|
5c1ca2069230bac5ac6bdd32d782d9d798d52c2b | soumasish/leetcodely | /python/paint_house.py | 1,628 | 3.765625 | 4 | """Created by sgoswami on 7/29/17."""
"""There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of
painting each house with a certain color is different. You have to paint all the houses such that no two adjacent
houses have the same color.
The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0]
is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green,
and so on... Find the minimum cost to paint all houses."""
class Solution(object):
def minCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
# Greedy approach will not yield an optimum solution here
if not costs:
return 0
F = costs[0]
curr = [0] * 3
for i in range(1, len(costs)):
curr[0] = min(F[1], F[2]) + costs[i][0]
curr[1] = min(F[0], F[2]) + costs[i][1]
curr[2] = min(F[0], F[1]) + costs[i][2]
F = curr[:]
return min(F)
# if not costs:
# return 0
# f = costs[0]
# curr = [0] * 3
#
# for i in range(1, len(costs)):
# curr[0] = min(f[1], f[2]) + costs[i][0]
# curr[1] = min(f[0], f[2]) + costs[i][1]
# curr[2] = min(f[0], f[1]) + costs[i][2]
# f = curr[:]
# return min(f)
if __name__ == '__main__':
solution = Solution()
print(solution.minCost([[5, 8, 6], [19, 14, 13], [7, 5, 12], [14, 15, 17], [3, 20, 10]])) |
7249beac71d56639fd3ef819f0a58f94698dfe58 | GuilhermeFA00/WeatherDTS_project | /main.py | 1,567 | 4.03125 | 4 | #Reading csv file
import pandas as pd
data = pd.read_csv(r"C:\Users\Usuario\Desktop\I.A. lrn_path\DataScy_Learning\WeatherDTS_project\WeatherDataM.csv")
#Pre-processing
from sklearn import preprocessing
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
weather_features = ['Temperature (C)', 'Wind Speed (km/h)', 'Pressure (millibars)']
#"a" for input columns
a = data[weather_features]
#"b" for output columns
b = data.Humidity
#plot test
#Let's see which feature together with humidity have a good linear regression relationship
import matplotlib.pyplot as plt
plt.subplot(2,2,1)
plt.scatter(a['Temperature (C)'],b)
plt.subplot(2,2,2)
plt.scatter(a['Wind Speed (km/h)'],b)
plt.subplot(2,2,3)
plt.scatter(a['Pressure (millibars)'],b)
#plt.show()
#Humidity against Pressure forms no linear relationship
#Let's delete it from the model
a = a.drop("Pressure (millibars)", 1)
#Now a 3D plot
from mpl_toolkits.mplot3d import axes3d
img = plt.figure()
ax = img.add_subplot(111, projection='3d')
x1 = a["Temperature (C)"]
x2 = a["Wind Speed (km/h)"]
ax.scatter(x1, x2, b, c='r', marker='o')
ax.set_xlabel('Temperature (C)')
ax.set_ylabel('Wind Speed (km/h)')
ax.set_zlabel('Humidity')
#plt.show()
#Implement our Multiple Linear Regression Model
from sklearn.linear_model import LinearRegression
lr_Model = LinearRegression()
#ŷ = θ₀– θ₁𝑥¹- θ₂𝑥²
lr_Model.fit(a, b)
#Use our Multiple Linear Regression Model to make predictions
b_pred = lr_Model.predict([[4, 11]])
print(b_pred) |
d3adc7c557b18c69b8abde7be34ae9e11b1ada5b | k4u5h4L/algorithms | /leetcode/Word_Search.py | 1,515 | 3.875 | 4 | '''
Word Search
Medium
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
'''
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == word[0] and self.dfs(board, i, j, 0, word):
return True
return False
def dfs(self, board, i, j, count, word):
if count == len(word):
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[i]) or board[i][j] != word[count]:
return False
temp = board[i][j]
board[i][j] = " "
found = self.dfs(board, i+1, j, count+1, word) or self.dfs(board, i-1, j, count+1, word) or self.dfs(board, i, j+1, count+1, word) or self.dfs(board, i, j-1, count+1, word)
board[i][j] = temp
return found
|
ce6d705fec6ff297d36bb190ce5f8d1f5e58a049 | lxh0019/AID2003 | /day1/fork.py | 505 | 3.703125 | 4 | """
创建二级子进程处理僵尸
"""
from os import *
from time import *
def f1():
for i in range(3):
sleep(2)
print("写代码")
def f2():
for i in range(2):
sleep(4)
print("测代码")
pid = fork()
if pid < 0:
print("Create process failed")
elif pid == 0:
p = fork() # 创建二级子进程
if p == 0:
f1()
else:
_exit(0) # 一级子进程退出
else:
pid, status = wait() # 等待回收一级子进程
f2()
|
5bd2273d3b638db81170098428bbf7766db8af52 | benkadiayi/HWW2D3 | /md.py | 390 | 4.125 | 4 | class area():
def __init__(self,length,width):
self.length = length
self.width = width
self.area = length * width
print (f"Your area is {self.area}square foot")
class circumference():
def __init__ (self,radius):
self.radius = radius
self.circ = 2 * radius * 3.14
print (f'The circumference of your circle is {self.circ}feet') |
1a5363884a7ff5674fa59ec74fc144e9f4e6c0f9 | bcheney21/git_practice_2 | /general-assembly/unit4/w1/d3/solution.py | 312 | 4.1875 | 4 | greeting_dictionary = {
'english': 'Hello!',
'spanish': 'Hola!',
'french': 'Bonjour!'
}
user_input = input('please enter a language: english, spanish, or french\n').lower()
for key, value in greeting_dictionary.items():
if key == user_input:
print_greeting = value
print(print_greeting) |
90a9a4e4eee2cbecc9660adfae3ab72b9c1535b4 | debryc/LPTHW | /ex15.4.py | 402 | 3.75 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your %r file: " % filename
print txt.read()
# Why doesn't the script stop and ask me for another argument?
print "Write the file name in the command line again."
from sys import argv
script, filename_again = argv
txt_again = open(filename_again)
print "Here's your %r file again: " % filename
print txt_again.read() |
8556169f2bae7bbde9b88ef3486023d881d7e202 | tonycmooz/git-practice | /test.py | 1,218 | 3.59375 | 4 | import csv
import json
class TestClass(object):
def __init__(self, foo, bar, baz):
self.foo = foo
self.bar = bar
self.baz = baz
def fizz_buzz(self, digit_1, digit_2):
for i in range(1, 100):
if i % digit_1 == 0:
if i % digit_2 == 0:
print 'fizzbuzz!'
else:
print 'fizz!'
elif i % digit_2 == 0:
print 'buzz!'
else:
print i
def bubble_sort(self, alist):
length = len(alist) - 1
for i in range(0, length):
if alist[i] > alist[i + 1]:
# alist[i], alist[i+1] = alist[i+1], alist[i] # python way
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
def json_to_csv(self, json_file_path, outfile_path):
"""DictWriter has saved my life!!!
"""
with open(json_file_path) as f:
data = json.load(f)
with open(outfile_path, 'w') as fp:
writer = csv.writer(fp)
writer.writerow(data[0].keys())
for item in data:
writer.writerow(item.values())
|
e1baeac08ad198a1fd322eb280ac487c7770878d | mike03052000/python | /Training/HackRank/mike/while-1.py | 342 | 4 | 4 | numbers = [11, 22, 33, 44, ]
print('before: %s' % (numbers,))
def test_while():
idx = 0
while idx < len(numbers):
numbers[idx] *= 2
idx += 1
print('after: %s' % (numbers))
test_while()
def enumerate1(x):
v=[]
for idx,val in enumerate(x):
v.append(idx+val)
print('v=',v)
enumerate1(numbers)
|
fd2c7b79022b8a8fc94c4ee12b94222684261fe9 | quarkgluant/boot-camp-python | /day03/ex03/ColorFilter.py | 7,275 | 3.703125 | 4 | #!/usr/bin/env python3
# -*-coding:utf-8 -*
import numpy as np
class ColorFilter:
"""a tool that can apply a variety of color filters on images.
For this exercise, the authorized functions and operators are specified for each methods. You
are not allowed to use anything else."""
def _dtype_to_int(selfself, array):
if array.dtype == np.float32: # Si le résultat n'est pas un tableau d'entiers
array = (array * 255).astype(np.uint8)
if array.dtype == np.float64: # Si le résultat n'est pas un tableau d'entiers
array = (array * 255 * 255).astype(np.uint16)
return array
def _blue_mask(self, array):
array = self._dtype_to_int(array)
shape_mask = [array.shape[0], array.shape[1], array.shape[2] - 1]
return np.zeros(shape_mask, dtype=array.dtype)
def _shading(self, colors, thresholds):
val_threshold = 256 // thresholds
for index, val in enumerate(colors):
for i in range(thresholds):
if val_threshold * i <= val < val_threshold * (i + 1):
colors[index] &= val_threshold * i
# if val < 64:
# colors[index] &= 64 * (thresholds - 4)
# elif 64 <= val < 128:
# colors[index] &= 64 * (thresholds - 3)
# elif 128 <= val < 192:
# colors[index] &= 64 * (thresholds - 2)
# elif val >= 192 :
# colors[index] = 64 * (thresholds - 1)
def invert(self, array):
"""Takes a NumPy array of an image as an argument and returns an array with inverted color.
Authorized function : None
Authorized operator: -
"""
array = self._dtype_to_int(array)
return -array
def to_blue(self, array):
"""Takes a NumPy array of an image as an argument and returns an array with a blue filter.
Authorized function : .zeros, .shape
Authorized operator: None
"""
array = self._dtype_to_int(array)
mask = self._blue_mask(array)
array[:, :, :2] = mask
return array
def to_green(self, array):
"""Takes a NumPy array of an image as an argument and returns an array with a green filter.
Authorized function : None
Authorized operator: *
"""
return array[:, :, :] * [0, 1, 0]
def to_red(self, array):
"""Takes a NumPy array of an image as an argument and returns an array with a red filter.
Authorized function : None
Authorized operator: *
"""
return array[:, :, :] * [1, 0, 0]
def to_celluloid(self, array, n=4):
"""Takes a NumPy array of an image as an argument, and returns an array with a celluloid shade filter.
The celluloid filter must display at least four thresholds of shades. Be careful! You are not
asked to apply black contour on the object here (you will have to, but later...), you only have to
work on the shades of your images.
Authorized function: arange, linspace
Bonus: add an argument to your method to let the user choose the number of thresholds.
Authorized function : .vectorize, (.arange?)
Authorized operator: None
"""
array = self._dtype_to_int(array)
# vfunc = np.vectorize(self._shading)
for ext_array in array:
for colors in ext_array:
self._shading(colors, n)
# vfunc(colors, n)
return array
def to_grayscale(self, array, filter="w"):
"""Takes a NumPy array of an image as an argument and returns an array in grayscale. The method takes another
argument to select between two possible grayscale filters. Each filter has specific authorized functions and operators.
* 'mean' or 'm' : Takes a NumPy array of an image as an argument and returns an array in grayscale created
from the mean of the RBG channels.
Authorized function : .sum, .shape, reshape, broadcast_to, (as_type?)
Authorized operator: /
* 'weighted' or 'w' : Takes a NumPy array of an image as an argument and returns an array in weighted grayscale.
This argument should be selected by default if not given.
The usual weighted grayscale is calculated as : 0.299 * R_channel + 0.587 * G_channel + 0.114 * B_channel.
Authorized function : .sum, .shape, .tile
Authorized operator: *
"""
if filter.startswith("m"):
# on fait la somme selon l'axe z, donc la somme des 3 nombres RGB:
arr_sum = np.sum(array, axis=2)
# arr_sum.shape => (200, 200), donc on transforme cette matrice pour en faire (200, 200, 1):
arr_resh = np.reshape(arr_sum, (200, 200, 1))
# ne reste plus qu'à cloner 3 fois la valeur en z, pour avoir une array de (200, 200, 3):
arr_br = np.broadcast_to(arr_resh, (200, 200, 3))
# étape finale, on divise par le nombre de couleurs:
arr_mean = arr_br[:,:,:] / array.shape[2]
return arr_mean
elif filter.startswith("w"):
# on multiplie les couleurs RGB par les coefficients, puis on somme le tout
arr_sum = np.sum(array[:, :, :] * [0.299, 0.587, 0.114], axis=2)
# arr_sum.shape => (200, 200), donc on crée une 3e dim avec arr_sum[:, :, None]
# et avec np.tile, on remplit cette 3e dimensions
arr_w = np.tile(arr_sum[:, :, None], (1, 1, 3))
return arr_w
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
class ImageProcessor:
def load(self, path):
"""opens the .png file specified by the path argument and returns an array
with the RGB values of the image pixels. It must display a message specifying
the dimensions of the image (e.g. 340 x 500)."""
img = mpimg.imread(path)
# if img.dtype == np.float32: # Si le résultat n'est pas un tableau d'entiers
# img = (img * 255).astype(np.uint8)
print(f"Loading image of dimensions {img.shape[0:2]}")
return img
def display(self, array):
"""takes a NumPy array as an argument and displays the corresponding RGB image."""
plt.imshow(array)
plt.show()
if __name__ == '__main__':
# from ImageProcessor import ImageProcessor
imp = ImageProcessor()
arr = imp.load("../ressources/42AI.png")
print(f"type of arr: {arr.dtype}")
# Loading image of dimensions 200 x 200
# from ColorFilter import ColorFilter
cf = ColorFilter()
invert_arr = cf.invert(arr)
print("première case de arr:")
print(arr[ 1, 1, :])
print("première case de invert_arr:")
print(invert_arr[ 1, 1, :])
imp.display(invert_arr)
imp.display(cf.to_green(arr))
imp.display(cf.to_red(arr))
imp.display(cf.to_blue(arr))
imp.display(cf.to_celluloid(arr))
imp.display(cf.to_celluloid(arr, 8))
imp.display(cf.to_celluloid(arr, 2))
imp.display(cf.to_grayscale(arr, 'm'))
imp.display(cf.to_grayscale(arr, 'weigthed')) |
e996cb3a023c6c7c2ff1e8ecb9e2f9a1913b6760 | carloswm85/2021-cs111-programming-with-functions | /w10-handling-exceptions/prove-handling-exceptions/receipt.py | 3,065 | 3.875 | 4 | import csv
from datetime import datetime
def main():
products_file = "E:/GitHub/2021-cs111-programming-with-functions/w10-handling-exceptions/prove-handling-exceptions/products.csv"
products = read_products(products_file)
print('>>> Inkom Emporium <<<')
# print('Products:')
# for number, product in products.items(): # This loop is going to print a dictionary
# print(number, product)
requests_file = "E:/GitHub/2021-cs111-programming-with-functions/w10-handling-exceptions/prove-handling-exceptions/request.csv"
process_request(requests_file, products_file)
def read_products(file):
"""
Reads file into a dictionary.
"""
print()
products = {}
try:
with open(file, "rt") as infile:
reader = csv.reader(infile)
next(reader)
for line in reader:
product_number = line[0]
product_name = line[1]
product_price = line[2]
products[product_number] = [product_name, product_price]
except KeyError as key_err:
print(
f"Error: line {reader.line_num} of {file.name} is formatted incorrectly.")
# If we write code that attempts to find a key in a dictionary and that key doesn't exist in the dictionary.
print(key_err)
except FileNotFoundError as file_not_found_err:
print(f"Error: cannot open {file} because it doesn't exist.")
print(file_not_found_err)
exit()
except PermissionError as perm_err:
print(
f"Error: cannot read from {file} because you don't have permission.")
print(perm_err)
exit()
return products
def process_request(requests_file, products_file):
product_dic = read_products(products_file)
current_date = datetime.now()
with open(requests_file, "rt") as infile:
reader = csv.reader(infile)
next(reader)
print('Requested items:')
number_items = 0
total = 0
sub_total = 0
sales_tax_rate = 0.06
for line in reader:
product_number = line[0]
product_quantity = line[1]
quantity = int(product_quantity)
if product_number in product_dic.keys():
product = product_dic[product_number]
name = product[0]
price = float(product[1])
print(f'{name}: {product_quantity} @ {price}')
sub_total = sub_total + quantity * price
number_items = number_items + quantity
print(f'\nNumber of Items: {number_items}')
print(f'Subtotal: {sub_total}')
sales_tax = sales_tax_rate * sub_total
print(f'Sales Tax: {sales_tax:.2f}')
total = sub_total + sales_tax
print(f'Total: {total:.2f}')
print('\nThank you for shopping at the Inkom Emporium')
# Formatting date and time https://stackoverflow.com/a/63061189/7389293
print(f'{current_date:%A %d, %Y, %I:%M %p}')
if __name__ == "__main__":
main()
|
1fa4edf8f99ef1ac2473221e91c4a47ed37ee860 | 13424010187/python | /源码/【11】循环圣诞树-课程资料/11.py | 1,659 | 4.1875 | 4 | ''''''
'''
*在不同数据类型下的使用:在字符串:倍数 在数字类型:乘号
遍历:逐个访问
序列:一组数据
遍历序列:逐个访问一组数据的每个元素
for循环:已知循环次数的循环,常用来遍历
while循环:未知循环次数的循环,符合条件就行,很少用来遍历
for循环:for 变量 in 序列:
range()方法:start:默认为0 stop:不包括stop本身 step:步长,默认为1
'''
'''while循环实现圣诞树'''
# number=int(input('please input a number :'))
# i=1
# while i<=number:
# print(' '*(number-i)+'*'*(i*2-1))
# i+=1
# j=1
# while j<=number//2:
# print(' '*(number-2)+'*'*3)
# j+=1
'''for循环实现圣诞树'''
# number=int(input('please input a number :'))
# for i in range(1,number+1):
# print(' '*(number-i)+'*'*(i*2-1))
# for j in range(1,number//2+1,):
# print(' '*(number-2)+'*'*3)
'''挑战:for循环实现分层圣诞树'''
# number=int(input('please input a number :'))
# y=1
# for i in range(1,number+1):
# print(' '*(number-y)+'*'*(y*2-1))
# if i%5==0:
# y-=2
# else:
# y+=1
# for j in range(1,number//2+1,):
# print(' '*(number-2)+'*'*3)
'''范围内的水仙花数:使用for循环'''
# a1=int(input('input a number1:'))
# a2=int(input('input a number2:'))
# for a1 in range(a1,a2+1):
# #判断a1是不是水仙花数
# s=0
# astr=str(a1)
# for i in range(len(astr)):
# s+=int(astr[i])**3
# if s==a1:
# print(a1,'yes')
'''----------------------------------------------------------------------------------------------'''
|
dc4f1bc96ae3f24670b289cfe52626df67206b70 | Alexanderklau/hackerRank_test | /test_project.py | 870 | 3.984375 | 4 | # -*-coding:utf-8 -*-
__author__ = 'Yemilice_lau'
# def print_formatted(number):
# width = len("{0:b}".format(number))
# for i in range(1, n + 1):
# # print("{0:{width}d}".format(i,width=width))
# print("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width))
#
# # your code goes here
#
# if __name__ == '__main__':
# n = int(input())
# print_formatted(n)
import string
a = string.ascii_lowercase
#小写字母
# b = int(input())
# L = []
# for i in range(b):
# s = "-".join(a[i:b])
# L.append(s[::-1] + s[1:]).center()
# #center() 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格
# print(L)
# # print(s)
# # print(a)
s = input()
for x in s[:].split():
s = s.replace(x, x.capitalize())
print(s)
# if __name__ == '__main__': |
60a60eb4b62884547b8ccf65709a8a263cabb7f7 | sarck1/RoadPython | /chapter010/chapter_01004.py | 1,527 | 4.28125 | 4 | # 类的继承
class BaseClass:
"""基类"""
# 成员变量
def __init__(self, age, name, job): # 特殊函数:双下划线开始+双下划线结束,系统定义的特殊函数,不能在类外部访问
self.age = age # 公有成员: 对所有人公开,可以在类的外部直接访问
self._name = name # 保护成员:不能够通过 "from module import *" 的方式导入
self.__job = job # 私有成员:双下划线开始,无双下划线结束;类的外部不能直接访问,需要调用类的公开成员方法访问
print("BaseClass init")
# 成员函数
def get_age(self):
print(self.age)
return self.age
def set_age(self, age):
self.age = age
print(age)
# 保护成员函数
def _get_name(self):
return self._name
# 私有成员函数
def __get_job(self):
return self.__job
# 派生类
class DriverdClass(BaseClass):
def __init__(self, age, name, job, cardno):
BaseClass.__init__(self, age, name, job)
self.cardno = cardno
print("DriverdClass init")
def get_age(self):
print("DriverdClass get_age")
def main():
# 有参数的对象声明
mycls = DriverdClass(20, "张子良", "Python全栈工程师", "SVIP_0001")
mycls.get_age() # 增加重载的情况
print(mycls._name)
mycls._get_name() # 访问保护成员函数
# 执行主函数
if __name__ == '__main__':
main() |
e64ec18bc9e744298a5b7041fad45dedf48b260e | tangdoufeitang/leetcode | /Python/29.divide-two-integers.py | 1,482 | 4.09375 | 4 | from __future__ import print_function
# 29. Divide Two Integers
# Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
# Return the quotient after dividing dividend by divisor.
# The integer division should truncate toward zero.
# Example 1:
# Input: dividend = 10, divisor = 3
# Output: 3
# Example 2:
# Input: dividend = 7, divisor = -3
# Output: -2
# Note:
# Both dividend and divisor will be 32-bit signed integers.
# The divisor will never be 0.
# Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range:
# [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
neg = ((dividend < 0) != (divisor < 0))
dividend = dive = abs(dividend)
divisor = divs = abs(divisor)
ans = 0
Q = 1
if dive < divs:
return 0
else:
while dive > divs:
dive -= divs
ans += Q
divs += divs
Q += Q
if dive < divs:
Q = 1
divs = divisor
if neg:
max(-ans, -2147483648)
else:
min(ans, 2147483647)
if __name__ == '__main__':
print(Solution().divide(75,7)) |
275652e0b654a516f0433e58c023b160863e264a | YancyWei/YancyWorld | /循环队列/循环队列.py | 2,997 | 4.21875 | 4 | """
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。
循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
你的实现应该支持如下操作:
MyCircularQueue(k): 构造器,设置队列长度为 k 。
Front: 从队首获取元素。如果队列为空,返回 -1 。
Rear: 获取队尾元素。如果队列为空,返回 -1 。
enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
isEmpty(): 检查循环队列是否为空。
isFull(): 检查循环队列是否已满。
"""
class MyCircularQueue:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the queue to be k.
"""
self.size = k
self.queue = [-1] * k
self.head = -1
self.tail = -1
def enQueue(self, value: int) -> bool:
"""
Insert an element into the circular queue. Return true if the operation is successful.
"""
if self.isFull():
return False
if self.isEmpty():
self.head = 0
self.tail = (self.tail + 1) % self.size
self.queue[self.tail] = value
return True
def deQueue(self) -> bool:
"""
Delete an element from the circular queue. Return true if the operation is successful.
"""
if self.isEmpty():
return False
if self.head == self.tail:
self.head = -1
self.tail = -1
return True
self.head = (self.head + 1) % self.size
return True
def Front(self) -> int:
"""
Get the front item from the queue.
"""
return self.queue[self.head] if not self.isEmpty() else -1
def Rear(self) -> int:
"""
Get the last item from the queue.
"""
return self.queue[self.tail] if not self.isEmpty() else -1
def isEmpty(self) -> bool:
"""
Checks whether the circular queue is empty or not.
"""
return self.head == -1
def isFull(self) -> bool:
"""
Checks whether the circular queue is full or not.
"""
return (self.tail + 1) % self.size == self.head
# Your MyCircularQueue object will be instantiated and called as such:
obj = MyCircularQueue(3)
p1 = obj.enQueue(1)
p2 = obj.enQueue(2)
p3 = obj.enQueue(3)
p4 = obj.enQueue(4)
p5 = obj.Rear()
p6 = obj.isFull()
p7 = obj.deQueue()
p8 = obj.enQueue(4)
p9 = obj.Rear()
print([p1, p2, p3, p4, p5, p6, p7, p8, p9])
|
627bdd2b9b779002274765f3925b9d1cbc143bd8 | ricardoBpinheiro/PythonExercises | /Desafios/desafio066.py | 197 | 3.765625 | 4 | n = 0
cont = 0
soma = 0
while True:
n = int(input('Digite um numero (999 para sair): '))
if n == 999:
break
soma += n
cont += 1
print(f'A soma dos {cont} valores é {soma}') |
ed26ac19ec3096e369a83bb327861f3baf19ee01 | MCaldwell-42/classes | /classes.py | 1,066 | 3.984375 | 4 | class Pizza:
def __init__(self):
# Establish the properties of each pizza
# with a default value
self.size = ""
self.style = ""
self.crust = ""
self.toppings = []
def add_topping(self, topping):
self.toppings.append(topping)
print(f"added {topping} to toppings")
def print_order(self):
tops = ""
list_length = len(self.toppings)
for food in self.toppings:
if self.toppings.index(food) < list_length-1:
tops += f"{food} and "
else:
tops += f"{food}"
print(f"I would like a {self.size}-in, {self.style} pizza with {tops}.")
meat_lovers = Pizza()
meat_lovers.size = 16
meat_lovers.style = "Deep dish"
meat_lovers.add_topping("Pepperoni")
meat_lovers.add_topping("Sausage")
meat_lovers.print_order()
cheese_lovers = Pizza()
cheese_lovers.size = 16
cheese_lovers.style = "thin crust"
cheese_lovers.add_topping("Pepperoni")
cheese_lovers.add_topping("Extra Cheese")
cheese_lovers.print_order() |
8e1b298679ba890b6ebea48a266b68f25d2e1354 | mahimadubey/leetcode-python | /different_ways_to_add_parentheses/solution.py | 1,395 | 4.25 | 4 | """
Given a string of numbers and operators, return all possible results from
computing all the different possible ways to group numbers and operators. The
valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
"""
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
self.operators = set(['+', '-', '*'])
return self.diff_ways(input)
def calculate(self, a, b, operator):
return eval('%d %s %d' % (a, operator, b))
def diff_ways(self, inp):
if not inp:
return []
elif inp.isdigit():
return [int(inp)]
else:
res = []
for i, c in enumerate(inp):
if c in self.operators:
left = self.diff_ways(inp[:i])
right = self.diff_ways(inp[i + 1:])
for l in left:
for r in right:
s = self.calculate(l, r, c)
res.append(s)
return res
s1 = '2*3-4*5'
s2 = '11'
s = Solution()
print(s.diffWaysToCompute(s1))
print(s.diffWaysToCompute(s2))
|
3d466a1d1b683fff57ef69a54274344ce7bd5a21 | skinan/Competative-Programming-Problems-Solutions-Using-Python | /1154A.py | 598 | 3.75 | 4 | # Codeforces
# 1154A - Restoring Three Numbers.
def main():
temp = input().split(" ") # Get the inputs in a temporary list.
num = []
# Convert all the list elements to integer type, and append it to a new list.
for i in range(len(temp)):
num.append(int(temp[i]))
# Sort the list.
num = sorted(num)
# Mathematical operations are done below to find the three numbers.
a = int(num[3]) - int(num[0])
b = int(num[3]) - int(num[1])
c = int(num[3]) - int(num[2])
print(a, b, c)
if __name__ == "__main__":
main()
|
de8fbf0346deac21df683dfb177dfef3cf90570d | jclopezp/retos-py | /ej-02.py | 172 | 3.53125 | 4 | # isinstance(3, int) -> True
# isinstance(3, str) -> False
# x es un elemento del rango
def multiplos(a, b):
lista = [a * x for x in range(1, b + 1)]
return lista
|
25e777491b72b0f9535734f46ce339afc8b909b0 | peterJbates/euler | /027/quadratic_primes.py | 837 | 3.796875 | 4 | from time import time
import math
start = time()
# checks if a number is prime
def isPrime(n):
if n < 2:
return False
elif n == 2:
return True
elif not n & 1: # if n is even (and not 2)
return False
for x in range(3, int(math.sqrt(n))+1, 2):
if n % x == 0:
return False
return True
def main():
a_max, b_max, longest = 0, 0, 0
for x in range(-999, 1000):
for y in range(-1000, 1001):
n = 0
while isPrime(abs((n*(x+n) + y))):
n += 1
if n > longest:
longest = n
a_max, b_max = x, y
print("a = %s, b = %s, longest sequence = %s, max product = %s\n---%s seconds---"\
%(a_max, b_max, (a_max * b_max), longest, (time() - start)))
if __name__ == "__main__":
main()
|
3a40256b0e3b4d3dff2196591ab75ff59900dce1 | razvanilie/UniWork | /AF/Finished/DFS/DFS.py | 885 | 3.78125 | 4 | #http://www.cs.yale.edu/homes/aspnes/pinewiki/DepthFirstSearch.html
from collections import defaultdict
def addEdge(u, v):
graph[u].append(v)
graph[v].append(u) # it depends if it s a directed or undirected graph
#DFS starting with node x
def DFS(x):
visitedArray[x] = True
print(x)
for y in graph[x]:
if(visitedArray[y] == False):
DFS(y)
numberOfNodes = 6 #number of vertexes
visitedArray = [False for x in range(numberOfNodes)] #initialise an array of numberOfNodes length with false values
# graph = [[] for x in range(numberOfNodes)] # for each node we will append the nodes with a common edge
graph = defaultdict(list)
print(visitedArray)
# print(graph)
addEdge(0, 1)
addEdge(0, 2)
addEdge(1, 3)
addEdge(1, 2)
addEdge(2, 3)
addEdge(3, 4)
addEdge(4, 1)
addEdge(4, 0)
addEdge(4, 5)
print("After we added the edges\n" + str(graph))
DFS(0) |
9ab3890b27d2bab9674fb68db3c59acd635441dd | VictorVaquero/sentimentAnalysis | /src/preprocesado.py | 2,897 | 3.609375 | 4 | import csv
from collections import Counter
DIR = "../JavaPreprocesamiento/"
TEXT = "market.csv"
FINAL = "market.txt"
IRREGULAR = "IrregularVerbs.csv"
COLS = 10 # Numero de columnas de el archivo de texto
VOCABULARY = 200 # Numero de palabras a mantener
DEBUG = True
# Simbolos o palabras que no se van a considerar
SIGNS = [" œ "," £ ","\""," "," ", " of ", " the "," an "," a ",",",".",";",":","...","?","!","¡","(",")","[","]","—","-","_","/","'\'","*","$","@","0","1","2","3","4","5","6","7","8","9","·","#","|","º","ª","~","%","","&","¬","=","^","+","š","ç","<",">","","","","", "“", "”", "•"]
RULES = [ ("won't","will not"), ("shan't", "shall not"), ("can't", "cannot") # Negaciones problematicas
]
# Tipicas contracciones, no serian ambiguas porque van con un pronombre
# (la sustitucion es mas compleja en varios casos cuando no van con pronombre)
PRONOUNS = ["i","you","he","she","it","we","they"]
CONTRACTIONS = [("m","am"),("re","are"),("s","is"),("ve","have"),("ll","will"),("d","had")] # Ultimo caso dudoso 'had' o 'would'
RULES.extend([(p+"'"+c,y) for p in PRONOUNS for (c,y) in CONTRACTIONS])
if(DEBUG):
print(RULES)
print("\n")
# Comprobar al final de cada palabra
POSTFIX = [ ("n't"," not"), ("nŽt", " not"), ("n`t"," not"), # Negaciones generales
("ies","y"), ("s",""), ("es",""), ("zzes","z"), ("ves","f"), # Plural a singular
]
def readData(name):
""" Lectura de archivo csv
Devuelve matriz con los datos y cabecera
"""
data = []
with open(name, 'r') as f:
reader = csv.reader(f)
for row in reader:
data.append(row)
return data
def writeData(name, data):
""" Escribe en archivo name los
datos 'data'"""
with open(name, 'w') as f:
f.write(data)
def preProcess(data,irregular):
""" Procesa una cadena de caracteres
"""
data = [x for row in data for x in row]
data = " ".join(data[10:])
data = data.lower() # Trabajar con minusculas
for (x,y) in RULES: #
data = data.replace(x,y)
for sign in SIGNS: # Elimina simbolos
data = data.replace(sign, " ")
for verb in irregular: # Pasar formas verbales irregulares a infinitivo
for form in verb[1:]:
if form != "":
data = data.replace(form,verb[0])
return data
def tokenize(data):
sp = [ d for d in data.split(" ") if d != ""] # Tokeniza el texto
count = [ a for (a,_) in Counter(sp).most_common(VOCABULARY-1) ] # Solo queremos palabras mas comunes
di = { a : count.index(a) for a in count } # Diccionario con la codificacion
return " ".join(sp),[ di[x] for x in sp if x in di], di
data = readData(DIR+TEXT)
irregular_verbs = readData(DIR+IRREGULAR)
data = preProcess(data, irregular_verbs)
data,tokens, dic = tokenize(data)
writeData(FINAL,data)
print(dic)
|
ec029b7a58fa3d665a45949ebe7f04b928795b72 | uvae/BojSolution | /14XXX/boj_14624.py | 163 | 3.796875 | 4 | n = int(input())
if not(n%2): print('I LOVE CBNU')
else:
print('*'*n)
for i in range(n//2+1):
print('{}*{}'.format(' '*(n//2-i), ' '*(i*2-1)+'*' if i else '')) |
b894fa69ad4ca9ccd810d66d6d314f1c537ee3f2 | DarkAlexWang/leetcode | /laioffer/search-in-sorted-matrix.py | 1,315 | 3.703125 | 4 | class Solution:
def search_in_sorted_matrix(self, matrix, target):
if len(matrix) == 0 or len(matrix[0]) == 0:
return [-1, -1]
res = [-1, -1]
m = len(matrix)
n = len(matrix[0])
row = self.find_row(matrix, 0, m - 1, target)
if row == -1:
return res
col = self.find_col(matrix[row], 0, n -1, target)
if col == -1:
return res
res = [row, col]
return res
def find_row(self,matrix, top, down, target):
while top <= down:
mid = (top + down) // 2
if matrix[mid][0] >= target:
down = mid - 1
else:
top = mid + 1
print('top', down)
return down
def find_col(self,array, left, right, target):
while left <= right:
mid = (left + right)// 2
if array[mid] == target:
return mid
elif array[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
print(mid)
if __name__ == '__main__':
solution = Solution()
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
target = 5
res = solution.search_in_sorted_matrix(matrix, target)
print(res)
|
7aa05cab25aabea9b1c2674e51ebd3933f205ddb | dragosbratuflorian19/Skills | /SQL_notes.py | 1,208 | 4.03125 | 4 | ###################################################
# SQLITE3
import sqlite3
the_connection = sqlite3.connect(':memory:') # Connection to a datebase (file or memory)
the_cursor = the_connection.cursor()
the_cursor.execute("""
CREATE TABLE employees (
first text,
last text,
pay integer
)""")
the_cursor.execute(f"INSERT INTO employees VALUES (?, ?, ?)", ('Marian', 'POPA', 45000))
the_cursor.execute(f"INSERT INTO employees VALUES (?, ?, ?)", ('Dragos', 'BRATU', 80000))
the_cursor.execute(f"INSERT INTO employees VALUES (?, ?, ?)", ('Vlad', 'URSU', 50000))
the_cursor.execute("SELECT * FROM employees WHERE last=:last", {"last": 'BRATU'})
print(the_cursor.fetchall())
the_cursor.execute("""
UPDATE employees
SET pay = :pay
WHERE first =:first
AND last = :last
""",
{'first': 'Dragos', 'last': 'BRATU', 'pay': 100000})
with the_connection:
the_cursor.execute("""
DELETE FROM employees
WHERE first=:first
AND last=:last""",
{"first": 'Marian', 'last': 'POPA'})
the_cursor.execute("SELECT * FROM employees")
print(the_cursor.fetchall())
the_connection.close()
################################################### |
87e846986fe2555c9b3d5e876ef6f1c6737e05ea | raysomnath/Python-Basics | /Python_MySQL/Select_With_WildcardCharacters.py | 564 | 3.53125 | 4 | # You can also select the records that starts, includes, or ends with a given letter or phrase.
# Use the % to represent wildcard characters:
import sys
import mysql.connector
# Try connecting to database "mydatabase"
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Somshona$1",
database = "mydatabase",
auth_plugin = 'mysql_native_password'
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address LIKE '%way%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
|
f5dc7d5389e5d26a2d68152e6d9e7b0a58b6b308 | Qinpeng96/leetcode | /206. 反转链表.py | 1,695 | 4.375 | 4 | """
[206. 反转链表](https://leetcode-cn.com/problems/reverse-linked-list/)
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
***
反转一个链表有两种方法:
迭代法和递归法。
迭代法就是每次提出一个左边元数,插入到之前的一个链表中去。
#
[1,2,3,4,5,None]
[1,None] [2,3,4,5,None]
[2,1,None] [3,4,5,None]
[3,2,1, None] [4,5,None]
[4,3,2,1,None] [5,None]
[5,4,3,2,1,None] [None]
"""
```python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
cur = head
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre
```
"""
下面是递归法做:
递归不要想太多,就指向head之后都倒序了这一种情况就可以了。
#
[1->2<-3<-4<-5<-6] head = 1,之后的数都是反转好了的,并且每次返回都是返回的头节点,即6
此时 只需要把2->1, 1->None, 再返回头节点6就可以了。
"""
```python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
last = self.reverseList(head.next)#默认已经排好序了
head.next.next = head
head.next = None
return last
```
|
0dbdbd57d3f4af853170eeed6af6ec0d4533fead | yosifnandrov/func_exercise | /funny_funcs.py | 1,731 | 3.640625 | 4 | def numJewelsInStones(jewels, stones):
final = 0
for jewel in list(jewels):
final += stones.count(jewel)
return final
#print(numJewelsInStones("aA","aAAbbbb"))
def find_smaller(arr):
final = []
for i in range(len(arr)):
final.append(sum(map(lambda x: x < arr[i], arr)))
return final
#print(find_smaller([8,1,2,2,3]))
def simple_math(n):
n = [int(el) for el in list(str(n))]
multiply = 1
sumarry = 0
for num in n:
multiply *= num
sumarry += num
return multiply - sumarry
#print(simple_math(234))
def restoreString(s, indices):
combined = list(zip(s, indices))
new_word = [""] * len(s)
for letter, index in combined:
new_word[index] = letter
return ''.join(new_word)
#print(restoreString("aiohn",[3,1,4,2,0]))
def find_compressed(nums):
final = []
for i in range(2, len(nums)+1, 2):
final.append([nums[i - 1]] * nums[i-2])
final = [num for row in final for num in row]
return final
#print(find_compressed([1,2,3,4]))
def decode(encoded,first):
out = [first]
for i in range(len(encoded)):
out.append(out[i] ^ encoded[i])
return out
#print(decode([1,2,3],1))
def target_array(index,nums):
target = []
new = list(zip(index,nums))
for i,j in new:
target.insert(j,i)
return target
#print(target_array([0,1,2,3,4],[0,1,2,2,1]))
some_text ="HOW ARE YOU".split()
final_list = []
for i in range(len(max(some_text,key=len))):
new_list = []
for el in some_text:
if i >= len(el):
new_list.append(" ")
else:
new_list.append(el[i])
final_list.append(''.join(new_list).rstrip())
#print(final_list)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.