blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
1c0384b4f2d5c1a85cfb7ec10ab45ef19d86582c | KBK3/Python | /m.A/циклы.py | 1,438 | 3.859375 | 4 | #циклы
# 6/12/18
'''
a=10
while a:
a = int(input('Задайте значение переменной ='))
if a==0:
print('Вы вышли т.к а=0')
'''
#2
import random
'''
a=random.randint(1,10)
print('Кол-во рандомных чисел', a)
b=1
c=0
summa=0
while b<=a:
number=random.randint(10,25)
print(str(b)+'.\t', number)
b=b+1
summa=summa+number
if number%2==1:
c=c+1
print('Нечетные числа =', c)
print('Сумма всех чисел =', summa)
'''
#3
'''
a=random.randint(-10,10)
while a!=0:
if a<0:
print('Сгенерировались отицательные число =', a)
break
a=random.randint(-10,10)
print('a= ', a)
else:
print('Встретилось число равное нулю', a)
'''
#4
print('Загадай число от 1 до 100')
x=random.randint(1,100)
print(x)
k=y=0
while y!=x:
y=input('Число=')
if y==" ":
print("Жаль");
break
y=int(y)
k+=1 #k=k+1
if abs(x-y)<5:
print('Жарко')
if abs(x-y)<10:
print('Тепло')
if abs(x-y)<20:
print('Холодно')
if abs(x-y)<30:
print('Мороз')
if y == x:
print('Количество попыток=', k,',загаданное число =', x)
elif k == 8:
print('Игра закончена')
|
3463d1021d834004525ca5434d67ff03b2704301 | sungminoh/algorithms | /leetcode/solved/777_Toeplitz_Matrix/solution.py | 1,865 | 4.21875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 sungminoh <smoh2044@gmail.com>
#
# Distributed under terms of the MIT license.
"""
Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Example 2:
Input: matrix = [[1,2],[2,2]]
Output: false
Explanation:
The diagonal "[1, 2]" has different elements.
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99
Follow up:
What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
What if the matrix is so large that you can only load up a partial row into the memory at once?
"""
from typing import List
import pytest
import sys
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
"""11/08/2022 21:17"""
m, n = len(matrix), len(matrix[0])
return all(len(set(matrix[i+j][j] for j in range(min(m-i, n)))) == 1 for i in range(1, m))\
and all(len(set(matrix[i][j+i] for i in range(min(n-j, m)))) == 1 for j in range(n))
@pytest.mark.parametrize('matrix, expected', [
([[1,2,3,4],[5,1,2,3],[9,5,1,2]], True),
([[1,2],[2,2]], False),
([[36,59,71,15,26,82,87],
[56,36,59,71,15,26,82],
[15,0,36,59,71,15,26]], False),
])
def test(matrix, expected):
assert expected == Solution().isToeplitzMatrix(matrix)
if __name__ == '__main__':
sys.exit(pytest.main(["-s", "-v"] + sys.argv))
|
4bdcbfac2247020cfcb741f8d6172a11d2275683 | NJMES/HackerRank | /Python_practice/FindtheRunner-UpScore_complete.py | 520 | 4 | 4 | # link :https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem
#Find the Runner-Up Score!
if __name__ == '__main__':
n = int(input())
#map is read as an object/ set is to merge duplicate /list to make map/set object into list.
arr = list(set(map(int, input().split())))
#print(arr) #can print the new set/ list
arr.remove(max(arr)) #remove the max element on the list to left with 2nd runnerup.
print(max(arr)) #print the 2nd runner up.
|
03502115034121b423ee3d439135b66d65952c93 | WSJ-2018SE-CPP/gasme | /crawler/crawler.py | 3,279 | 3.578125 | 4 | """
Crawler definition for extracting gas station information from GoogleMaps.
Version 1.0:
- address
- lat/lon
- gas price (3 tiers)
- brand (76, Shell, etc.)
Date: 09/11/2018
"""
import urllib.request
from parser.parser import Parser
from random import randint
import time
class Crawler:
"""
A Crawler class for crawling GoogleMaps gas station prices.
"""
def __init__(self, cities, gas_stations, storage, min_sleep_time=15, max_sleep_time=60):
"""
Initializes a crawler.
Args:
cities: a list of "city, state"
gas_stations: a list of gas stations
sleep_time: number of seconds to sleep after web request
"""
# list of cities
self.cities = cities
# list of gas stations
self.gas_stations = gas_stations
# sleep time
self.min_sleep_time = min_sleep_time
self.max_sleep_time = max_sleep_time
# parser for the gas station blocks
self.parser = Parser()
# parameters to extract
self.params = ['address', 'brand', 'lat', 'lon', 'price_1', 'price_2', 'price_3']
# storage medium
self.storage = storage
def crawl(self):
"""
Begin crawling.
"""
# for each city
for city in self.cities:
# catch error
try:
# store data per city so less connections to db made
data = []
# for each gas station
for gas_station in self.gas_stations:
# search the area
res = self._search(city, gas_station)
# politeness sleeping within a random range, so we don't seem like a robot
time.sleep(randint(self.min_sleep_time, self.max_sleep_time))
# append the results
data.append(res)
# store the results
self.storage.store_data(res)
except Exception as e:
print(e)
def _search(self, city, gas_station):
"""
Search the latitude and longitude for gas station information.
Args:
city: the city to search
gas_station: the gas station to search
Return:
A list of gas station information for each station within the html from the url request
"""
# print feedback
print('Searching %s gas stations in %s --> ' % (gas_station, city), end='', flush=True)
# url to search
url = 'https://www.google.com/maps/search/%s+gas+prices+%s' % (gas_station.replace(' ', '+'), city.replace(' ','+'))
# read the url
with urllib.request.urlopen(url) as response:
# parse the html for gas station information
res = self.parser.parse(html=response.read().decode('utf-8'),
gas_station=gas_station,
params=self.params)
# print feedback
print('Found %d' % len(res), flush=True)
# return results
return res
# print feedback
print('Found %d' % 0, flush=True)
# return empty list if couldn't open url
return []
|
e4818420725f8b9781b3b8043e95a79b7694a776 | uwaifo/Python-for-Algorithms--Data-Structures--and-Interviews | /Sections/Lists/find_missing_number.py | 1,267 | 3.71875 | 4 | '''
So both silutions bellow are quadratic
see vfind_with_collections.py for linear solution 0(n)
'''
def find_missing_number(arr1,arr2):
#understand that in many such questions it would be wise to sanitize
#the arguments such sorting, removing white spaces , making lowercase etc
#sort arrays
arr1.sort()
arr2.sort()
for num1, num2 in zip(arr1,arr2):
if num1 != num2:
return num1
#otherwise return the last element of the first array
return arr1[-1]
arr1 = [1,2,3,4,5,6,7]
arr2 = [3,7,2,1,4,6]
print(find_missing_number(arr1,arr2))
# print(find_missing_number([1,2,3,4,5,6,7],[3,7,2,1,4,6]))#5
# print(find_missing_number([9,8,7,6,5,4,3,2,1],[9,8,7,5,4,3,2,1]))#6
#Bellow is a naive solution as it pays no mind to the posibilitiy of having duplicates
def finder(arr1,arr2):
# check for in-equality in arguments
if len(arr1) == len(arr2):
return
for item in arr1:
#print(item)
if item not in arr2:
return item
'''
arr1 = [1,2,3,4,5,6,7]
arr2 = [3,7,2,1,4,6]
print(finder(arr1,arr2))
print(finder([1,2,3,4,5,6,7],[3,7,2,1,4,6]))#5
print(finder([9,8,7,6,5,4,3,2,1],[9,8,7,5,4,3,2,1]))#6
'''
#Complexity = O(n) Linear both space and time |
150b91035ced6331df64eb40510c529c1612ecc5 | Wertheim/hello-world | /Interest(bisection).py | 1,688 | 4.25 | 4 | #keep working on PS 1
#If you dont know how to do something
#check your Lesson Code notes
#They have good examples of all the code
#ps1c (bi-section)
#declare variables for user input
annual_salary = int(input("Enter your annual salary: "))
portion_saved = 0
total_cost = 1000000
semi_annual_raise = 0.07
portion_down_payment = total_cost * .25
#update current savings every month
current_savings = 0
#annual return
r = 0.04
#counters
num_guesses = 0
low = 0
high = 10000
portion_saved = (high + low)/2.0
while abs(current_savings - portion_down_payment) >= 100:
#recalculate monthly salary every time we try a new portion saved.
monthly_salary = annual_salary / 12
months = 0
current_savings = 0
#use a while loop to simulate 36 months
while(months < 32):
#update savings using calculations from problem
current_savings += current_savings * r/12
current_savings += monthly_salary * (portion_saved/10000.0)
#print(current_savings, portion_saved/1000.0)
#print(portion_down_payment, monthly_salary)
#calculate semi-annual raise and increase number of months
months += 1
if(months%6==0):
monthly_salary += annual_salary * semi_annual_raise / 12
#calculate new guess(portion_saved) based on if we are above or below
if(current_savings < portion_down_payment):
low = portion_saved
else:
high = portion_saved
portion_saved = (high+low)/2.0
num_guesses+=1
#print output outside of while loop
print "Best savings rate: " + str(portion_saved/10000.0)
print "Number of guesses: " + str(num_guesses)
|
475a5485cb6558ee0bc6ca5406046bc7fcf6f9c0 | xieh1987/MyLeetCodePy | /Search a 2D Matrix.py | 865 | 3.53125 | 4 | class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
found=False
m=len(matrix)
n=len(matrix[0])
low=0
high=m-1
while low<=high:
mid=(low+high)//2
if matrix[mid][0]==target:
found=True
break
elif matrix[mid][0]>target:
high=mid-1
else:
low=mid+1
if high<0:
return False
head=0
end=n-1
while head<=end and not found:
mid=(head+end)//2
if matrix[high][mid]==target:
found=True
elif matrix[high][mid]>target:
end=mid-1
else:
head=mid+1
return found
|
9fb6c5dd16cf27dfc0e6e5a1faa3381264859245 | manutdmohit/mypythonexamples | /pythonexamples/implementationofsupermarkeybydict.py | 751 | 4.0625 | 4 | supermarket={
'store1':{
'name':'Durga General Store',
'items':[
{'name':'soap','quantity':20},
{'name':'brush','quantity':30},
{'name':'pen','quantity':40},
]
},
'store2':{
'name':'Sunny Book Store',
'items':[
{'name':'python','quantity':100},
{'name':'django','quantity':200},
{'name':'java','quantity':300},
]
}
}
print('Name of the store1:')
print(supermarket['store1']['name'])
#print(supermarket.get('store1').get('name'))
print('The Names of all items present in store1:')
for d in supermarket['store1']['items']:
print(d['name'])
print('The number of django books in store2:')
for d in supermarket['store2']['items']:
if d['name']=='django':
print(d['quantity'])
|
b2082dcc0ed070b4497132095332931063ddc8d8 | sououshiii/tkinter-Desktop-App | /main.py | 3,256 | 3.625 | 4 | from tkinter import *
from tkinter import ttk
from database import DB
db = DB()
class Window(Tk):
def __init__(self):
super().__init__()
self.title("Book Store Desktop Application")
self.geometry("600x400")
self.configure(background="Light Blue")
self.widgets()
self.show_all()
def widgets(self):
self.title_input = StringVar()
self.author_input = StringVar()
self.year_input = StringVar()
self.isbn_input = StringVar()
self.title_label = ttk.Label(self, text="Title : ")
self.title_label.grid(column=1,row=1, sticky=E, pady=10)
self.title_entry = ttk.Entry(self, textvariable=self.title_input)
self.title_entry.grid(column=2, row=1, sticky=W)
self.author_label = ttk.Label(self, text="Author : ")
self.author_label.grid(column=3, row=1, sticky=E)
self.author_entry = ttk.Entry(self, textvariable=self.author_input)
self.author_entry.grid(column=4, row=1, sticky=W)
self.year_label = ttk.Label(self, text="Year : ")
self.year_label.grid(column=1, row=2, sticky=E)
self.year_entry = ttk.Entry(self, textvariable=self.year_input)
self.year_entry.grid(column=2, row=2, sticky=W)
self.isbn_label = ttk.Label(self, text="ISBN : ")
self.isbn_label.grid(column=3, row=2, sticky=E)
self.isbn_entry = ttk.Entry(self, textvariable=self.isbn_input)
self.isbn_entry.grid(column=4, row=2, sticky=W)
self.add_button = ttk.Button(self, text="Add", command=self.add)
self.add_button.grid(column=1, row=3, pady=10)
self.delete_button = ttk.Button(self, text="Delete", command=self.delete)
self.delete_button.grid(column=2, row=3)
self.update_button = ttk.Button(self, text="Update", command=self.update)
self.update_button.grid(column=3, row=3)
self.search_button = ttk.Button(self, text="Search", command=self.search)
self.search_button.grid(column=4, row=3)
self.books = Listbox(self, height=6,width=50, border=2)
self.books.grid(column=0, row=4, rowspan=7, columnspan=5, padx=10, pady=10)
self.books.bind("<<ListboxSelect>>", self.select_book)
def select_book(self, select):
book_name = select.widget
self.selected_line = book_name.get(ANCHOR)
self.selected_id = self.selected_line[0]
def show_all(self):
self.books.delete(0, END)
books = db.fetch()
for book in books:
self.books.insert(END, book)
def add(self):
db.insert(self.title_input.get(), self.author_input.get(), self.year_input.get(), self.isbn_input.get())
self.show_all()
def delete(self):
db.delete(self.selected_id)
self.show_all()
def update(self):
db.update(self.selected_id, self.title_input.get(), self.author_input.get(), self.year_input.get(), self.isbn_input.get())
self.show_all()
def search(self):
search_index = db.search(self.title_input.get(), self.author_input.get(), self.year_input.get(), self.isbn_input.get())
for index in search_index:
self.books.insert(END, index)
window = Window()
window.mainloop() |
ba366ab4a5f47fce61b8f7c00044cfed3608c81f | N0rtha/frep | /cipher.py | 2,711 | 3.578125 | 4 | '''
Шифровка по Цезарю
Нет заглавных букв
Работает через файл с названием text.txt
Результат в файле caesar cipher.txt
'''
def ccipher(i):
count=0
countt=0
f = open("text.txt")
fi = open('caesar cipher.txt','w')
for line in f:
count+=1
f = open("text.txt")
for line in f:
countt+=1
if count!=countt:
line=line[0:len(line)-1].lower()
alp = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
index=0
tindex=0
text=''
for a in line:
if a!=" ":
for b in alp:
if a!=b:
index+=1
else:
tindex=index+i
index=0
break
if tindex>25:
tindex=tindex-26
text=text+alp[tindex]
else:
text=text+a
fi.write(text+"\n")
'''
'''
def crackc():
i=-1
fi = open("cracked caesar.txt","w")
for cracking in range(26):
i+=1
count=0
countt=0
raz="--------------------------------------------------- "+str(i)
f = open("cipher.txt")
fi.write(raz+'\n')
for line in f:
count+=1
f = open("cipher.txt")
for line in f:
countt+=1
if count!=countt:
line=line[0:len(line)-1]
alp = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
index=0
text=''
for a in line:
if a!=" ":
for b in alp:
if a!=b:
index+=1
else:
tindex=index+i
index=0
break
if tindex>25:
tindex=tindex-26
text=text+alp[tindex]
else:
text=text+a
fi.write(text+'\n')
'''
'''
def vcipher(key):
alp = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,"l":11,"m":12,"n":13,"o":14,"p":15,"q":16,"r":17,"s":18,"t":19,"u":20,"v":21,"w":22,"x":23,"y":24,"z":25}
#alp.get("h")
f = open("text.txt")
fi = open('Vigenere cipher.txt','w')
for line in f:
count+=1
f = open("text.txt")
for line in f:
countt+=1
if count!=countt:
line=line[0:len(line)-1].lower()
|
6514162dee94f5aa1ffb19e083b495f22768c981 | arihant-2310/mockvita2-2020 | /cadbury.py | 354 | 3.515625 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
total =0
def find_total(a, b):
if a == b:
return 1
if b == 1:
return a
diff = a - b
return 1+find_total(max(diff,b),min(diff,b))
for i in range(a, b + 1):
for j in range(c, d + 1):
total = total + find_total(max(i, j), min(i, j))
print(total) |
8a03b0e80ba077b32c82da6f5fd3fd9eef18872b | PyRPy/Py4fun | /FiveLinesPython/022_number_compare.py | 356 | 4.03125 | 4 | Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # is a number between 3 and 7 ?
>>> guess = int(input("enter a number: "))
enter a number: 4
>>> if guess >= 3 & guess <= 7:
print("corret")
else:
print("guess again")
corret
>>> |
f50b09adf73f3c20b5fb0c2b5f2d8d60763bea28 | rqewqdd/python-starter | /week1/example_if3.py | 597 | 3.6875 | 4 | # [문제3] 홀수 짝수 판별
#
# 주어진 수가 짝수인지 홀수인지 판별하는 프로그램을 작성하시오.
try:
num = int(input())
if num % 2 == 0:
print('짝수')
else:
print('홀수')
except:
print('INT형만 입력해주세요.')
# 연습도중 TypeError: not all arguments converted during string formatting 오류가 출력되었는데 num 변수에 입력받은 수가
# str 형태이고 거기에 나머지연산자 %를 써서 오류가 발생했다. 그래서 입력함수인 input을 int 형태로 처리해 결과를 도출했다.
|
92b856252b996daa7708685b72533301d2da0cc1 | ckdrjs96/algorithm | /leetcode/sort/lc_75_v1.py | 438 | 3.71875 | 4 | #삽입정렬
#세가지 숫자만 있을땐 다른 방법보다 느림
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i=1
while i<len(nums):
j=i
while j>0 and nums[j-1]>nums[j]:
nums[j-1],nums[j]=nums[j],nums[j-1]
j-=1
i+=1
print(nums) |
af528d47686f3dc6a537deb41259abbe8fb12e12 | f981113587/Python | /Aula 13/Desafios/060.py | 242 | 3.921875 | 4 | """
Faça um programa que leia um número qualquer
e mostre o seu fatorial
"""
n = int(input('Informe um número: '))
s = n
fatorial = 1
while n > 1:
fatorial *= n
n -= 1
print('O fatorial de {} é {} !'.format(s, fatorial))
|
f946fd906144310d872c3b17a485ca64a368d940 | joshpaulchan/bootcamp | /ctci/4-9.py | 783 | 3.984375 | 4 |
class Tree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
if not self.left and not self.right:
return f"{self.data}"
return f"({self.left}) <- {self.data} -> ({self.right})"
def find_sequences_that_make_tree(tree):
print(tree)
pass
def main():
tree_from_1_to_10 = Tree(5,
Tree(3,
Tree(2,
Tree(1)
),
Tree(4)
),
Tree(8,
Tree(7,
Tree(6)
),
Tree(10,
Tree(9)
)
),
)
find_sequences_that_make_tree(tree_from_1_to_10)
if __name__ == "__main__":
main()
|
36b13e38483a19607144535a5d4400b323f52802 | fr42k/leetcode | /solutions/540-single-element-in-a-sorted-array/single-element-in-a-sorted-array.py | 772 | 3.71875 | 4 | # You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.
#
# Follow up: Your solution should run in O(log n) time and O(1) space.
#
#
# Example 1:
# Input: nums = [1,1,2,3,3,4,4,8,8]
# Output: 2
# Example 2:
# Input: nums = [3,3,7,7,10,11,11]
# Output: 10
#
#
# Constraints:
#
#
# 1 <= nums.length <= 10^5
# 0 <= nums[i] <= 10^5
#
#
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
l, h = 0, len(nums) - 1
while l < h:
m = (l + h) // 2
if nums[m] == nums[m^1]:
l = m + 1
else:
h = m
return nums[l]
|
5db4e9f840373dd9e6bae97e488aaacb41161ba4 | radomirbosak/japanese | /japanese/counter.py | 1,759 | 3.53125 | 4 |
_zero = 'ぜろ'
_one = 'いち'
_ten = 'じゅう'
_hundred = 'ひゃく'
_thousand = 'せん'
_man = 'まん'
_single_digits = [
'',
'',
'に',
'さん',
'よん',
'ご',
'ろく',
'なな',
'はち',
'きゅう',
'じゅう',
]
_hundred_exceptions = {
3: 'さんびゃく',
6: 'ろっぴゃく',
8: 'はっぴゃく',
}
_thousand_exceptions = {
3: 'さんぜん',
8: 'はっせん',
}
_replacements = {
# 100
'さんひゃく': 'さんびゃく',
'ろくひゃく': 'ろっぴゃく',
'はちひゃく': 'はっぴゃく',
# 1000
'さんせん': 'さんぜん',
'はちせん': 'はっせん',
}
_orders = [
(10000, _man),
(1000, _thousand),
(100, _hundred),
(10, _ten),
]
def _compose_higher_part(num, word):
if num == 1:
return word
naive_answer = number(num) + word
return _apply_end_replacement(naive_answer)
def _apply_end_replacement(word):
for src, dst in _replacements.items():
if word.endswith(src):
return word[:-len(src)] + dst
return word
def _number_nozero(num):
if num == 0:
return ''
if num == 1:
return _one
for order, order_word in _orders:
if num < order:
continue
units, rest = divmod(num, order)
higher_part = _compose_higher_part(units, order_word)
return higher_part + _number_nozero(rest)
return _single_digits[num]
def number(num):
if num < 0:
raise ValueError("Negative numbers are not supported.")
if num >= 10000**2:
raise ValueError("Numbers larger than 10^8 are not supported.")
if num == 0:
return _zero
return _number_nozero(num)
|
3203658233a9d37ca4d5ceb6d7f563551bbaf9e0 | kkroy36/Research | /particleFilter/robot.py | 1,302 | 3.703125 | 4 | from math import cos,sin,pi,sqrt
class robot():
def __init__(self):
return
def move(self,world,theta,d):
world.beta += theta
x = int(world.xy[0])
y = int(world.xy[1])
if not (theta==0 and d==0):
world.grid[x][y] = world.grid[x][y][:-7]
radians = (world.beta*pi)/float(180)
world.xy[1] += d*cos(radians)
world.xy[0] += d*sin(radians)
world.boundXY()
if world.color[int(world.xy[0])][int(world.xy[1])] == "white":
world.grid[int(world.xy[0])][int(world.xy[1])] += "(robot)"
else:
world.color[int(world.xy[0])][int(world.xy[1])] += "(robot)"
print "\nmoved: "+str(d)+" units at an angle of "+str(theta)+" degrees\n"
def sense(self,world):
obs = []
pos = world.xy
for item in [[0,0],[2,0],[0,2],[2,2]]:
ssum = 0
for i in range(2):
ssum += (item[i]-pos[i])**2
obs.append(sqrt(ssum))
return obs
def getObs(self,world,pos):
obs = []
for item in [[0,0],[2,0],[0,2],[2,2]]:
ssum = 0
for i in range(2):
ssum += (item[i]-pos[i])**2
obs.append(sqrt(ssum))
return obs
|
36c40e4ff6a2163430ed9afb7e26881ea3c9f3c6 | Suren76/Python | /python procedural programing/homework1/test2.py | 352 | 3.65625 | 4 | x = 0b00101010
y = 0b10101010
print(x,y)
print (bin (x | y))
print (bin (x & y))
print(bin (x ^ y))
print (bin (x |~ y))
print (bin (x &~ y))
print(bin (x ^~ y))
z1 = int(x) and int(y) # Equal bin (x | y)
z2 = int(x) or int(y) # Equal bin (x & y)
z3 = int(x) ^ int(y)
print (z1,z2,z3)
print (bin(z1))
print (bin(z2))
print (bin(z3))
print (z1,z2,z3)
|
a01ce5d38b6f2d602a7ac4c1aefd321acffd8624 | romibello/CRUD_en_Python | /soloAnotaciones.py | 634 | 3.71875 | 4 | """una variable que empieza con guion bajo ( “_” ) es PRIVADA
una variable toda en mayuscula es una CONSTANTE
variables que empiezan con doble guion bajo ( “__”) SEÑAL DEL PROGRAMADOR PARA NO MODIFICAR LA VARIABLE
Las variables se pueden reasignar
No pueden comenzar con numeros
No se pueden utilizar las palabras reservadas de Python como variable. (28 palabras reservadas, si no te genera error) """
""" PEMNDAS = Parentesis, Exponente, Multiplicacion, Division, Adicion, Substraccion (orden de operaciones)
Ejemplo: 2 + 7 / 4 = 3.75 (primero divide y luego suma)
para cambiar el orden uso Parentesis ejemplo: (2+7)/4"""
|
af45a1894796d38549b05282ab208704b1954e8a | GlebBorovskiy/TMS_home_work | /work1.py | 681 | 3.90625 | 4 | # Написать функцию решающую квадратные уравнения. Функция принимает три параметра a, b, c для уравнения ax**2+bx+c=0. Функция возвращает два корня в виде tuple. Решить несколько уравнений и вывести результат
def kvardat(a,b,c):
d = b * b - 4 * a * c
if d < 0:
return ()
elif d == 0:
x1 = -b / (2 * a)
return (x1,)
else:
x1 = (-b - d ** 0.5)/(2 * a)
x2 = (-b + d ** 0.5)/(2 * a)
return (x1, x2)
print(kvardat(8,5,3))
print(kvardat(8,5,16))
print(kvardat(8,18,1))
|
330831f3151ea07c05a8db39bc89bfaaef6a9043 | struggl/DataStructure | /python程序员面试宝典/二叉树/3.4如何求一棵二叉树的最大子树和.py | 3,798 | 3.96875 | 4 | '''
题目描述:给定一棵二叉树,它的每个阶段都是整数(可以为负数),如何找到一棵子树,使得它所有结点的和最大?
思路:遍历每棵子树,计算结点和,比较所有子树的结点和
个人感觉用前序遍历是最简洁的,因为当前子树不一定有左右结点,但是一定有当前这个结点值,无论中序还是后序,都要先
看有没有左结点,多了一层判断,会多需要一个临时变量,至于层序遍历,完全没这个必要
'''
class BTNode(object):
def __init__(self,x):
self.data = x
self.left = None
self.right = None
self.id = None
#以中序构建二叉树
def inorder_create_BTree(arr):
if arr is None or type(arr) != list or len(arr) == 0:
return False
return _inorder_create_BTree(arr,0,len(arr)-1)
def _inorder_create_BTree(arr,start,end):
#递归终止返回
if start > end:
return
mid = (start + end + 1) // 2
root = BTNode(arr[mid])
root.left = _inorder_create_BTree(arr,start,mid-1)
root.right = _inorder_create_BTree(arr,mid+1,end)
return root
class Test(object):
'''
使用递归来计数时,除非是像3.1basic.py计算结点总数那样的简单情形,
否则还是要用类来维护一个整个递归栈都可见的计数变量
说3.1basic.py简单是因为每次递归都对最上层返回有简单的加1贡献,
而本题获取最大子树需要对比并存储不同递归结点的加和,给树结点进行编号也需要维护一个各递归可见的变量
'''
def __init__(self):
import sys
#sys.maxsize为系统最大整数值,-sys.maxsize-1得到最小整数值
self.maxSum = -sys.maxsize - 1
self.maxNode = BTNode(self.maxSum)
self.id = 1
def rank_node(self,root):
#中序遍历对全树结点进行编号
if root is None:
return False
if root.left is None and root.right is None:
root.id = self.id
self.id += 1
else:
#以下两个if的相反情况实际上是递归终止条件
if root.left:
self.rank_node(root.left)
#当前递归结点返回的东西或输出的东西(相当于把返回值定向到类变量中)
root.id = self.id
self.id += 1
if root.right:
self.rank_node(root.right)
def get_maxSum(self,root):
if root is None:
return
if root.left is None and root.right is None:
return root.data
#以上皆为参数边界检测
Sum = root.data
#if root.left 与 if root.right的相反情况实际上作为递归终止条件
if root.left:
Sum += self.get_maxSum(root.left)
if root.right:
Sum += self.get_maxSum(root.right)
#维护最大
if Sum > self.maxSum:
self.maxSum = Sum
#其实要想真正锁定最大子树的根结点位置,应当先用层序遍历给全树结点编号,返回最大子树根结点的编号
self.maxNode.data = root.id
#当前递归结点的返回
return root.data
#中序遍历输出结点值
def inorder(root):
if root is None:
return False
if root.left is None and root.right is None:
print(root.data)
else:
#以下两个if的相反情况实际上是递归终止条件
if root.left:
inorder(root.left)
#当前递归结点输出或返回的东西
print(root.data)
if root.right:
inorder(root.right)
#中序遍历输出结点id
def inorder2(root):
if root is None:
return False
if root.left is None and root.right is None:
print(root.id)
else:
#以下两个if的相反情况实际上是递归终止条件
if root.left:
inorder2(root.left)
print(root.id)
if root.right:
inorder2(root.right)
if __name__ == '__main__':
test = Test()
root = inorder_create_BTree([1,200,3,4,5,6,7,8,90,10])
inorder(root)
print('=====')
test.rank_node(root)
inorder2(root)
print('=====')
test.get_maxSum(root)
print(test.maxSum)
print(test.maxNode.data)
|
53b95e900a7ba586f29ad6cdd9138c29ae97a0c4 | mzambe/CompetitionsGit | /ProjEuler/probl20.py | 264 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import array
def fact(x):
if x <= 1:
return 1
else:
return x*fact(x - 1)
def main():
print fact(100)
print sum(map(int, str(fact(100))))
if __name__ == '__main__':
main()
|
8802e6c329edeac3b597edc61df1d82e7bacdf0c | jemcghee3/ThinkPython | /10_15_exercise_07.py | 723 | 3.96875 | 4 | """Exercise 7
Write a function called has_duplicates that takes a list and returns True
if there is any element that appears more than once. It should not modify the original list."""
def has_duplicates(input_list): # this function will consider 1 and 1.0 as duplicates
for item in input_list:
t = input_list[:]
t.remove(item)
if item in t:
return True
return False
def has_duplicates2(input_list): # this function will consider 1 and 1.0 as duplicates
for item in input_list:
if input_list.count(item) > 1:
return True
return False
test_list = ['a', 1, 1.1, 1.0, '1', []]
print(test_list)
print(has_duplicates2(test_list))
print(test_list)
|
5cf6814b6e51b62e72258026896e64929c0ac7fb | liuderchi/codewars_katas_practice | /python/rgb_to_hex_6kyu.py | 802 | 3.828125 | 4 | '''
The rgb() method is incomplete.
Complete the method so that passing in RGB decimal values will
result in a hexadecimal representation being returned.
The valid decimal values for RGB are 0 - 255.
Any (r,g,b) argument values that fall out of that range should
be rounded to the closest valid value.
The following are examples of expected output values:
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3
'''
def rgb(r, g, b):
round256 = lambda x: max(0, min(x, 255))
return ('{:02X}'*3).format(round256(r), round256(g), round256(b))
assert rgb(0,0,0) == "000000"
assert rgb(1,2,3) == "010203"
assert rgb(255,255,255) == "FFFFFF"
assert rgb(254,253,252) == "FEFDFC"
assert rgb(-20,275,125) == "00FF7D"
|
9f60d020bd64125aa5e77e994f7ad9bd35f213fc | markusk/minibot | /test/battery.py | 748 | 3.6875 | 4 | #!/usr/bin/python
# coding=utf-8
import Adafruit_ADS1x15
# the Analog Digital converter object
adc = Adafruit_ADS1x15.ADS1015()
""" Gain 1 means, max a value of +4.096 Volt (+4,096 Volt in Europe) on the ADC channel, resulting in a 'value' of +2047. """
GAIN = 1
voltage = 0
# read AD converter (battery voltage)
# use channel 0 on IC
value = adc.read_adc(0, gain=GAIN)
# 13.44 Volt battery voltage resulted in 2,94 Volt on the ADC channel with my circuit (voltage divider w/ two resistors (39k + 11k)).
# This resulted in a ADC 'value' of 1465.
# The conversion factor for the battery voltage is then: 1465 / 13.44 = 109.00297619047619
#
voltage = (value / 109.00297619047619)
print("Value: %d" % value)
print("Battery: %.1f Volt" % voltage)
|
e81a5cccbe9f9039c35fda279c35d5576c3ed6bb | L200170143/prak_ASD | /Modul5.py | 2,400 | 3.828125 | 4 | #No 1
class MhsTIF(object):
def __init__(self, nim):
self.nim = nim
def insertionSort(A):
n = len(A)
for i in range(1,n):
nilai = A[i]
MhsTIF = i
while MhsTIF > 0 and nilai < A[MhsTIF - 1]:
A[MhsTIF] = A[MhsTIF-1]
MhsTIF = MhsTIF-1
A[MhsTIF] = nilai
c0 = 200170001
c1 = 200170003
c2 = 200170007
c3 = 200170005
c4 = 200170002
c5 = 200170006
Daftar = [c0, c1, c2, c3, c4, c5]
insertionSort(Daftar)
print("Berikut adalah NIM Mahasiswa secara urut :","\n",Daftar, "\n")
#No 2
A = ["Ayas", "Nindi" , "Tika" , "Corry" , "Yarin"]
B = ["A143" , "A147 " , "A156" , "A152" , "A155"]
C =[]
C.extend(A)
C.extend(B)
def insertionSort(A) :
n = len(A)
for i in range(1,n):
nilai = A[i]
pos = i
while pos > 0 and nilai < A[pos - 1] :
A[pos] = A[pos-1]
pos = pos - 1
A[pos] = nilai
insertionSort(C)
print("Nilai C yang telah urut adalah : ","\n",C,"\n")
#No 3
from time import time as detak
from random import shuffle as kocok
def swap(A,p,q):
tmp = A[p]
A[q]= A[q]
A[q]= tmp
def bubbleSort(A):
n = len(A)
for i in range(n-1):
for j in range (n-i-1):
if A[j] > A[j+1]:
swap(A,j,j+1)
def cariPosisiYangTerkecil(A, dariSini, sampaiSini):
posisiYangTerkecil=dariSini
for i in range(dariSini+1, sampaiSini):
if A[i]<A[posisiYangTerkecil]:
posisiYangTerkecil = i
return posisiYangTerkecil
def selectionSort(A):
n = len(A)
for i in range(n-1):
indexKecil = cariPosisiYangTerkecil(A, i, n)
if indexKecil != i:
swap(A, i, indexKecil)
def insertionSort(A):
n = len(A)
for i in range(1, n):
nilai = A[i]
pos = i
while pos > 0 and nilai < A[pos - 1]:
A[pos] = A[pos - 1]
pos = pos - 1
A[pos] = nilai
k=[]
for i in range(1, 6001):
k.append(i)
kocok(k)
u_bub = k[:]
u_sel = k[:]
u_ins = k[:]
aw = detak();bubbleSort(u_bub);ak=detak();print("bubble : %g detik" %(ak-aw));
aw = detak();selectionSort(u_bub);ak=detak();print("selection: %g detik" %(ak-aw));
aw = detak();insertionSort(u_bub);ak=detak();print("insertion : %g detik" %(ak-aw));
|
df0b3dcb7dfe366b5754da32449dc575c05f5a3f | txt91275847/Test | /threadTest/threadDemo2.py | 763 | 3.828125 | 4 | import threading
import time
class MyThread(threading.Thread):
def __init__(self, threadId, threadName, delay):
threading.Thread.__init__(self)
self.threadId = threadId
self.threadName = threadName
self.delay = delay
def run(self):
print("开始线程:", self.threadName)
print_time(self.threadName, 5, self.delay)
print("退出线程:", self.threadName)
def print_time(threadName, counter, delay):
while counter:
time.sleep(delay)
print(threadName, time.ctime(time.time()))
counter = counter - 1
thread1 = MyThread(1, "Thread-1", 2)
thread2 = MyThread(2, "Thread-2", 1)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("退出主线程!")
|
e43a63ff8a8976114692166ec9cfa6635887e8ca | HeinzVelasquez/PAIE | /dosendos.py | 616 | 3.6875 | 4 | archivo=open("CuentaDos.txt", "w")
def cuentados ():
n=int(input("Ingrese el primer número: "))
m=int(input("Ingrese el segundo número: "))
cuenta=0
for i in range (n,m, 2):
if i % 2 == 0:
cuenta= cuenta +1
print(i)
archivo.write ('i=% s' %i)
archivo.write ('\n')
#programa continua
continua=True
while (continua):
seleccion=cuentados()
print("¿Quieres continuar (s/n)? ")
if (input ()=="s" or input ()=="S"):
continua=True
else:
continua=False
print("Fin del programa")
archivo.close ()
|
2988f8f8b94a9efcbbb0ce87aeaeecb2a4cb32f5 | Damns99/4BreviLezioniDiPython | /errori python.py | 1,288 | 3.5625 | 4 | ###Errori comuni
##sintax error
#syntax error è l'errore che appare ogni qualvolta che un comando viene scritto male o viene usato un carattere sbagliato, qui sono riportati alcuni esempi
#print("ciao')
'''
d=5
print("f=%f", %d)
'''
#impord numpy
'''
import numpy
a=numpy.array(dtype=int , [1,1,1,1,1,1,1])
'''
'''
import numpy
a=numpy.array([1,1,1,1,1,1,1], dtype=2 ,dtype=2)
'''
##dividere per zero
'''
import numpy
a=numpy.array([1,2,5,9,0,7,3])
b=1/a
'''
##array di diverse lunghezze
'''
import numpy
a=numpy.array([1,2,5,9,8,7,3])
b=numpy.array([15,8,6,7])
c=a+b
'''
##File not found
'''
import pylab
x, Dx, y, Dy = pylab.loadtxt('dati4.txt', unpack=True)
'''
## index out of bound
'''
import numpy
a=numpy.array([1,1,1,1,1,1,1,1,1,1,1,1])
n=a[12]
'''
## indentation error
'''
def funzione(x, a, b):
return a*x+b
def funzione(x, a, b):m
return a*x+b
n=5
f=9
x=3
h=funzione(x,n,f)
print(h)
'''
## errori di scrittura
'''
import numpy
import pylab
plt.figure(1)
def f(x):
return x**3
x = np.linspace(-1, 1, 1000)
plt.plot(x, f(x))
plt.show(figure=1)
'''
'''
import numpy
a=numpy.array([1,1,1,1,1,1,1], dtype=6)
'''
'''
import numpy
a=numpy.array([1,1,1,1,1,1,1], unpack=True)
'''
##errori di definizione
'''
x=3
b=x+g
print(b)
'''
|
b2b7a4e4774600fd9352b0bd5bd5b4eb1e162b7a | geolib8/Mision-04 | /reloj.py | 879 | 3.84375 | 4 | #Autor: Jesús Emmanuel Alcalá Nava
#Descripción: este programa calcula la hora en un formato de 12 horas dada la hora en formato de 24 horas por el usuario
def formato12Horas(hora): #convierte la hora en formato de 12 horas
if hora == 0:
return 12
if hora <= 12:
return hora
if hora > 12:
return hora%12
def mañanaTarde(hora): #regresa si la hora es de la mañana o tarde
if hora >= 12:
return "pm"
return "am"
def main():
hora = int(input("Hora en formato de 24 horas: "))
minutos = int(input("Minutos: "))
segundos = int(input("Segundos: "))
horaEn12 = formato12Horas(hora)
pmAm = mañanaTarde(hora)
if hora < 0 or hora > 23 or segundos > 59 or segundos < 0 or minutos > 59 or minutos < 0:
print ("error")
else:
print (horaEn12,":",minutos,":",segundos ,pmAm)
main() |
5b657cb9318893ddb8e8f19f908c171158a29793 | hyunjun/practice | /python/problem-dynamic-programming/steps.py | 2,086 | 4.3125 | 4 | '''
A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time.
Implement a method to count how many possible ways the child can run up the stairs.
Tip:
There are three approaches to this problem.
- recursive algorithm
- top-down dynamic programming - it is actually a recursive algorithm with caching, that saves repeated sub-problems solutions so there are no repetitive calculations.
- bottom-up dynamic programming - starting from the smallest possible problem size, and work the way up to the original size problem. This can be done by caching states in the table, represented in a 1d or 2d arrays. HINT: use two for-loops. The first for-loop is the step size, start from 0 to n steps (thus bottom-up). The second for-loop controls how many hops a child can start with, which are 1 step, 2 steps, or 3 steps.
'''
def step_count(n):
if n == 0:
return 1
if n >= 3:
return step_count(n - 3) + step_count(n - 2) + step_count(n - 1)
if n >= 2:
return step_count(n - 2) + step_count(n - 1)
if n >= 1:
return step_count(n - 1)
def step_count_general(k, n):
if n < 0:
return 0
if n == 0:
return 1
return sum([step_count_general(k, n - i) for i in range(1, k + 1)])
def step_iter(n):
result, l = 0, [n]
while 0 < len(l):
cur = l.pop(0)
for i in range(1, 4):
next = cur - i
if next in [0, 1]:
result += 1
if 1 < next:
l.append(next)
return result
def step_iter_general(k, n):
result, l = 0, [n]
while 0 < len(l):
cur = l.pop(0)
for i in range(1, k + 1):
next = cur - i
if next in [0, 1]:
result += 1
if 1 < next:
l.append(next)
return result
def step_dynamic(n):
count = [0] * (n + 1)
count[0] = None
for step in range(1, 4):
count[step] = 1
for i in range(2, n + 1):
for step in range(1, 4):
if 0 < i - step:
count[i] += count[i - step]
return count[-1]
i = 5
print(step_count(i), step_count_general(3, i), step_iter(i), step_iter_general(3, i), step_dynamic(i))
|
42b696e854df6159afa998388fb3cda6eb9e32a8 | tahiru94/leetcode-solutions | /recursion/reverse-string/reverse_string.py | 255 | 3.8125 | 4 | from math import ceil
def reverse_string(s):
def recursive_reverse(s, i, o):
if i < o:
s[i], s[o] = s[o], s[i]
recursive_reverse(s, i + 1, o - 1)
else:
return
recursive_reverse(s, 0, len(s) - 1) |
2df6952d7dbc308568f978fce36751c42584aa5b | azure1016/MyLeetcodePython | /Google_OA/largest_cake_area.py | 2,757 | 3.5625 | 4 | '''
Input: radii = [1, 1, 1, 2, 2, 3], numberOfGuests = 6.
Output: 7.0686
Explanation:
Reason being you can take the area of the cake with a radius of 3, and divide by 4. (Area 28.743 / 4 = 7.0686)
Use a similary sized piece from the remaining cakes of radius 2 because total area of cakes with radius 2 are > 7.0686
[1,1,1,4,4,9]
we want find x for n people, y cakes is good for x * n
higher bound is 9
lower bound is 1
mid = 5, how many values are bigger than 5? 6 * 5 > 1+1+1+4+4+9=20
higher = 5,lower is 1
mid = 3, sastisfy 5 people
higher 3, lower is 1
mid = 2, we can satisfy: 2+2+4 = 8 people
lower = 2, higher = 3
mid = 2.5, we can satisfy 1+1+3
lower = 2, high is 2.5
mid = 2.25 satisfy: 1+1+4=6
lower = 2.25, higher = 2.5
'''
import math, sys
class CakeDivider:
def largestCake_dp(self, cakes, k):
self.dp = [[float('inf') for _ in range(len(cakes)+1)] for _ in range(k+1)]
areas = [r**2 for r in cakes]
areas.sort()
self.findAllpossible(areas, k, len(areas))
return self.dp[k][-1] * math.pi
def findAllpossible(self, areas, remained, index):
if index == 0: return sys.maxsize
if remained == 0: return sys.maxsize
if remained == 1: return areas[index-1]
if index == 1: return areas[index-1] / float(remained)
if self.dp[remained][index] != float('inf'): return self.dp[remained][index]
cur_max = 0
for i in range(remained):
cur_max = max(cur_max,
min(self.findAllpossible(areas, i, index - 1), areas[index-1] / float(remained - i)))
self.dp[remained][index] = cur_max
return cur_max
def largestCake(self, cakes, k):
areas = [ r**2 for r in cakes]
areas.sort()
high = areas[-1]
low = areas[0]
result = 0
mid = 0
while high > low+0.00001:
mid = low + (high - low) / 2.0
if self.satisfy(mid, k, areas): #
result = max(result, mid)
low = mid # maximum
else:
high = mid
return max(result, mid) * math.pi
def satisfy(self, area, k, areas):
counter = 0
for cake in areas[::-1]:
if cake >= area:
counter += math.floor(cake / area)
if counter >= k:
return 1
else: return 0
def test1(self):
cakes = [1,1,1,2,2,3]
k = 6
result = self.largestCake(cakes, k)
result_dp = self.largestCake_dp(cakes, k)
print(result_dp)
print(result)
def test2(self):
cakes = [4,3,3]
k = 3
print(self.largestCake_dp(cakes, k))
print(self.largestCake(cakes, k))
sol = CakeDivider()
sol.test2()
|
fca67ab172b331a5319cc475af1954f696ac869d | jimmy-rojas/StudentGeolocationPythom | /BoundingBox.py | 1,220 | 3.578125 | 4 | import math
class BoundingBox(object):
def __init__(self, *args, **kwargs):
self.lat_min = None
self.lon_min = None
self.lat_max = None
self.lon_max = None
def hasWithin(self, student):
return self.lat_min <= student["latitude"] <= self.lat_max and self.lon_min <= student["longitude"] <= self.lon_max
@staticmethod
def getBoundingBox(latitude_in_degrees, longitude_in_degrees, half_side_in_meters):
assert half_side_in_meters > 0
assert latitude_in_degrees >= -90.0 and latitude_in_degrees <= 90.0
assert longitude_in_degrees >= -180.0 and longitude_in_degrees <= 180.0
half_side_in_km = (half_side_in_meters/1000.0)
lat = math.radians(latitude_in_degrees)
lon = math.radians(longitude_in_degrees)
radius = 6371
# Radius of the parallel at given latitude
parallel_radius = radius * math.cos(lat)
lat_min = lat - half_side_in_km / radius
lat_max = lat + half_side_in_km / radius
lon_min = lon - half_side_in_km / parallel_radius
lon_max = lon + half_side_in_km / parallel_radius
rad2deg = math.degrees
box = BoundingBox()
box.lat_min = rad2deg(lat_min)
box.lon_min = rad2deg(lon_min)
box.lat_max = rad2deg(lat_max)
box.lon_max = rad2deg(lon_max)
return (box)
|
73f9180b49009c4a52be068f633f177124ec4c97 | parthu12/DataScience | /daily practise/try.py | 206 | 3.890625 | 4 | a=int(input('enter a num'))
try:
if a>4:
print('>4')
else:
print('<4')
except valueerror:
print('value in digit')
finally:
print('success')
|
6eb2d0ebd4a5c5a609ec6372fc419bc927dc06fb | jinbooooom/coding-for-algorithms | /LeetCode/416-分割等和子集/canPartition.py | 3,963 | 3.625 | 4 | # -*- coding:utf-8 -*
"""
https://leetcode-cn.com/problems/partition-equal-subset-sum
https://leetcode-cn.com/problems/partition-equal-subset-sum/solution/0-1-bei-bao-wen-ti-xiang-jie-zhen-dui-ben-ti-de-yo/
给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
注意:
每个数组中的元素不会超过 100
数组的大小不会超过 200
示例 1:
输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].
示例 2:
输入: [1, 2, 3, 5]
输出: false
解释: 数组不能分割成两个元素和相等的子集.
"""
from typing import List
class Solution:
def canPartition(self, nums: list) -> bool:
"""
提示:
方法一:二维动态规划
可以把这道题转换为 0-1 背包问题:
有一些物品,它们的重量存储在列表 nums 中,
而你刚好有两个包,怎么装能让这两个包装的物品重量相等?
或者说,你只有一个包,怎么让这一个包刚好带走总重量一半的物品?
0-1 背包问题也是最基础的背包问题,它的特点是:待挑选的物品有且仅有一个,可以选择也可以不选择。
下面我们定义状态,不妨就用问题的问法定义状态。
dp[i][j]:表示从数组的 [0, i] 这个子区间内挑选一些正整数,每个数只能用一次,使得这些数的和等于 j。
新来一个数,例如是 nums[i],这个数可能选择也可能不被选择:
如果不选择 nums[i],在 [0, i - 1] 这个子区间内已经有一部分元素,使得它们的和为 j ,那么 dp[i][j] = true;
如果选择 nums[i],在 [0, i - 1] 这个子区间内就得找到一部分元素,使得它们的和为 j - nums[i] (nums[i] <= j)。
以上二者成立一条都行。于是得到状态转移方程:
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i]], (if nums[i] <= j)
"""
size = len(nums)
# 特判,如果整个数组的和都不是偶数,就无法平分
s = sum(nums)
if s & 1 == 1:
return False
# 二维 dp 问题:背包的容量
target = s // 2
# 定义并初始化 size 行 target+1 列的备忘录
dp = [[False for _ in range(target + 1)] for _ in range(size)]
# 先写第 1 行:看看第 1 个数是不是能够刚好填满容量为 target
for i in range(target + 1):
dp[0][i] = False if nums[0] != i else True
# i 表示物品索引
for i in range(1, size):
# j 表示容量
for j in range(target + 1):
if j >= nums[i]:
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i]]
else:
dp[i][j] = dp[i - 1][j]
return dp[-1][-1]
def canPartition2(self, nums: List[int]) -> bool:
"""
提示:
方法二:优化成一维动态规划
即是 01 背包求方案数的问题
"""
s = sum(nums)
if s & 1:
return False;
s = s // 2
dp = [0 for _ in range(s + 1)]
dp[0] = 1
for x in nums:
for j in range(s, x - 1, -1):
dp[j] = dp[j - x] + dp[j]
return bool(dp[-1])
def canPartition3(self, nums: List[int]) -> bool:
"""
提示:
方法三:在方法二的基础上改进,更容易理解
"""
s = sum(nums)
if s & 1:
return False;
s = s//2
dp = [False for _ in range(s + 1)]
dp[0] = True
for x in nums:
for j in range(s, x - 1, -1):
dp[j] = dp[j - x] or dp[j]
return dp[-1]
if __name__ == "__main__":
f = Solution()
nums = [1, 5, 11, 5]
f2 = f.canPartition2(nums)
print(f2)
|
493f2ab9fd706f3e4b63892900124590596771b6 | JCVANKER/anthonyLearnPython | /learning_Python/basis/输入输出以及while循环/标志、break、continue/sign_break_continue.py | 947 | 4.09375 | 4 | #在要求很多条件都满足才能继续运行的程序中,可定义一个变量,判断整个程序是否处于活动状态
#标志为True时循环继续,False时循环停止
prompt="Tell me something, and i will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program."
active = True
while active:
message=input(prompt)
if message == 'quit':
active = False
else:
print(message+"\n")
print("--------------------------------------")
#break退出循环
prompt="\nPlease enter the name of a city you have visited:"
prompt+="\n(Enter 'quit' when you are finished.)"
while True:
city=input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to "+city.title()+"!")
print("--------------------------------------")
#continue忽略循环内以下代码,返回到循环开头
current_number = 0
while current_number <10:
current_number+=1
if current_number % 2 == 0:
continue
else:
print(current_number)
|
133a9648c49a6ee30c07b3d02b1e42fb0b3b49b9 | ArtemSmeta/Python_Lyceum | /lesson_new.py | 1,847 | 3.703125 | 4 | import random
name = "Name"
hp = random.randint(70, 100)
money = random.randint(700, 1010)
luck = random.randint(1, 10)
is_blessed = True
is_immortal = False
print('Вы посмотрели в волшебное зеркало, на нем появляется мутная надпись - привет, {}'.format(name.upper()))
'''
### Таверна ###
Зайдя в нее, нужно перебрать список людей в ней и выделить тех, кому больше 18 лет для продолжения общения. Вывести имена этих людей
'''
def find_friend(db, age):
pass
def aura_color(is_blessed, is_immortal, hp):
aura_visible = is_blessed & (hp > 50) | is_immortal
if aura_visible:
color = "green"
else:
color = "red"
return color
def health_status(hp, is_blessed):
if hp == 100:
status = 'is in excellent condition!'
elif hp in range(90, 100):
status = "has a few scratches."
elif hp in range(75, 90):
if is_blessed:
status = "has some minor wounds, but is healing quite quickly!"
else:
status = "has some minor wounds."
elif hp in range(15, 75):
status = "looks pretty hurt."
else:
status = "is in awful condition!"
return status
def convert_base(num, to_base=10, from_base=10):
# first convert to decimal number
if isinstance(num, str):
n = int(num, from_base)
else:
n = int(num)
# now convert decimal to 'to_base' base
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < to_base:
return alphabet[n]
else:
return convert_base(n // to_base, to_base) + alphabet[n % to_base]
print(convert_base('1000101011', from_base=2))
print(int('1000101011', 2))
|
240c4baa67df074cbafe08329cba41fc8b7c634e | Ridwanullahi-code/python-regular-expression | /reg1.py | 250 | 3.890625 | 4 | import re
phone_number = ("123 567 678333")
reg_pattern = re.compile(r'\b\d{3} \d{3} \d*')
search = reg_pattern.search(phone_number)
print(search)
name = ("Ridwanullahi9")
pattern = re.compile(r'[0-9]+')
search = pattern.search(name)
print(search)
|
221cb199c47035b8e38a25ed2b836b4bbdd3bc7f | LucasMoretti8/PythonExercicios | /ex026.py | 563 | 3.984375 | 4 | #frase = input('Digite uma frase: ')
#frase = frase.lower()
#c = frase.count('a')
#pos1 = frase.find('a')
#pos2 = frase.rfind('a')
#print('Na frase "{}" a letra "A" aparece {} vezes.\nEla aparece na primeira vez na posição {},\ne ela aparece na última vez na posição {}'.format(frase, c, pos1, pos2))
frase= str (input('Digite uma frase: ')).upper().strip()
print('A letra A aparece {} vezes nesta frase.\nA primeira letra A apareceu na posição {}\nA última letra A apareceu na posição {}'.format(frase.count('A'),frase.find('A')+1,frase.rfind('A')+1)) |
f5251355ae4567dfd6ec2cb47607f6b8e11af564 | swatisjss/Currency-Converter | /CurrencyConverter.py | 679 | 4.09375 | 4 | #For Reading and Exporting texts from Files
with open("Currencydata.txt") as f:
lines = f.readlines()
#Using Dictionary For Calling Amount As Value From Currency as Key
currencyDict = {}
for line in lines:
parsed = line.split("\t")
currencyDict[parsed[0]] = parsed[1]
#For User input and taking out value in INR
amount = int(input("Enter the amount:\n"))
print("Enter the name of currency you want to convert this amount this amount to? Available options are:\n ")
[print(item) for item in currencyDict.keys()]
currency = input("Please enter one of these values\n")
print(f"{amount} INR is equal to {amount*float(currencyDict[currency])} {currency}") |
5008b9295ac1a9eb1679598cbe94de3679bae530 | khalifardy/tantangan-python | /stringclass.py | 501 | 3.890625 | 4 | # pertanyaan buatlah sebuah class string dengan minimal dua metode, untuk mengambil input
# Dan mencetak input dengan string huruf besar semua
class String(object):
def __init__(self):
self.string = " "
def get_string(self):
self.string = input("masukan kata :")
def print_string(self):
print(self.string.upper())
nama = String()
nama.get_string()
nama.print_string()
#fungsi Upper(), untuk mengembalikan string menjadi huruf besar semua
|
f149de08a1381cb79785dbefc4945a5dcce52a47 | skafev/Python_fundamentals | /Final_exam/02Destination_mapper.py | 288 | 3.6875 | 4 | import re
res = []
length = 0
text = input()
pattern = re.compile(r'(=|\/)([A-Z][A-Za-z]{2,})\1')
matches = re.finditer(pattern, text)
for match in matches:
res.append(match[2])
length += len(match[2])
print(f"Destinations: {', '.join(res)}")
print(f"Travel Points: {length}")
|
252b7c015b09d4ca2e4850050d5df8091bae1abf | pinwei67/computational-thinking-and-program-design | /week14_A108060032林品慰.py | 300 | 4.0625 | 4 | weight = float(input("Enter Your Weight(KG)? "))
height = float(input("Enter Your height(M)? "))
bmi = weight / (height * height)
print("BMI指數為",bmi)
n = 0
left = 0
while n < 10:
n = n + 1
left = 10 - n
print("這是第", n, "次的hello", "還有",left, "次機會") |
71f927986c32be4123c1b285f2c8fb6c9baeb008 | cfryhofer/hi-im-connor | /FinalProjectPart1/FinalProjectPart1.py | 5,921 | 3.625 | 4 | #Connor Fryhofer Student ID 1853826
import csv
from datetime import datetime
class OutputInventory:
# Class for output inventory files from input
def __init__(self, item_list):
'''
These are all the items
'''
self.item_list = item_list
def full(self):
'''
This makes it to where an inventory is entirely created through alphabetical order and will include item id, item type, price, manufacturer name, service date, and damaged. All onto a csv file.
'''
with open('./output_files/FullInventory.csv', 'w') as file:
items = self.item_list
# get order of keys to write to file based on manufacturer
keys = sorted(items.keys(), key=lambda x: items[x]['manufacturer'])
for item in keys:
id = item
man_name = items[item]['manufacturer']
item_type = items[item]['item_type']
price = items[item]['price']
service_date = items[item]['service_date']
damaged = items[item]['damaged']
file.write('{},{},{},{},{},{}\n'.format(id, man_name, item_type, price, service_date, damaged))
def by_type(self):
'''
This makes it to where items will get sorted by the item ID, one item on each row of file, and creates csv output files.
'''
items = self.item_list
types = []
keys = sorted(items.keys())
for item in items:
item_type = items[item]['item_type']
if item_type not in types:
types.append(item_type)
for type in types:
file_name = type.capitalize() + 'Inventory.csv'
with open('./output_files/' + file_name, 'w') as file:
for item in keys:
id = item
man_name = items[item]['manufacturer']
price = items[item]['price']
service_date = items[item]['service_date']
damaged = items[item]['damaged']
item_type = items[item]['item_type']
if type == item_type:
file.write('{},{},{},{},{}\n'.format(id, man_name, price, service_date, damaged))
def past_service(self):
'''
This makes it to where an output file will be created for the items that are expired. Oldest to most recent with one item on each row.
'''
items = self.item_list
keys = sorted(items.keys(), key=lambda x: datetime.strptime(items[x]['service_date'], "%m/%d/%Y").date(),
reverse=True)
with open('./output_files/PastServiceDateInventory.csv', 'w') as file:
for item in keys:
id = item
man_name = items[item]['manufacturer']
item_type = items[item]['item_type']
price = items[item]['price']
service_date = items[item]['service_date']
damaged = items[item]['damaged']
today = datetime.now().date()
service_expiration = datetime.strptime(service_date, "%m/%d/%Y").date()
expired = service_expiration < today
if expired:
file.write('{},{},{},{},{},{}\n'.format(id, man_name, item_type, price, service_date, damaged))
def damaged(self):
'''
Output files will be created for any damaged items from most to least expensive, one item on each row.
'''
items = self.item_list
# get order of keys to write to file based on price
keys = sorted(items.keys(), key=lambda x: items[x]['price'], reverse=True)
with open('./output_files/DamagedInventory.csv', 'w') as file:
for item in keys:
id = item
man_name = items[item]['manufacturer']
item_type = items[item]['item_type']
price = items[item]['price']
service_date = items[item]['service_date']
damaged = items[item]['damaged']
if damaged:
file.write('{},{},{},{},{}\n'.format(id, man_name, item_type, price, service_date))
if __name__ == '__main__':
items = {}
files = ['ManufacturerList.csv', 'PriceList.csv', 'ServiceDatesList.csv']
for file in files:
with open(file, 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for line in csv_reader:
item_id = line[0]
if file == files[0]:
items[item_id] = {}
man_name = line[1]
item_type = line[2]
damaged = line[3]
items[item_id]['manufacturer'] = man_name.strip()
items[item_id]['item_type'] = item_type.strip()
items[item_id]['damaged'] = damaged
elif file == files[1]:
price = line[1]
items[item_id]['price'] = price
elif file == files[2]:
service_date = line[1]
items[item_id]['service_date'] = service_date
inventory = OutputInventory(items)
# Create all the output files
inventory.full()
inventory.by_type()
inventory.past_service()
inventory.damaged()
# Get the different manufacturers and types in a list
types = []
manufacturers = []
for item in items:
checked_manufacturer = items[item]['manufacturer']
checked_type = items[item]['item_type']
if checked_manufacturer not in types:
manufacturers.append(checked_manufacturer)
if checked_type not in types:
types.append(checked_type)
|
0d2bfeaa9d38d02e264dbbda7157a4372326b98a | sauravp/snippets | /python/merge_two_sorted_lists_ii.py | 557 | 3.796875 | 4 | # https://www.interviewbit.com/problems/merge-two-sorted-lists-ii/
class Solution:
# @param A : list of integers
# @param B : list of integers
def merge(self, A, B):
i, j = 0, 0
while j < len(B):
if B[j] < A[i]:
A.insert(i, B[j])
if i < len(A) - 1:
i += 1
j += 1
elif i < len(A) - 1:
i += 1
else:
A.extend(B[j:])
j = len(B)
print( " ".join(map(str, A)) + " ")
|
a15ef55d33890aee4749fd24115482b5517717a2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/phone-number/f7baf707a986401bbadceb7b7e1db53d.py | 472 | 3.71875 | 4 | class Phone(object):
def __init__(self,input):
self.input = input
self.make_num()
def make_num(self):
num = [i for i in self.input if i in '1234567890']
if len(num) == 10:
self.number = ''.join(num)
elif len(num) == 11 and num[0] == '1':
self.number = ''.join(num[1:])
else:
self.number = '0000000000'
def area_code(self):
return self.number[:3]
def pretty(self):
return "(%s) %s-%s" % (self.number[:3],self.number[3:6],self.number[6:])
|
37cae65190ba7e65c6e027d06edb99d256c60b26 | hungrytech/Practice-code | /DFS and BFS/BFS practice1.py | 557 | 3.75 | 4 | def bfs(graph, start_node) :
visited =list() # 방문노드 저장
need_visit=list()
need_visit.append(start_node)
while need_visit :
node=need_visit.pop(0)
if node not in visited :
visited.append(node)
need_visit.extend(graph[node])
return visited
data=dict()
data['A'] = ['B','C']
data['B'] = ['A','D']
data['C'] = ['A','G','H','I']
data['D'] = ['E','F']
data['E'] = ['D']
data['F'] = ['D']
data['G'] = ['C']
data['H'] = ['C']
data['I'] = ['C','J']
data['J'] = ['I']
print(bfs(data, 'A')) |
2822e11b68e91ae57cd91f8019590c08f74eb7f7 | concpetosfundamentalesprogramacionaa19/clase4-2do-ispa16 | /ejercicios-python1/principal3.py | 237 | 4.0625 | 4 | """
@reroes
Manejo de estructuras
"""
lista = ["Loja", "Cuenca"]
lista2 = ["Loja", "Azuay"]
lista.append("Zamora")
print("Imprimir lista ")
for l in lista:
print(l)
print("Imprimir lista2 ")
for l in lista2:
print(l)
|
fcdae2fbe26fdc25a813d3e14e72d358903c78aa | super-aardvark/project-euler | /problem-001-100/problem-011-020/problem-015.py | 951 | 4.1875 | 4 | '''
Created on Jan 10, 2017
@author: jfinn
'''
def paths_through_lattice(grid_size):
# Problem defines the grid size as the number of squares. Add one to get the number of intersections.
grid_size += 1
# We'll track the number of different paths that may be taken to get to each node
nodes = [ [ 0 for col in range(grid_size) ] for row in range(grid_size) ]
# Always 1 path to the first node (we start there)
nodes[0][0] = 1
# For each path to a given node, that many paths are added to any node reachable from there
for row in range(grid_size):
for col in range(grid_size):
if row < grid_size - 1:
nodes[row+1][col] += nodes[row][col]
if col < grid_size - 1:
nodes[row][col+1] += nodes[row][col]
return nodes[-1][-1]
print(paths_through_lattice(1))
print(paths_through_lattice(2))
print(paths_through_lattice(20)) |
4c07ccab02908e85818afd310c2b3a25054a5c92 | StudyForCoding/BEAKJOON | /05_Practice1/Step05/yj.py | 136 | 3.65625 | 4 | a = int(input())
for i in range(a):
print(' '*i+'*'*(a-i)+'*'*(a-i-1))
for i in range(1,a):
print(' '*(a-i-1)+'*'*(i)+'*'*(i+1)) |
8f52c011ba0daa2a51c4fcb292545d738322d006 | andrefisch/PythonScripts | /chessboardShapes.py | 2,399 | 3.921875 | 4 | def ChessboardShapes(squares):
a = 1
print "Squares ", squares
board = [[0 for x in range(8)] for y in range(8)]
FillBoard(board)
for i in squares:
# take array info and fill in chessboard
for j in squares:
n, l = j
n = ord(n) - 97
l = int(l) - 1
print "changing", n, ",", l, "to 1"
board[n][l] = 1
# then find area
n, l = j
n = ord(n) - 97
l = int(l) - 1
t = FindArea(n, l, board)
for x in range (8):
for y in range (8):
print board[x][y],
if y == 7:
print "\n"
FillBoard(board)
if t > a:
a = t
return a
def FindArea(n, l, board):
s = 1
# if we have a number in the middle of the board it is easy
# if this part of the board is shaded we are done
if board[n][l] == 0:
return 0
# if this part of the board is shaded we recurse
else:
# mark the square so we dont count it twice
board[n][l] = 0
# call the method in four directions
if n < 7:
print "case 1:", n, ", ", l
s += FindArea (n + 1, l, board)
if l < 7:
print "case 2:", n, ", ", l
s += FindArea (n, l + 1, board)
if n > 0:
print "case 3:", n, ", ", l
s += FindArea (n - 1, l, board)
if l > 0:
print "case 4:", n, ", ", l
s += FindArea (n, l - 1, board)
return s
def FillBoard(board):
s = 0
# populate chessboard
for i in range (8):
s += 1
for j in range (8):
board[i][j] = 0 if s % 2 == 0 else 1
s += 1
# print ChessboardShapes(["g2", "h1"])
# around the edges
print ChessboardShapes(["a2", "a4", "a6", "a8", "c8", "e8", "g8", "h7", "h5", "h3", "h1", "f1", "d1", "b1"])
# all white squares
# print ChessboardShapes(["a8", "a6", "a4", "a2", "b7", "b5", "b3", "b1", "c8", "c6", "c4", "c2", "d7", "d5", "d3", "d1", "e8", "e6", "e4", "e2", "f7", "f5", "f3", "f1", "g8", "g6", "g4", "g2", "h7", "h5", "h3", "h1"])
# all black squares
# print ChessboardShapes(["a9", "a7", "a5", "a3", "b8", "b6", "b4", "b2", "c1", "c7", "c5", "c3", "d8", "d6", "d4", "d2", "e1", "e7", "e5", "e3", "f8", "f6", "f4", "f2", "g1", "g7", "g5", "g3", "h8", "h6", "h4", "h2"])
|
526942be596a590733fb7a14509368156cc5ebb8 | srikanthpragada/demo_24_june_2019 | /oop/employee.py | 588 | 3.65625 | 4 | class Employee:
def __init__(self, name, salary, grade=1):
self.name = name
self.salary = salary
self.grade = grade
def print_details(self):
print("Name : ", self.name)
print("Salary : ", self.salary)
print("Grade : ", self.grade)
def get_salary(self):
if self.grade == 1:
return self.salary + self.salary * .30
else:
return self.salary + self.salary * .25
def set_grade(self, grade):
self.grade = grade
e1 = Employee("Scott",100000,2)
e2 = Employee("Mike",50000)
|
fcb55bcf22ae4c66dd349e006180d0cb9c05d11a | Yustynn/digital-world | /WK4/explain_laguerre.py | 1,473 | 4.21875 | 4 | # assoc_laguerre expects you to make a function that creates a new function and returns it
# think of it like a factory that you can invoke to make similar functions. It's a very
# useful but also rather advanced technique
# here's an example of how it's done.
# this function is like a factory that creates and then returns specific types of functions
# these created functions all do the same thing: they take any number (as n2)
# and add a fixed number (n1) to it
# the difference between the created functions is what this fixed number is.
def create_adder(n1):
# let's make the adder function. A new one gets made everytime create_adder is called
def adder(n2):
# notice how the adder function, which gets returned, only takes n2 as a parameter
# it already knows n1 because when it was created, n1 took on the value
# passed into the create_adder function
# Another way to think of it: n1 is defined when create_adder is called
# So there's no need for adder to take in n1 as an argument. It's fixed already
return n1 + n2
# let's return the custom adder that we just made!
return adder #
five_adder = create_adder(5) # returns fn that adds 5 to the number you call it with
hundred_adder = create_adder(100) # returns fn that adds 100 to the number you call it with
print five_adder(1) # prints 6
print hundred_adder(1) # prints 101
print create_adder(100)(1) # exactly the same as the above line
|
5cf30b3de867bec1ad31a66882efe1cf1aea27c8 | JessyLeal/fundamentals-of-computational-issues | /recursion/main.py | 265 | 3.859375 | 4 |
# ao invés de retornar um valor inteiro baseado na sequência de fibonacci, a função retornará uma string
def rec(n):
if n == 0:
return 'b'
elif n == 1:
return 'a'
else:
return rec(n-1)+ rec(n-2)
print(rec(int(input())))
|
f84d8515bbe1db5bf69d71ded265a71d91c3ee3e | ay1011/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /bisection_guess.py | 840 | 4.15625 | 4 | print "Please think of a number between 0 and 100!: "
lo = 0
hi = 100
guessed = False
while not guessed:
guess = (hi + lo) / 2
print 'Is your secret number ' + str(guess) + '?'
respond = raw_input(" Enter 'h' to indicate the guess is too high." \
" Enter 'l' to indicate the guess is too low." \
" Enter 'c' to indicate I guessed correctly. ")
if respond == 'c':
guessed = True # Guessed correctly!
elif respond == 'h':
hi = guess # Guess too high. let current guess be highest possible guess.
elif respond == 'l':
lo = guess # Guess too low. let current guess be lowest possible guess.
else:
print("Sorry, I did not understand your input.")
print('Game over. Your secret number was: ' + str(guess))
|
47c325af5dfd78a48e09f8644cf969ffe1e8dbc0 | rileyrohloff/pythontheHardWay | /Python Projects/ex13.py | 490 | 3.828125 | 4 | from sys import argv
#read the WYSS section of python documentation
script, first, second, third = argv
print("Your script is called: ", script)
print("Your first variable is: ", first)
print("Your third variable is:", second )
print("Your third variable is:", third)
print("What is your age?", end=' ')
your_age = int(input())
print("What is your weight?", end=' ')
your_weight = int(input())
print(f"Your age is {your_age} and your weight is {round(your_weight / 2.2046226)} in kgs.") |
54a38474bcfc39ee234c64a8b7808d3df7e31c7d | payal-98/Student_Chatbot-using-RASA | /db.py | 1,205 | 4.15625 | 4 | # importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect("students.db")
# cursor
crsr = connection.cursor()
# SQL command to create a table in the database
sql_command = """CREATE TABLE students (
Roll_No INTEGER PRIMARY KEY,
Sname VARCHAR(20),
Class VARCHAR(30),
Marks INTEGER);"""
# execute the statement
crsr.execute(sql_command)
# SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (1, "Payal", "10th", 100);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (2, "Devanshu", "9th", 98);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (3, "Jagriti", "8th", 95);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (4, "Ansh", "5th", 90);"""
crsr.execute(sql_command)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()
|
d26e7cffc49d6e1b0b6e7e056667a8fb4f07ffb5 | zhufangxin/learn-python3 | /Exchange/currency_converter v5.0.py | 1,155 | 4 | 4 | # -*- coding: utf-8 -*-
"""
功能:汇率转换
版本: V5.0
新增功能: 1.程序结构化 2.简单函数的定义 Lamda 函数名=lamda <参数列表>:<表达式>
"""
# def convert_currency(im, rate):
# """
# 汇率兑换函数
# """
# return im * rate
def main():
"""
主函数
"""
USD_VS_RMB = 6.77 # 固定值的命名用大写
currency_inp_value = input('请输入带单位的货币金额(退出程序请输入Q):')
unit = currency_inp_value[-3:]
if unit == 'CNY':
exchange_rate = 1 / USD_VS_RMB
elif unit == 'USD':
exchange_rate = USD_VS_RMB
else:
exchange_rate = -1
if exchange_rate != -1:
inp_money = eval(currency_inp_value[:-3])
# 使用Lamda定义函数
convert_currency2 = lambda x: x * exchange_rate
# 调用函数
# out_money = convert_currency(inp_money, exchange_rate)
# 调用lamda函数
out_money = convert_currency2(inp_money)
print("转换后的金额为", out_money)
if __name__ == '__main__': # ALWAYS RETURN TRUE
main()
|
263f9d74b0c56b54ae61b705fc78e35537aa37aa | cybelewang/leetcode-python | /code394DecodeString.py | 2,120 | 3.875 | 4 | """
394 Decode String
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
"""
class Solution:
# OJ's best
def decodeString(self, s):
stack = []; curNum = 0; curString = ''
for c in s:
if c == '[':
stack.append(curString)
stack.append(curNum)
curString = ''
curNum = 0
elif c == ']':
num = stack.pop()
prevString = stack.pop()
curString = prevString + num*curString
elif c.isdigit():
curNum = curNum*10 + int(c)
else:
curString += c
return curString
# my solution
def decodeString2(self, s):
"""
:type s: str
:rtype: str
"""
stack, num = [''], 0
for c in s:
if c.isdigit():
num = num*10 + ord(c) - ord('0')
elif c == '[':
stack.append(num)
stack.append('')
num = 0
elif c == ']':
sub = stack.pop()
count = stack.pop()
stack[-1] += sub*count
num = 0
else:
stack[-1] += c
num = 0
return stack[-1]
obj = Solution()
test_cases = ['', 'abcde', '3[a]2[bc]', '3[a2[c]]', '2[abc]3[cd]ef']
for case in test_cases:
print(obj.decodeString(case)) |
edf56333c9f69222d913b9f27ebe6bb7aaa2b8e4 | tsdiallo/Python_Exercices-4 | /exo 17 Suite de Syracuse.py | 232 | 3.96875 | 4 | print("suite cyracuse")
n=int(input("Saisissez une valeur\t"))
def f(n):
if n%2==0:
return n//2
else:
return (3*n)+1
while(True):
print n,"-->",
n=f(n)
if n==1:
print 1
break
|
8312e7ff72ba367295df875c61051c92ff84dc40 | O5-2/computerclub | /week03/week3problemC.py | 646 | 3.609375 | 4 | # Leetcode problem: Find Smallest Letter Greater Than Target (852)
from typing import List
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
for i in range(0, len(letters)):
if (target < letters[i]):
return letters[i]
return letters[0]
s = Solution()
print(s.nextGreatestLetter(["c", "f", "j"], "a"))
print(s.nextGreatestLetter(["c", "f", "j"], "c"))
print(s.nextGreatestLetter(["c", "f", "j"], "d"))
print(s.nextGreatestLetter(["c", "f", "j"], "g"))
print(s.nextGreatestLetter(["c", "f", "j"], "j"))
print(s.nextGreatestLetter(["c", "f", "j"], "k"))
|
57c7c375db5996200d3f55c0a4ed455a0c471c2b | Laura7089/practicalProjects | /week2/funcVersions/question2.py | 388 | 4.0625 | 4 | print("How many hours did you work?")
hours = float(input(">"))
print("How much do you get paid (per hour)?")
salary = float(input(">"))
print("You're owed " + str(hours * salary) + " pounds in ordinary wages.")
if hours > 40:
print("You've worked overtime!")
overtime = hours - 40
print("You're owed " + str(overtime * salary * 0.5) + " pounds in additional overtime pay!")
|
45e2f5141741c57c35ec4129e4781fa96a1a34b5 | SanjayVelu/Python-Programming | /src/vowel.py | 113 | 3.6875 | 4 | n=input
c=["a","e","i","o","u"]
if n in c:
print("vowel")
else:
print("Consonant")
else:
print("Invalid")
|
cb3ac10805523fd2f9284fc03444bdaf76787b76 | masakiaota/kyoupuro | /contests/ABC094/D_BinomialCoefficients.py | 330 | 3.59375 | 4 | n = int(input())
A = list(map(int, input().split()))
a_max = max(A)
def find_nearest(arr, target):
m = min(arr)
dist = abs(m-target)
for a in arr:
if abs(a-target) < dist:
dist = abs(a - target)
m = a
# print(m, dist)
return m
print(a_max, find_nearest(A, a_max/2))
|
dc64788c4cc2b1ecd86135e663a4a53b77b1733e | Yoottana-Prapbuntarik/python-pandas-learning | /write.py | 354 | 3.5 | 4 | import xlsxwriter
import pandas as pd
name = [
"Smith",
"John",
"Prayuth",
"Prawit",]
last_name = [
"Doe",
"Doe",
"Janocha",
"Wongsuwan"
]
df = pd.DataFrame({
'Name': name,
'Last Name': last_name,
})
df.index = range(1,len(df)+1)
writer = pd.ExcelWriter('data.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name="page 1")
writer.save() |
83ac6b7811a8c1dc00aeb47a7f9fdd7b2821a2ee | lmb633/leetcode | /19removeNthFromEnd.py | 536 | 3.5625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
head1 = head
head2 = head
for i in range(n):
head1 = head1.next
if head1 is None:
return head2.next
while head1.next is not None:
head1 = head1.next
head2 = head2.next
head2.next = head2.next.next
return head
|
17ddc701ef79208bc2d5ed055c87a7c7da3504dd | grapefruit623/leetcode | /medium/97_interleavingString.py | 2,971 | 3.828125 | 4 | # -*- coding:utf-8 -*-
#! /usr/bin/python3
import unittest
'''
AC
ref: https://medium.com/@bill800227/leetcode-97-interleaving-string-18b1202fb0ea
'''
class Solution:
def isInterleave(self, s1:str, s2:str, s3:str)->bool:
slen1 = len(s1)
slen2 = len(s2)
slen3 = len(s3)
if s1=="" and s2=="" and s3=="":
return True
if slen1+slen2 != slen3:
return False
'''
Definition of dp[i][j] is
s1[0:j+1] and s2[0:i+1] can combine to s3[0: i+j]
For example
dp[0][1] means s1[0:2] is substring of s3.
'''
dp=[]
for i in range(0, slen2+1):
dp.append( [False]*(slen1+1) )
dp[0][0] = True
for i in range(1, slen2+1):
if s2[i-1] == s3[i-1] and dp[i-1][0] == True:
dp[i][0] = True
for j in range(1, slen1+1):
if s1[j-1] == s3[j-1] and dp[0][j-1] == True:
dp[0][j] = True
for i in range(1, slen2+1):
for j in range(1, slen1+1):
if dp[i][j-1] == False and dp[i-1][j] == False:
dp[i][j] = False
elif dp[i][j-1] == True and s1[j-1] != s3[i+j-1]:
dp[i][j] = False
elif dp[i-1][j] == True and s2[i-1] != s3[i+j-1]:
dp[i][j] = False
else:
'''
dp[i][j-1] and s1[j-1] which means
dp[i][j-1] == True means that
s2[0:i+1] combine s1[0:j-2] can to create s3[0:i+j-2]
Try to concatenate a new char from s1, it index is j-1
If new char from s1 is equals char from s3's current end
then a valid string borned.
'''
if dp[i][j-1] == True and s1[j-1] == s3[i+j-1]:
dp[i][j] = True
if dp[i-1][j] == True and s2[i-1] == s3[i+j-1]:
dp[i][j] = True
return dp[-1][-1]
class Unittest(unittest.TestCase):
def setUp(self):
self.sol=Solution()
def test_case1(self):
s1="aabcc"
s2="dbbca"
s3="aadbbcbcac"
expect=True
self.assertEqual(expect, self.sol.isInterleave(s1, s2, s3))
def test_case2(self):
s1=""
s2=""
s3=""
expect=True
self.assertEqual(expect, self.sol.isInterleave(s1, s2, s3))
'''
WA
'''
def test_case3(self):
s1="a"
s2=""
s3="aa"
expect=False
self.assertEqual(expect, self.sol.isInterleave(s1, s2, s3))
'''
WA
'''
def test_case4(self):
s1="db"
s2="b"
s3="cbb"
expect=False
self.assertEqual(expect, self.sol.isInterleave(s1, s2, s3))
if __name__ == "__main__":
unittest.main()
|
8986a5f65d75c668ec06699bace5287900136817 | ksr19/python_basics | /L6/4.py | 2,104 | 4.0625 | 4 | class Car:
is_police = False
def __init__(self, speed, color, name):
self.speed = speed
self.color = color
self.name = name
def go(self):
print("Машина поехала!")
def stop(self):
print("Машина остановилась!")
def turn(self, direction):
dir_dict = {'r': 'направо', 'l': 'налево'}
print(f"Машина повернула {dir_dict[direction]}.")
def show_speed(self):
print(f"Текущая скорость автомобиля {self.speed} км/ч.")
class TownCar(Car):
max_speed = 60
def show_speed(self):
if self.speed > TownCar.max_speed:
print(f"Максимально разрешенная скорость - {TownCar.max_speed} км/ч. "
f"Текущая скорость - {self.speed} км/ч. Пожалуйста, снизьте скорость!")
else:
print(f"Текущая скорость автомобиля {self.speed} км/ч.")
class SportCar(Car):
pass
class WorkCar(Car):
max_speed = 40
def show_speed(self):
if self.speed > WorkCar.max_speed:
print(f"Максимально разрешенная скорость - {WorkCar.max_speed} км/ч. "
f"Текущая скорость - {self.speed} км/ч. Пожалуйста, снизьте скорость!")
else:
print(f"Текущая скорость автомобиля {self.speed} км/ч.")
class PoliceCar(Car):
is_police = True
car1 = SportCar(200, 'white', 'Audi')
car2 = TownCar(70, 'silver', 'Volkswagen')
car3 = TownCar(50, 'blue', 'Lada')
car4 = WorkCar(50, 'orange', 'Mini')
car5 = WorkCar(39, 'yellow', 'Subaru')
car6 = PoliceCar(90, 'white', 'Ford')
cars = [car1, car2, car3, car4, car5, car6]
for car in cars:
print(f"Модель машины - {car.name}. Цвет - {car.color}. Является полицейской - {car.is_police}.")
car.go()
car.show_speed()
car.turn('r')
car.stop()
|
6f9b1a0ba91c4b7856e4786f6ebb4eb891104dde | LeonardoSaes/Exercicios-python-basico | /python básico/desafio04.py | 206 | 3.953125 | 4 | # calcula a média de dois números
n1 = float(input('Digite a sua nota: '))
n2 = float(input('Digite a outra nota: '))
media = (n1 + n2) / 2
print('Média das notas {} e {} é {} '.format(n1, n2, media))
|
546c3bfcf871df31239dbdd67e7cf2f7ec5210aa | fcxmarquez/GBM_CHALLENGE | /Primer prueba tecnica/number_module.py | 154 | 3.65625 | 4 | def module(a,b):
"""
Esta funcion entrega el numero de
"""
mult=a//b
modulo=a-(b*mult)
print(f"El {a}mod{b} es igual a {modulo}") |
51baa9dea7166db2f80a4e3eb87a7b20b6d56056 | xiangpingli/python_practice | /dict.py | 675 | 3.75 | 4 | #!/usr/bin/python
def dict_test():
dict_test={'hangzhou':'hikvision', 'shenzhen':'huawei', 'beijing':'baidu'}
print dict_test
for key in dict_test.keys():
print "key=%s, value=%s" %(key, dict_test[key])
for key in dict_test:
print "key=%s, value=%s" %(key, dict_test[key])
dict_new = dict_test.copy()
print dict_new
print "len(dict_new):%d" %len(dict_new)
dict_get = dict(American='Newyork', China='Beijing')
print dict_get
print dict_get.keys()
print dict_get.values()
print dict_get.items()
for item in dict_get.items():
print item
dict_test.update(dict_get)
print dict_test
if __name__=='__main__':
dict_test()
|
bc0135de93258057f9ab041fdc94cf3b8863aa10 | VanJoyce/Algorithms-Data-Structures-and-Basic-Programs | /Interview practical 2/task3.py | 791 | 4.28125 | 4 | import task2
def read_text_file(name):
"""
Reads a text file and converts it into a list of strings.
:param name: Name of the text file
:pre-condition: file must be a text file and must be in the same folder as this module. Filename must include the
file extension
:post-condition: each line is an element in the list
:return: list of strings associated to the file
:complexity: best case and worst case are both O(n) where n is the number of lines in the file
"""
list_strings = task2.ListADT()
with open(name) as file:
for line in file:
list_strings.append(line)
if not file.closed:
file.close()
for string in list_strings:
string.strip()
return list_strings |
1fcea0e645418c63763dce921b77aa3a42b9629c | pouxol/TurtleCrossing | /car_manager.py | 849 | 3.71875 | 4 | from turtle import Turtle
import random
import time
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
self.cars = []
self.create_car()
def create_car(self):
self.add_car()
def add_car(self):
random_chance = random.randint(1, 6)
if random_chance == 1:
t = Turtle()
t.penup()
t.color(random.choice(COLORS))
t.shape("square")
t.shapesize(stretch_wid=1, stretch_len=2)
t.setpos(300, random.randint(-250, 250))
t.setheading(180)
self.cars.append(t)
def move_car(self, levelscore=1):
for car in self.cars:
car.forward(STARTING_MOVE_DISTANCE + (levelscore - 1) * MOVE_INCREMENT)
|
0ab5a48497611787a88d5caa08bbc5e9346c6ed3 | ashutoshchaudhary/DataStructuresAndAlgorithms | /DataStructures/LinkedList.py | 922 | 3.90625 | 4 | class LinkedListNode:
def __init__(self, data):
self.data = data
self.next = None
def get_next(self):
return self.next
def get_data(self):
return self.data
class LinkedList:
def __init__(self, data):
node = LinkedListNode(data)
self.head = node
self.tail = node
self.length = 1
def add_node_at_the_end(self, data):
node = LinkedListNode(data)
self.tail.next = node
self.tail = node
self.length += 1
def add_node_at_the_beginning(self, data):
node = LinkedListNode(data)
node.next = self.head
self.head = node
self.length += 1
def add_node_at_position(self, position):
pass
def remove_node_from_the_beginning(self):
pass
def remove_node_from_the_end(self):
pass
def remove_node_from_position(self, position):
pass |
2dc556143d1934db36ac5ffe29124456e6afd4d3 | nitintr/CodeChef-Programming | /1.Sum-of-Digits-using-char.py | 172 | 3.59375 | 4 | def func():
t=int(input(""))
while t > 0:
n=input("")
ans=0
for x in n: ans+=( ord(x) - ord('0') );
print(ans)
t=t-1
func()
|
36c81d06cf3080ef9cdbe2afc5fb416344b32623 | toromeike/euler | /Problem 4/sol.py | 436 | 3.921875 | 4 | def is_palindrome(x):
'''
Checks if an integer or string is a palindrome
'''
s = str(x)
return s == s[::-1]
palindromes = []
#Rather inefficient looping. More efficient would be a zig-zag path through
#the outer product (999:100)^T * (999:100)
for i in range(999,99,-1):
for j in range(999,99,-1):
p = i*j
if is_palindrome(p):
palindromes.append(p)
print(max(palindromes))
|
b07c87c4ed647e0f201702b5395139acf584e62c | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/3119/codes/1667_2966.py | 234 | 3.59375 | 4 | m = input("MULHER? S ou N? ")
ingresso = float(input("Valor integral do ingresso: "))
quant = int(input("Quantidade de ingressos: "))
if( m == "S"):
msg = (ingresso * 0.80) * quant
else:
msg = ingresso * quant
print(round(msg, 2)) |
08f8f8a5d3e0389176e23dffd1f0bbb8a87e1ff7 | michaelstresing/python_fundamentals | /04_conditionals_loops/03_08_table.py | 968 | 4.0625 | 4 | '''
Use a loop to print the following table to the console:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
'''
'''
for num in range(0, 50):
if num == 9:
print(9)
elif num == 19:
print(19)
elif num == 29:
print(29)
elif num == 39:
print(39)
else:
print(num, end=' ')
print()
#again, this feel less sohpisticated than a proper solution to the question....
for num in range(0,10):
print(num, end=' ')
print()
for num in range(11,20):
print(num, end=' ')
print()
for num in range(21,30):
print(num, end=' ')
print()
for num in range(31,40):
print(num, end=' ')
print()
for num in range(41,50):
print(num, end=' ')
'''
#pleased with this one...
r = 1
while r < 50:
if (r + 1) % 10 != 0:
print(r, end= " ")
r += 1
else:
print(r)
r += 1
|
64e52e9f567b3a77aeb623a66962923a45551cec | jiangweiguang/leecode | /字符串/简单/亲密字符串/buddyStrings.py | 650 | 3.65625 | 4 | def buddyStrings(A:str,B:str):
#长度不同时
if len(A) != len(B):
return False
#两个字符串相等,若A中有重复元素,则返回TRUE
if A == B and len(set(A)) < len(A):
return True
#使用zip进行匹配对比,挑出不同的字符对(python真的灵活啊)
dif = [(a,b) for a,b in zip(A,B) if a != b]
#对数只能为2,并且对称,如(a,b),(b,a)
return len(dif) == 2 and dif[0] == dif[1][::-1]
if __name__ =="__main__":
with open('data.txt') as data:
nums = data.read().split('\n')
for i in range(0,len(nums),2):
print(buddyStrings(nums[i],nums[i+1])) |
73399c92e8ecb3d8a4a04f2e0fa8b0e84f8c7f22 | jaeyoung-jane-choi/2019_Indiana_University | /Intro-to-Programming/test02/test02practical1.py | 983 | 4.21875 | 4 |
#Jane Choi , janechoi
##1
def addItemToList(l,i):
"""Recieves a list, item and append the item to the list
list, string -> list """
#the item is appended to the list
l.append(i)
#returns the list
return l
print("""Add as many items to the bicycle as you want. When you're done, enter
'nothing'.""")
#before the while loop .. we need
#a empty list
itemlist = []
#the user input object
user_input =''
while user_input != 'nothing':
#while the user input is not nothing
#ask the user input first (since our user input is '' at first )
user_input = input('What do you want add to the bicycle now?')
#now use the function addItemToList , and append the input
addItemToList(itemlist, user_input)
print('Okay')
#since the itemlist includes nothing, for both length and list we substract the nothing value
itemlist.remove('nothing')
print( 'There are ' +str(len(itemlist))+ ' items added to the bicycle: ' +str(itemlist))
|
b1a5ce1ad02f550e8f1f233ba23b7b0ca19b20dc | imademethink/MachineLearning_related_Python | /prg01_basic_python/basicpython04_array_and_matrix.py | 1,444 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
array_1_d = ["emp_01","sales",30000, 0.4]
array_2_d = [array_1_d, ["emp_02","prod",40000, 0.45], ["emp_03","procurement",350000, 0.5]]
print ("array_1_d == ",array_1_d)
print ("array_1_d.index(\"sales\") == ",array_1_d.index("sales"))
array_1_d.remove(0.4)
print ("array_1_d after remove(0.4) == ",array_1_d)
array_1_d.insert(len(array_1_d),0.4)
print ("array_1_d after insert(len(array_1_d),0.4) == ",array_1_d)
array_1_d.pop(2)
print ("array_1_d after pop(2) == ",array_1_d)
print ("array_1_d == ",array_1_d)
print ("array_2_d[1] == ",array_2_d[1])
print ("array_2_d == ",array_2_d)
print ("array_2_d.index([\"emp_03\",\"procurement\",350000, 0.5]) == ",array_2_d.index(["emp_03","procurement",350000, 0.5]))
print("access array elements using simple for loop")
for i in range(len(array_2_d)):
for j in range(len(array_2_d[i])):
print (array_2_d[i][j]," ",end="")
print()
print("\n")
print("access array elements using simple for loop part 2")
for row in array_2_d:
for e in row:
print (e," ",end="")
print()
print("\n")
myarr=[
[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13,14,15]]
print("myarr = ",myarr)
print("myarr[3] = ",myarr[3])
print("myarr[3][0]= ",myarr[3][0])
print("myarr[1:3]= ",myarr[1:3]) # only row 1 to row 3
print("\n")
|
a46e89252a2c21ef99e9472f04e06a4fbf5c5ba2 | award96/teach_python | /I-lists.py | 1,011 | 4.125 | 4 | """
Lists are the most common non-primitive. They represent lists of things, ie [0, 2, 4, 6, 8]
They are mutable
Objects have methods. These are things that can be done by or to the object, by the object.
Object methods are almost always written
object.method()
the exception being the len(object) method which returns the length of the list or string.
The main 'methods' lists have:
len(list) - the number of values in the list
list.append(x) - increase the length of the list by one. Put x at the end of the list.
list[index] - index is an integer. Return the value from that location in the list
lists are indexed 0 to len(list) - 1
[0, 1, 2, 3] -> a list of length 4. list[1] returns 1.
"""
lst = [0, 1, 2, 3]
print(f"\ntype(x) = {type(lst)}")
print(f"lst = {lst}")
print(f"lst[0] = {lst[0]}")
print(f"lst[1] = {lst[1]}")
print(f"lst[-1] = {lst[-1]}") # negative indices go through the list in reverse. -1 is the last value. -2 is the second to last value
|
b7a9dc62d800797e63963c3b3121319d0f7f1020 | angeldeng/LearnPython | /Python100days/Day7/set.py | 502 | 4.15625 | 4 | # 集合
set1 = {1, 2, 3, 3, 2, 2}
# 集合会自动去重
print(set1)
print(type(set1))
print('length=', len(set1))
set2 = set(range(1, 10))
set3 = set((1, 2, 3, 3, 2, 1))
print(set2, set3)
# 创建集合的推导式语法
# set4 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0}
# print(set4)
print(set1 & set2)
print(set1 | set2)
# print(set1 - set2)
print(set1.difference(set2))
print(set1 ^ set2)
#判断子集和超集合
print(set2<set1)
print(set3<set1)
print(set3>=set1)
|
7f83ed3c9632afd96270b4e4a029f3ed3b551fa6 | zmh19941223/heimatest2021 | /04、 python编程/day08/3-code/08-覆盖父类方法.py | 347 | 3.703125 | 4 | class animal:
def sleep(self):
print("睡")
def eat(self):
print("吃")
class dog(animal):
def eat(self): # 出现和父类同名方法,在子类dog中,就没有父类的eat方法了
print("吃肉")
d = dog()
d.sleep()
d.eat() # 由于覆盖了父类的eat方法,,所以这里调用的是dog类的eat方法 |
2f7c698cf679059f55fbf0ca0fab9332fc3397f2 | gogiasss/stoloto_random | /lottery.py | 582 | 3.6875 | 4 | from random import sample
lotts = int(input("Введите КОНЕЧНОЕ число в лотерее, например 36 или 45: "))
nums = int(input("Введите сколько цифр отметить (например 5 или 6: "))
count = int(input("Введите количество комбинаций: "))
# Создаем список
numbers = [n for n in range(1,lotts+1)]
# Генерируем количество комбинаций
for i in range(count):
combination = sample(numbers, nums)
print(combination)
|
f2a880369dbf6b73a1b9b29c93666025353f626a | PandaHero/data_structure_algorithms | /data_algorithms/shell_sort.py | 534 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2018/12/10 11:58
@Author : TianCi
@File : shell_sort.py
@Software: PyCharm
@desc:希尔排序
"""
li = [5, 4, 3, 2, 1]
def shell_sort(li):
n = len(li)
gap = n // 2 # 步长增量
while gap > 0:
for i in range(gap, n):
j = i
while j >= gap and li[j] < li[j - gap]:
li[j], li[j - gap] = li[j - gap], li[j]
j -= gap
gap = gap // 2
return li
print(shell_sort(li))
shell_sort(li)
|
cc90715dcf7f39203b7f8d7e77ba47418fdff153 | PhilPore/Factor_Tree | /factortree.py | 1,873 | 3.796875 | 4 | import sys
import math
class Tree_Node:
def __init__(self, val):
self.val = val
self.left = None #this will be the prime
self.right = None #always move down this way
class Bin_Tree:
def __init__(self, head):
self.root = head
def In_Order(self,head):
#trav = head
print(head.val)
if head.left:
self.In_Order(head.left)
if head.right:
self.In_Order(head.right)
#padding = ""
def make_fact_tree(prime_list, value, F_Tree):
iteri = F_Tree.root
factor_list = []
factored_vars = None
cur_val = value
ind = 0
print(f"Value sent in {value}")
while cur_val > 1:
prime_check = math.sqrt(cur_val)
#print(f"prime check {prime_check}")
#print(f"cur_val {cur_val}")
for i in prime_list:
if cur_val%i == 0:
factor_list.append(i)
cur_val//=i
iteri.left = Tree_Node(i)
iteri.right = Tree_Node(cur_val)
iteri = iteri.right
#print(f"In prime check. Vals cur: {cur_val} {cur_val*i} {i}")
break
if i > prime_check:
factor_list.append(cur_val)
cur_val/=cur_val
break
ind+=1
print(f"Prime Factor list {factor_list}")
return factor_list
arg1 = int(sys.argv[1])
r_file = open("primes.txt","r")
prime_list = r_file.read().split(",")
print(len(prime_list))
for i in range(len(prime_list)):
prime_list[i] = int(prime_list[i])
#print(prime_list[-1])
Factor_Node = Tree_Node(arg1)
Factor_Tree = Bin_Tree(Factor_Node)
make_fact_tree(prime_list,arg1, Factor_Tree)
Factor_Tree.In_Order(Factor_Tree.root)
#print(type(prime_list[-1]))
|
2690b9a3e7a11371e3b63b801c1a1dbab257cb8e | CoderFemi/AlgorithmsDataStructures | /practice_challenges/python/alternating_characters.py | 472 | 4.15625 | 4 | def alternatingCharacters(string_letters) -> int:
"""Calculate minimum number of characters to be removed"""
prev_char = ""
count = 0
for char in string_letters:
if char == prev_char:
count += 1
prev_char = char
return count
print(alternatingCharacters("AAAA"))
print(alternatingCharacters("BBBBB"))
print(alternatingCharacters("ABABABAB"))
print(alternatingCharacters("BABABA"))
print(alternatingCharacters("AAABBB"))
|
2e37840b0c5f758ae40ad31478583ce62bbe9bb9 | shaukhk01/project01 | /pro78.py | 179 | 3.5625 | 4 | def main():
class p:
def m1(self):
a = 'parent overriding'
class p2(p):
def m1(self):
print(self.a)
c = p2()
c.m1()
main()
|
d5334d105dcaf5862bd85fc54b9690f61e8ce7e0 | Ardric/School-Projects | /Python Code/Assignment 2/Stats on Temperature data from user.py | 1,211 | 4.1875 | 4 | #Daniel Lowdermilk
#This program takes input from the user until they either type done or enter 10 temperatures
#below 32. It then tells you the average of all temperatures, the max temp, the min temp,
#how many were above 90 and how many were below 32.
#Default Variables
x = ""
y = 0
low = 100
high = 0
count_high = 0
count_low = 0
count = 0
z = 0
print ("Please input temperatures, the program will stop either when you enter 10 numbers below 32 or when you type done.")
while x != "done" :
x = input("Please enter a number: ")
if x == "done":
break
count = count + 1
y = int(x)
z = z + y
if y < low :
low = y
if y > high :
high = y
if y > 90 :
count_high = count_high + 1
if y < 32 :
count_low = count_low + 1
if count_low == 10:
break
average = z / count
print ("The average of all temperatures that were entered is: ", average)
print ("The minimum temperature entered was: ", low)
print ("The highest temperature entered was: ", high)
print ("There were", count_high, "temperatures above 90.")
print ("There were", count_low, "temperatures below 32.")
|
5f253160af97ad99b7ade40fcbd3d9b3873dbe28 | sanu11/Codes | /HackerRank/HeightOfBinaryTree.py | 1,968 | 3.890625 | 4 | class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
if self.root == None:
self.root = Node(val)
else:
current = self.root
while True:
if val < current.info:
if current.left:
current = current.left
else:
current.left = Node(val)
break
elif val > current.info:
if current.right:
current = current.right
else:
current.right = Node(val)
break
else:
break
# Enter your code here. Read input from STDIN. Print output to STDOUT
'''
class Node:
def __init__(self,info):
self.info = info
self.left = None
self.right = None
// this is a node of the tree , which contains info as data, left , right
'''
def recur(root):
if root != None:
h1 = recur(root.left)
h2 = recur(root.right)
mx = max(h1,h2)+1
return mx
else:
return 0
def height3(root):
if(root==None):
return 0
q = []
q.insert(0,root)
height=0
while(1):
nodeCount = len(q)
if(nodeCount==0):
return height
height+=1
while nodeCount!=0:
temp = q.pop()
if(temp.left!= None):
q.insert(0,temp.left)
if(temp.right!=None):
q.insert(0,temp.right)
nodeCount-=1
def height(root):
# return iterative(root)-1
return recur(root)-1
|
f5bc88a63e52dd01cfc23eacfa5b118767f64a87 | tim24jones/algs_and_datastructs | /Chap_5/11unfinished.py | 499 | 3.875 | 4 | def bubbleSort(alist): #going in both directions, useful for stacks
for a in range (len(alist)//2):
while (i+1<len(alist)):
if alist[i]>alist[i+1]:
alist[i],alist[i+1]=alist[i+1],alist[i]
i=i+2
if len(alist%2==0:
i=len(alist)-1
else:
i=len(alist)
while (i>0):
if alist[i]<alist[i-1]:
alist[i-1],alist[i]=alist[i],alist[i-1] |
3ca563dbfb07b2830cfc160a7332bb0265aa2076 | vitaliytsoy/problem_solving | /python/medium/spiral_matrix.py | 1,601 | 3.984375 | 4 | """
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
"""
from typing import List
class Solution:
def spiral_order(self, matrix: List[List[int]]) -> List[int]:
row_len = len(matrix[0])
col_len = len(matrix)
top, right, bottom, left = 0, 0, 0, 0
items_count = row_len * col_len
result = []
while len(result) < items_count:
min_iter = min(left, right, top, bottom)
if top == right and min_iter == top:
for i in range (0 + left, row_len - right):
result.append(matrix[top][i])
top += 1
continue
if right == bottom and min_iter == bottom:
for i in range (0 + top, col_len - bottom):
result.append(matrix[i][row_len - right -1])
right += 1
continue
if bottom == left and min_iter == bottom:
for i in range (row_len - right -1, 0 + left - 1, -1):
result.append(matrix[(col_len - 1) - bottom][i])
bottom += 1
continue
if left + 1 == top and min_iter == left:
for i in range (col_len - bottom - 1, 0 + top - 1, -1):
result.append(matrix[i][left])
left += 1
continue
return result
solution = Solution()
print(solution.spiral_order([[1,2,3,4],[5,6,7,8],[9,10,11,12]]))
|
4db4133db2bd3ca59568097789edf9b8e4fda3dc | Bouyssounade/Trabalho | /ex2.py | 266 | 3.796875 | 4 | """
Programa ex22.py
Descrição: Digitando valor para variável insumo
Autor: Gabriel Souto Ribeiro Bouyssounade
Data: 25/05/2018
Versão: 0.0.1
"""
# Entrada de dados
insumo = float(input('Informe a quantidade de insumo:'))
# Saída de dados
print('O insumo é de:', insumo)
|
02c11111e09ee21a865431daf02de586a719b66d | YoungGaLee/Basic_Python | /Day_06/Let's Review_2_KYH.py | 207 | 3.6875 | 4 | i=int(input())
for T in range(i):
S=input()
odd=""
even=""
for j in range(len(S)):
if j%2==0:
even+=S[j]
if j%2==1:
odd+=S[j]
print(even,odd)
|
190dc48e4236425128d82047b5308ab7df253ed4 | devbaggett/python_algorithms | /anagram_check.py | 1,427 | 4.03125 | 4 | # anagram_check - verifies if two strings are anagrams
# ignores whitespace
# import tests
from tests.tests import AnagramTest
# solution 1
def anagram(s1, s2):
s1_dict = {}
s2_dict = {}
s1 = s1.lower()
s2 = s2.lower()
for char in s1:
if char != ' ':
if char not in s1_dict:
s1_dict[char] = 1
else:
s1_dict[char] += 1
for char in s2:
if char != ' ':
if char not in s2_dict:
s2_dict[char] = 1
else:
s2_dict[char] += 1
for key in s1_dict:
if key not in s2_dict or s1_dict[key] != s2_dict[key]:
return False
return True
# solution 2
def anagram2(s1, s2):
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
return sorted(s1) == sorted(s2)
# solution 3
def anagram3(s1, s2):
s1 = s1.replace(' ', '').lower()
s2 = s2.replace(' ', '').lower()
# edge case check
if len(s1) != len(s2):
return False
count = {}
for char in s1:
if char in count:
count[char] += 1
else:
count[char] = 1
for char in s2:
if char in count:
count[char] -= 1
else:
count[char] = 1
for key in count:
if count[key] != 0:
return False
return True
# run tests
t = AnagramTest()
t.test(anagram)
|
2bc79be200bb00e77c93efe53ea1ef5ef599bff3 | p77921354/260201061 | /lab5/1.py | 108 | 3.921875 | 4 | num = input("Enter an integer: ")
for i in range(1,11):
print(num + " x " + str(i) + " = ", int(num) * i ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.