blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
96df74099fa7a2432fb2796df8f440948bf76277 | f-bandet/Where-s-The-Money | /wheres_the_money.py | 4,730 | 4.21875 | 4 | ###
### Author: Faye Bandet
### Description: Welcome to Where's The Money! This is a program that helps a user
### visualize and understand how much money they spend of various categories of expenditures.
###
from os import _exit as exit
### Greeting statement
print ('-----------------------------')
print ("----- WHERE'S THE MONEY -----")
print ('-----------------------------')
### Checking for numbers
a_s = input ('What is your annual salary? \n')
if a_s.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
a_s = float (a_s)
m_r = input ('How much is your monthly mortgage/rent? \n')
if m_r.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
m_r = float (m_r)
b = input ('What do you spend on bills monthly? \n')
if b.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
b = float (b)
f = input ('What are your weekly grocery/food expenses? \n')
if f.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
f = float (f)
tr = input ('How much do you spend on travel annually? \n')
if tr.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
tr = float (tr)
ta = input ('Tax percentage? \n')
if ta.isnumeric() == False:
print ('Must enter positive integer number.')
exit (0)
ta = float(ta)
### TAX STATEMENTS
### I added a lowercase x when I transitioned variables.
### Basic input functions
if(ta<100):
print()
tax = (ta / 100.0) * a_s
taxx = (tax / a_s) * 100
if ta <0 or ta >100:
print ('Tax must be between 0% and 100%.')
exit (0)
m_rx = ((m_r * 12) / a_s) * 100
bx = ((b * 12) / a_s) * 100
fx = ((f * 52) / a_s) * 100
trx = ((tr) / a_s) * 100
e = (a_s) - (m_r * 12) - (b * 12) - (f * 52) - (tr) - (tax)
ex = (e / a_s) * 100
### Print the financial break down statement
if m_rx >= bx and m_rx >= fx \
and m_rx >= trx and m_rx >= taxx and m_rx >= ex:
print ('-' * 41 + '-' * int(m_rx))
if bx >= m_rx and bx >= fx \
and bx >= trx and bx >= taxx and bx >= ex:
print ('-' * 41 + '-' * int(bx))
if fx >= bx and fx >= m_rx \
and fx >= trx and fx >= taxx and fx >= ex:
print ('-' * 41 + '-' * int(fx))
if trx >= bx and trx >= fx \
and trx >= m_rx and trx >= taxx and trx >= ex:
print ('-' * 41 + '-' * int(trx))
if taxx >= bx and taxx >= fx and taxx >= trx \
and taxx >= m_rx and taxx >= ex:
print ('-' * 41 + '-' * int(taxx))
if ex >= bx and ex >= fx and ex >= trx \
and ex >= trx and ex >= taxx and ex >= m_rx:
print ('-' * 41 + '-' * int(ex))
print ('See the financial breakdown below, based on a salary of', '$' + format(a_s, '.0f'))
if m_rx >= bx and m_rx >= fx \
and m_rx >= trx and m_rx >= taxx and m_rx >= ex:
print ('-' * 41 + '-' * int(m_rx))
if bx >= m_rx and bx >= fx \
and bx >= trx and bx >= taxx and bx >= ex:
print ('-' * 41 + '-' * int(bx))
if fx >= bx and fx >= m_rx \
and fx >= trx and fx >= taxx and fx >= ex:
print ('-' * 41 + '-' * int(fx))
if trx >= bx and trx >= fx \
and trx >= m_rx and trx >= taxx and trx >= ex:
print ('-' * 41 + '-' * int(trx))
if taxx >= bx and taxx >= fx and taxx >= trx \
and taxx >= m_rx and taxx >= ex:
print ('-' * 41 + '-' * int(taxx))
if ex >= bx and ex >= fx and ex >= trx \
and ex >= trx and ex >= taxx and ex >= m_rx:
print ('-' * 41 + '-' * int(ex))
###formatting
print('| mortgage/rent | $' + format (m_r * 12, '10,.0f'), '|' +
format (m_rx, '6,.1f') + '% |', '#' * int (m_rx))
print('| bills | $' + format (b * 12, '10,.0f'), '|' +
format (bx, '6,.1f') + '% |', '#' * int (bx))
print('| food | $' + format (f * 52, '10,.0f'), '|' +
format (fx, '6,.1f') + '% |', '#' * int (fx))
print('| travel | $' + format (tr, '10,.0f'), '|' +
format (trx, '6,.1f') + '% |', '#' * int (trx))
print('| tax | $' + format (tax, '10,.1f'), '|' +
format (taxx, '6,.1f') + '% |', '#' * int (taxx))
print('| extra | $' + format (e, '10,.1f'), '|' +
format (ex, '6,.1f') + '% |', '#' * int (ex))
if m_rx >= bx and m_rx >= fx \
and m_rx >= trx and m_rx >= taxx and m_rx >= ex:
print ('-' * 41 + '-' * int(m_rx))
if bx >= m_rx and bx >= fx \
and bx >= trx and bx >= taxx and bx >= ex:
print ('-' * 41 + '-' * int(bx))
if fx >= bx and fx >= m_rx \
and fx >= trx and fx >= taxx and fx >= ex:
print ('-' * 41 + '-' * int(fx))
if trx >= bx and trx >= fx \
and trx >= m_rx and trx >= taxx and trx >= ex:
print ('-' * 41 + '-' * int(trx))
if taxx >= bx and taxx >= fx and taxx >= trx \
and taxx >= m_rx and taxx >= ex:
print ('-' * 41 + '-' * int(taxx))
if ex >= bx and ex >= fx and ex >= trx \
and ex >= trx and ex >= taxx and ex >= m_rx:
print ('-' * 41 + '-' * int(ex))
exit (0) |
a35e944774f76b40797b0d0b03cd97159e2a9a9b | SYiH/little_games_things | /knb.py | 2,356 | 3.90625 | 4 | import random, sys
while True:
while True:
b=('камень','ножницы','бумага')
usr=input('Камень, ножницы или бумага? Для выхода: "Выход" ')
usr=usr.lower()
if usr=='выход':
sys.exit()
elif usr.isalpha()==False:
print('Неверное значение, попробуйте снова.')
elif usr not in b:
print('Неверное значение, попробуйте снова.')
else:
break
pc=random.choice(b)
usr=usr.capitalize()
pc=pc.capitalize()
if pc==usr:
print('Ничья')
elif usr=='Ножницы' and pc=='Бумага': #Ножницы и бумага
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Вы победили!'
)
elif usr=='Бумага' and pc=='Ножницы': #Ножницы и бумага
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Компьютер победил!'
)
elif usr=='Камень' and pc=='Ножницы': #Ножницы и камень
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Вы победили!'
)
elif usr=='Ножницы' and pc=='Камень': #Ножницы и камень
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Компьютер победил!'
)
elif usr=='Камень' and pc=='Бумага': #Камень и бумага
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Компьютер победил!'
)
elif usr=='Бумага' and pc=='Камень': #Камень и бумага
print(
'Ваш ответ: ',usr,',',
'Ответ компьютера: ',pc,',',
'Вы победили!'
)
#else:
# while True:
# print('FATAL ERROR, DESTRUCTING PC')
|
671ee10d18931cda87cf94638f47747616eaed1c | RyanFatsena/Python_C11_BekerjaDenganDateTime | /Prak1C11.py | 601 | 3.84375 | 4 | #1
from datetime import *
def diffDate(i) :
listTgl = i.split("-")
dateList = []
for x in listTgl :
dateList.append(int(x))
kemarin = date(dateList[0], dateList[1], dateList[2])
hariIni = datetime.date(datetime.now())
delta = kemarin - hariIni
hasil = delta.days
return hasil
try :
tanggal = input("Masukkan tanggal yang anda inginkan berformat (yyyy-mm-dd) : ")
hasil = diffDate(tanggal)
print("Selisih tanggal {0} dengan hari ini adalah {1} hari".format(tanggal, hasil))
except ValueError :
print("Masukkan tanggal yang benar")
|
aad0123b1cbabad5f0fb0f9196628f0a853d28bb | jsteinhauser/Transparent-conductor-solver | /TClayer_GUI.py | 4,917 | 3.515625 | 4 | ## Import
import tkinter as tk
import TClayer as TC
from decimal import Decimal
## GUI
class GUI(tk.Frame):
""" Main GUI heritate from tkinter Frame """
def __init__(self): # Constructor
self.mainFrame = tk.Frame().pack() # Main frame
self.buildGUI() # launch widget builder
def stdInput (self, text):
""" helper function to build a std label-entry"""
self.entryFrame = tk.Frame(self.mainFrame)
tk.Label(self.entryFrame,text=text,width=25,anchor=tk.E).pack(side=tk.LEFT)
self.myEntry = tk.Entry(self.entryFrame,width=10)
self.myEntry.pack(side=tk.LEFT,padx=5,pady=2)
self.entryFrame.pack(side=tk.TOP)
return self.myEntry
def buildGUI (self):
""" Build the GUI """
self.picture = tk.PhotoImage(file = "Formula.gif")
formula = tk.Label(self.mainFrame,image=self.picture,
background="white")
formula.pack(anchor=tk.E, fill=tk.X)
tk.Label(self.mainFrame,background="white",
text="\nEnter known parameters and press 'solve'\n").pack(anchor=tk.E, fill=tk.X)
self.inputList = ['Thickness (nm) :',
'Sheet resistance (Ohms-square) :',
'Resistivity (Ohms.cm) :',
'Conductivity (S) :',
'Mobility (cm2.V-1.s-1) :',
'Carrier density (cm-3) :'
]
self.entries=[]
for str in self.inputList :
self.thisEntry = self.stdInput(str)
self.entries.append(self.thisEntry)
self.buttonFrame=tk.Frame()
self.clearAllButton = tk.Button(self.buttonFrame,text="Clear", width=12,
command=self.clearAll)
self.clearAllButton.bind("<Return>", self.clearAllWrapper)
self.clearAllButton.pack(side=tk.LEFT,padx=5)
self.solveButton=tk.Button(self.buttonFrame,text="Solve", width=12,
command=self.solve)
self.solveButton.bind("<Return>", self.solveWrapper)
self.solveButton.pack(side=tk.LEFT,padx=5)
self.solveButton.focus_force()
self.buttonFrame.pack(anchor=tk.E,pady=7)
self.msg = tk.StringVar()
self.statusBar = tk.Label(self.mainFrame,background="gray",
textvariable=self.msg, justify=tk.LEFT)
self.statusBar.pack(anchor=tk.E, fill=tk.X)
# Callbacks
def solveWrapper(self,event):
self.solve()
def solve(self):
""" Solve and display"""
values=[] # Get values
for object in self.entries:
val = object.get()
try:
val=float(val)
values.append(val)
except ValueError:
values.append(None)
thisTC = TC.TClayer(values[0],values[1],values[2],
values[3],values[4],values[5]) # Instantiate a TClayer
thisTC.solve() # Solve it
values=[thisTC.getThickness(), # Get the output values
(thisTC.getSheetResistance()),
(thisTC.getResistivity()),
(thisTC.getConductivity()),
(thisTC.getMobility()),
(thisTC.getCarrierDensity())]
i=0
for object in self.entries: # Display output values
object.delete(0,tk.END) # Delete entry content
if i in [0,3]:
try:
object.insert(0,"%.0f"%values[i]) # Display and format the output value if exist
except:
pass
if i in [1,4]:
try:
object.insert(0,"%.1f"%values[i])
except:
pass
if i in [2]:
try:
object.insert(0,"%.2e"%values[i])
except:
pass
if i in [5]:
try:
object.insert(0,"%.1e"%values[i])
except:
pass
i=i+1
self.msg.set(thisTC.getMsg()[:-1])
def clearAllWrapper(self,event):
self.clearAll()
def clearAll(self):
""" clear all entries """
for object in self.entries:
object.delete(0,tk.END)
self.msg.set("")
## init GUI
root = tk.Tk() # Build main window
root.title("TC-solver")
app = GUI() # Instantiate the GUI
root.mainloop() # Run event loop on main window
|
a18a4d56a8863c6112864ba0958ece31ea5d24d7 | longshuicui/leetcode-learning | /04.排序/692. 前K个高频单词(Medium).py | 1,435 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/5/20
@function:
692. 前K个高频单词 (Medium)
https://leetcode-cn.com/problems/top-k-frequent-words/
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
示例 1:
输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。 注意,按字母顺序 "i" 在 "love" 之前。
示例 2:
输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,出现次数依次为 4, 3, 2 和 1 次。
"""
def topKFrequent(words, k):
freq={} # 时间复杂度O(n), 空间复杂度O(l)
for word in words:
freq[word]=freq.get(word,0)+1
freq=sorted(freq.items(), key=lambda x:x[0], reverse=False) # 时间复杂度O(nlogn),空间复杂度O(logn)
freq=sorted(freq, key=lambda x:x[1], reverse=True) # # 时间复杂度O(nlogn),空间复杂度O(logn)
res=[]
for i in range(k):
res.append(freq[i][0])
return res
words=["i", "love", "leetcode", "i", "love", "coding"]
k=3
res=topKFrequent(words, k)
print(res) |
0826e56877d23ee9a6012dd2d8f0f89d0367fed5 | longshuicui/leetcode-learning | /01.贪心算法/区间问题/763.Partition Labels (Medium).py | 1,048 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/02/15
@function:
763. Partition Labels (Medium)
https://leetcode.com/problems/partition-labels/
A string S of lowercase English letters is given.
We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
"""
def partitionLabels(s):
# 统计每个字母出现的始末位置,变成区间问题
last={c:i for i,c in enumerate(s)}
j=anchor=0
ans=[]
for i,c in enumerate(s):
j=max(j,last[c])
if i==j:
ans.append(i-anchor+1)
anchor=i+1
return ans
s="ababcbacadefegdehijhklij"
res=partitionLabels(s)
print(res)
|
19c9392ec1edf3b17fec038531959b09e3184bdd | longshuicui/leetcode-learning | /08.数据结构/数组/48.Rotate Image (Medium).py | 944 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/3
@function:
48. Rotate Image (Medium)
https://leetcode.com/problems/rotate-image/
题目描述
给定一个 n × n 的矩阵,求它顺时针旋转 90 度的结果,且必须在原矩阵上修改(in-place)。O(1)空间复杂度
输入输出样例
输入和输出都是一个二维整数矩阵。
Input:
[[1,2,3],
[4,5,6],
[7,8,9]]
Output:
[[7,4,1],
[8,5,2],
[9,6,3]]
题解
每次只考虑四个间隔90度的位置,可以进行O(1)的额外空间旋转
"""
def rotate(matrix):
n=len(matrix)-1
for i in range(n//2+1):
for j in range(i,n-i):
matrix[j][n-i],matrix[i][j],matrix[n-j][i],matrix[n-i][n-j]=\
matrix[i][j],matrix[n-j][i],matrix[n-i][n-j],matrix[j][n-i]
return matrix
matrix=[[1,2,3],[4,5,6],[7,8,9]]
matrix=rotate(matrix)
print(matrix) |
d32283fbe67015b2ac7c4aefeedda87da1acd33b | longshuicui/leetcode-learning | /08.数据结构/优先队列(堆排序)/priority_queue.py | 2,033 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/4
@function:
优先队列
可以在O(1)时间内获得最大值,并且在O(logn)时间内取出最大值和插入任意值
优先队列常常用堆来实现。堆是一个完全二叉树。其父节点的值总是大于等于子节点的值。堆得实现用数组 ,
堆的实现方法:
核心操作是上浮和下沉 :如果一个节点比父节点大,那么交换这两个节点;交换过后可能还会比新的父节点大,
因此需要不断的进行比较和交换操作,这个过程叫上浮;类似的,如果一个节点比父节点小,也需要不断的向下
比较和交换操作,这个过程叫下沉。如果一个节点有两个子节点,交换最大的子节点。
维护的是数据结构的大于关系
"""
class PriorityQueue:
def __init__(self,maxSize):
"""初始化一个数组,构建完全二叉树"""
self.heap=[]
self.maxSize=maxSize
def top(self):
"""返回堆的根节点-最大值"""
return self.heap[0]
def swim(self,pos):
"""上浮"""
while pos>1 and self.heap[pos//2]<self.heap[pos]:
self.heap[pos//2], self.heap[pos]=self.heap[pos],self.heap[pos//2]
pos//=2
def sink(self,pos):
while 2*pos<=self.maxSize:
i=2*pos
if i<self.maxSize and self.heap[i]<self.heap[i+1]:
i+=1
if self.heap[pos]>=self.heap[i]:
break
self.heap[pos], self.heap[i]=self.heap[i], self.heap[pos]
pos=i
def push(self, k):
"""插入任意值,把新的数字放在最后一位ie,然后上浮"""
self.heap.append(k)
self.swim(len(self.heap)-1)
def pop(self):
self.heap[0], self.heap[-1]=self.heap[-1], self.heap[0]
self.heap.pop()
self.sink(0)
queue=PriorityQueue(10)
values=[5,4,8,6,2,7,1,3]
for val in values:
queue.push(val)
print(queue.heap) |
d37fd9b2691a2cb11cd6c6d92fd428e32b773153 | longshuicui/leetcode-learning | /09.字符串/字符串比较/242.Valid Anagram (Easy).py | 907 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/7
@function:
242. Valid Anagram (Easy)
https://leetcode.com/problems/valid-anagram/
题目描述
判断两个字符串包含的字符是否 完全相同 (不考虑顺序)。
输入输出样例
输入两个字符串,输出一个布尔值,表示两个字符串是否满足条件。
Input: s = "anagram", t = "nagaram"
Output: true
题解
使用哈希表或者数组统计两个字符串中每个字符出现的 频次 ,若频次相同 则说明他们包含的字符完全相同
"""
def isAnagram(s,t):
if len(s)!=len(t):
return False
counts={chr(i):0 for i in range(97,97+26)}
for i in range(len(s)):
counts[s[i]]+=1
counts[t[i]]-=1
for c in counts:
if counts[c]:
return False
return True
s = "anagram"
t = "nagaram"
ans=isAnagram(s,t)
print(ans) |
4c368fcf33423a8da4337c71271649d8cdcb93f4 | longshuicui/leetcode-learning | /12.数学/263. 丑数(Easy).py | 786 | 4 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/04/10
@function:
263. 丑数 (Easy)
https://leetcode-cn.com/problems/ugly-number/
给你一个整数 n ,请你判断 n 是否为 丑数 。如果是,返回 true ;否则,返回 false 。
丑数 就是只包含质因数 2、3 和/或 5 的正整数。
示例 1:
输入:n = 6
输出:true
解释:6 = 2 × 3
示例 2:
输入:n = 8
输出:true
解释:8 = 2 × 2 × 2
示例 3:
输入:n = 14
输出:false
解释:14 不是丑数,因为它包含了另外一个质因数 7 。
"""
def isUgly(n):
if n<=0:
return False
for factor in [2,3,5]:
while n%factor==0:
n//=factor
return n==1
n=14
res=isUgly(n)
print(res) |
8e60d212527da25dfcd1d7b46706012f552c61c5 | longshuicui/leetcode-learning | /10.链表/160.Intersection of Two Linked Lists (Easy).py | 1,379 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/8
@function:
160. Intersection of Two Linked Lists (Easy)
https://leetcode.com/problems/intersection-of-two-linked-lists/
题目描述
给定两个链表,判断它们是否相交于一点,并求这个相交节点。
输入输出样例
输入是两条链表,输出是一个节点。如无相交节点,则返回一个空节点。
题解
假设链表A的头节点到相交点的距离为a,距离B的头节点到相交点的距离为b,相交点到
链表终点的距离为c。我们使用两个指针,分别指向两个链表的头节点,并以相同的速度
前进,若到达链表结尾,则移动到另一条链表的头节点继续前进。按照这种方法,两个
指针会在a+b+c次前进后到达相交节点。
利用环路去做
"""
class ListNode:
def __init__(self, value, next=None):
self.value = value
self.next = next
def getIntersectionNode(headA, headB):
if headA is None or headB is None:
return None
l1, l2=headA, headB
while l1!=l2:
l1=l1.next if l1 else headB
l2=l2.next if l2 else headA
return l1
a=[1,9,1,2,4]
b=[3,2,4]
head=ListNode(2,ListNode(4))
headA=ListNode(1,ListNode(9,ListNode(1,head)))
headB=ListNode(3,head)
node=getIntersectionNode(headA,headB)
print(node.value)
|
d76d149e9719c27d2bb11132aaf4453ce9394974 | longshuicui/leetcode-learning | /06.动态规划/子序列问题/300.Longest Increasing Subsequence (Medium).py | 1,557 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/2
@function:
300. Longest Increasing Subsequence (Medium)
https://leetcode.com/problems/longest-increasing-subsequence/
题目描述
给定一个未排序的整数数组,求 最长 的 递增 子序列的长度。
注意 按照 LeetCode 的习惯,子序列(subsequence)不必连续,子数组(subarray)或子字符串
(substring)必须连续。
输入输出样例
输入是一个一维数组,输出是一个正整数,表示最长递增子序列的长度。
Input: [10,9,2,5,3,7,101,18]
Output: 4
在这个样例中,最长递增子序列之一是 [2,3,7,18]。
题解
求最长上升子序列的长度, 动态规划
第一种方法,定义一个dp数组,其中dp[i]表示以i结尾的子序列的性质。在处理好每个位置之后,统计一遍各个位置的结果
可以得到题目要求的结果。对于每一个位置i,如果其之前的某个位置j所对的数字小于所对应的数字,则我们可以获得一个以
i结尾的长度为dp[j]+1的子序列。需要遍历两遍, 时间复杂度为O(n**n)
"""
def lengthOfLIS(nums):
max_length=0
if len(nums)<=1:
return len(nums)
dp=[1 for _ in range(len(nums))]
for i in range(len(nums)):
for j in range(0,i):
if nums[i]>nums[j]:
dp[i]=max(dp[i],dp[j]+1)
max_length=max(max_length,dp[i])
return max_length
nums=[10,9,2,5,3,7,101,18]
res=lengthOfLIS(nums)
print(res)
|
20ad59679e55cafeda0c21e4bc11a2abeb5255e5 | longshuicui/leetcode-learning | /03.二分查找/1011. 在 D 天内送达包裹的能力(Medium).py | 1,734 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/4/26
@function:
1011. 在 D 天内送达包裹的能力 (Medium)
https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days/
传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i个包裹的重量为weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
示例 1
输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
输出:15
解释:
船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
第 1 天:1, 2, 3, 4, 5
第 2 天:6, 7
第 3 天:8
第 4 天:9
第 5 天:10
请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
示例 2:
输入:weights = [3,2,2,4,1,4], D = 3
输出:6
示例 3:
输入:weights = [1,2,3,1,1], D = 4
输出:3
题解:
二分查找判定
"""
def shipWithinDays(weights, D):
left, right = max(weights), sum(weights)
while left <= right:
mid = left + (right - left) // 2
curr, day = 0, 0
for weight in weights:
if curr + weight > mid:
day += 1
curr = 0
curr += weight
day += 1
if day <= D:
right = mid - 1
else:
left = mid + 1
return left
weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
D = 5
res = shipWithinDays(weights, D)
print(res)
|
dfa2c9a903d36e9c0d41e5112cc689e2fa44f969 | longshuicui/leetcode-learning | /06.动态规划/分割类型题/139.Word Break (Medium).py | 1,203 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/2
@function:
139. Word Break (Medium)
https://leetcode.com/problems/word-break/
题目描述
给定一个字符串和一个字符串集合,求是否存在一种分割方式,使得原字符串分割后的子字
符串都可以在集合内找到。
输入输出样例
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
在这个样例中,字符串可以被分割为 [“apple” ,“pen” ,“apple” ]
题解
类似于完全平方分割问题,分割条件由集合内的字符串决定,因此在考虑每个分割位置时,需要遍历字符串集合。
以确定当前位置是否可以成功分割。对于位置0,需要初始化为真
"""
def wordBreak(s, wordDict):
dp=[False]*(len(s)+1)
dp[0]=True # 初始位置初始化为真
for i in range(1,len(s)+1):
for word in wordDict:
if i>=len(word) and s[i-len(word):i]==word:
dp[i]=dp[i] or dp[i-len(word)]
return dp[len(s)]
s = "leetcode"
wordDict = ["leet", "code"]
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
res=wordBreak(s, wordDict)
print(res) |
c6a9c8a6da02b290fb10bfcb5e7145aeab575fc8 | longshuicui/leetcode-learning | /03.二分查找/旋转数组找数字/540.Single Element in a Sorted Array (Medium).py | 1,137 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/2/18
@function:
540. Single Element in a Sorted Array (Medium)
https://leetcode.com/problems/single-element-in-a-sorted-array/
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.
在时间复杂度为O(logn)和空间复杂度为O(1)的条件下找出只出现一次的数字
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Input: nums = [3,3,7,7,10,11,11]
Output: 10
因为是O(logn)的时间复杂度,不可以使用位操作,使用二分搜索来做
数组里面的数字要么出现一次,要么出现两次
"""
def singleNonDuplicate(nums):
if len(nums) == 1:
return nums[0]
l,r=0, len(nums)-1
while l<=r:
if nums[l]!=nums[l+1]:
return nums[l]
if nums[r]!=nums[r-1]:
return nums[r]
l+=2
r-=2
return -1
nums=[3,3,7,7,10,11,11]
num=singleNonDuplicate(nums)
print(num) |
23fec7cac2c6dae1931577d195e554638a949702 | longshuicui/leetcode-learning | /07.位运算/477. 汉明距离总和(Medium).py | 1,374 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
@author: longshuicui
@date : 2021/5/28
@function:
477. 汉明距离总和 (Medium)
https://leetcode-cn.com/problems/total-hamming-distance/
两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。
计算一个数组中,任意两个数之间汉明距离的总和。
示例:
输入: 4, 14, 2
输出: 6
解释: 在二进制表示中,4表示为0100,14表示为1110,2表示为0010。(这样表示是为了体现后四位之间关系)
所以答案为:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
"""
def totalHammingDistanceBrute(nums):
"""暴力求解 时间复杂度为O(n^2logC)"""
def hammingDistance(x, y):
diff = x ^ y
ans = 0
while diff:
ans += diff & 1
diff >>= 1
return ans
ans=0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
ans+=hammingDistance(nums[i],nums[j])
return ans
def totalHammingDistance(nums):
"""第i位的汉明距离c*(n-c),c为第i位为1的个数"""
ans=0
for i in range(30):
c=0
for val in nums:
c+=(val>>i)&1 # 统计第i位为1的个数
ans+=c*(len(nums)-c)
return ans
nums=[4,14,2]
res=totalHammingDistanceBrute(nums)
print(res) |
f8133e1eceeec54774ed972bd87e50f3b6da3f6f | billillib/100daysofcode-with-python-course | /days/13-15-text-games/code/game.py | 2,595 | 3.96875 | 4 | import random
def main():
print_header()
ask_player_name()
game_loop(create_rolls())
class Roll:
def __init__(self, name):
self.name = name
self.beats = None
self.loses = None
def can_defeat(self, beats):
if self.beats == beats:
return True
else:
return False
def loses_to(self, loses):
if self.loses == loses:
return True
else:
return False
def print_header():
print("Welcome to the awesome game of ROCK PAPER SCISSORS!!!")
def ask_player_name():
name = input("What is your name: ")
continue_game = input(f'are you ready to rock {name}? Type YES or NO: ')
if continue_game.upper() == 'YES':
print('Heck YEA!')
else:
print(f'Bye {name}...')
exit()
def create_rolls():
paper = Roll('Paper')
rock = Roll('Rock')
scissors = Roll('Scissors')
paper.beats = rock
paper.loses = scissors
rock.beats = scissors
rock.loses = paper
scissors.beats = paper
scissors.loses = rock
return paper, rock, scissors
def player_input(rolls):
choice = input("[R]ock, [P]aper, [S]cissors: ")
if choice.upper() == 'R':
return rolls[1]
elif choice.upper() == 'P':
return rolls[0]
elif choice.upper() == 'S':
return rolls[2]
else:
print("Invalid input")
def computer_input(rolls):
computer = random.choice(rolls)
return computer
def game_action(player, computer):
print(f'You chose {player.name}, computer chose {computer.name}')
if player.can_defeat(computer):
print('You won!')
return 1
elif player.loses_to(computer):
print('You lost!')
return 0
else:
print('Tie!')
return -1
def game_loop(rolls):
tracker = {'player': 0, 'computer': 0, 'tie': 0}
count = 0
while count < 3:
computer_roll = computer_input(rolls)
player_roll = player_input(rolls)
outcome = game_action(player_roll, computer_roll)
if outcome == 1:
tracker["player"] += 1
elif outcome == 0:
tracker["computer"] += 1
else:
tracker["tie"] += 1
count += 1
# print(tracker)
if tracker.get("player") > tracker.get("computer"):
print("YOU WON THE WHOLE THING!")
elif tracker.get("player") < tracker.get("computer"):
print("YOU LOST TO A COMPUTER OMG")
else:
print("HOW DID YOU TIE THREE TIMES IN A ROW??!?")
if __name__ == '__main__':
main()
|
8551d1220dd96bc945ca0272ffe8c797184d7504 | Manisha269/Test | /BackendTask.py | 561 | 3.828125 | 4 | input_string = input("Enter leads of various company: ")
userList = input_string.split(",")
def leads(User_list):
Lead_list={}
count={}
for i in User_list:
domain_name=i[i.index('@')+1:]
name=i[0:i.index('@')]
if(domain_name not in Lead_list):
Lead_list[domain_name]=[]
Lead_list[domain_name].append(name)
count[domain_name]=1
else:
Lead_list[domain_name].append(name)
count[domain_name]+=1
return Lead_list, count
print(leads(userList))
|
e3ab01a2ae4cb41fed9a8f34ca37b7c83c009304 | atominize/textbites | /textbites/api.py | 4,818 | 3.671875 | 4 | #!/usr/bin/env python
"""
API for textual resources. These are abstract base classes.
"""
from collections import namedtuple
class Resource:
""" Represents a textual resource which can provide references into it.
"""
def name(self):
""" Name is the pretty of the top reference.
"""
return self.top_reference().pretty()
def reference(self, string_ref):
""" Parse this string reference and return an object.
Supports the following formats:
Chapter N
chapter N
N
Chapter N:M
Chapter N:M-P
Doesn't support chapter range
Doesn't support open ended line ranges
Currently doesn't do any validation.
"""
raise NotImplementedError()
def top_reference(self):
""" Top-most reference for this resource, which can be traversed.
"""
raise NotImplementedError()
class Reference(object):
""" Represents some section of text.
NOTE: in future may want to add:
- parent()
- get_number() (e.g. line number), though
the goal is that the impl doesn't need to have that level of
detail.
- next()/prev() - for walking the chain
"""
def __init__(self):
# set parent for children
if self.children():
for child in self.children():
#print "Setting parent of %s to %s" % (child, self)
child._parent = self
def resource(self):
""" Return the resource that this is part of.
"""
return self.root()._resource
def pretty(self):
""" Return a canonical string of this reference.
"""
raise NotImplementedError()
def path(self):
""" Default relative path is pretty() except for root. This is
because resources are already namespaced under their resource
name which is this top level description.
"""
if self == self.root():
return ""
return self.pretty()
def short(self):
""" Shorter version of pretty with relative information.
e.g. a line would only include its number.
"""
return self.pretty()
def text(self):
""" Return string of the text corresponding to this reference.
Should probably be unsupported for entire book.
NOTE: how do we promise to handle whitespace? Currently,
line ranges are joined by lines.
"""
raise NotImplementedError()
def search(self, pattern):
""" Return list of Reference which match within this scope, which
indicate line matches.
"""
raise NotImplementedError()
def children(self):
""" Return an iterable of References under this item.
"""
raise NotImplementedError()
def parent(self):
""" Return parent reference or None.
For this, subclasses must have called Reference's ctor.
"""
try:
return self._parent
except:
return None
def root(self):
""" Top-most reference.
"""
top = self
while top.parent() != None:
top = top.parent()
return top
def previous(self):
""" Return reference for previous or None.
For this, subclasses must have called Reference's ctor.
"""
if self.parent():
try:
idx = self.parent().children().index(self)
if idx != -1 and idx >= 1:
return self.parent()[idx-1]
except:
pass
return None
def next(self):
""" Return reference for next or None.
For this, subclasses must have called Reference's ctor.
"""
if self.parent():
try:
idx = self.parent().children().index(self)
if idx != -1 and idx+1 < len(self.parent()):
return self.parent()[idx+1]
except:
pass
return None
def indices(self):
""" Return a pair of integers representing the order of this reference
within the resource. Used for determining overlap between references
in the database. Base on start and end.
Defined recursively, so only lowest level needs an overridden impl.
"""
return Index(self.children()[0].indices().start,
self.children()[-1].indices().end)
def __len__(self):
if self.children():
return len(self.children())
return 0
def __getitem__(self, key):
return self.children()[key]
def __str__(self):
return "%s:%s" % (type(self), self.pretty())
def __nonzero__(self):
""" Don't want evaluation based on len(). """
return 1
Index = namedtuple('Index', ['start', 'end'])
class UnparsableReferenceError(Exception):
""" Reference format is not supported.
"""
def __init__(self, val=""):
self.val = val
def __str__(self):
return repr(self.val)
class InvalidReferenceError(Exception):
""" Reference is out of bounds.
"""
def __init__(self, val=""):
self.val = val
def __str__(self):
return repr(self.val)
|
922071d30c161c1519d7f19910aabf7ba985ae03 | FRCTeam1571/Robot2017_Offseason | /Trevor/Interface/runrobotWIP.py | 2,840 | 3.796875 | 4 | #!/usr/bin/env python3
# coding=utf-8
import os
import platform # this is to detect the operating system for cross-platform compatibility
os.system('color f9')
@staticmethod
def error():
""" this is used when the program breaks or for stopping the command prompt from closing. """
print("")
input("Press Enter")
class Statics:
""" this is just a class full of static methods """
@staticmethod
def brk():
"""
this is used to add the line break. its just to save writing code
"""
print('')
print('')
print('')
print('')
def target_file():
"""
this attempts to find the file specified by the user.
:returns: file path of robot file
:rtype: str
"""
global fn, fpath
print("please input file name [should be 'robot.py'. you may click enter for the default}")
fn = input(": ")
if fn is "":
fn = "robot.py"
ext = ".py" #Checks for .py file extension
if ext not in fn:
fn = fn+ext
print("Is the program in this folder? [y/n]")
fpq = input(": ")
if fpq.lower() == 'n':
os.chdir
fpath = input("enter file path: ")
else:
fpath = os.path.join(os.path.dirname(__file__))
print(fpath)
Statics.brk()
return (fn, fpath)
def run_mode():
pass
def platCheck():
""" allows for cross-platform support though the assignment of variables """
global clear
platname = platform.system()
if platname == 'Linux':
clear = 'clear'
# Linux
elif platname == 'Darwin':
clear = 'clear'
#This is experimental. None of us know how to use OSX or have it.
# MAC OS X
elif platname == 'Windows':
clear = 'cls'
# Windows
else:
print("What is your OS?")
print("A. Linux")
print("B. Mac OS/ OSX")
print("C. Windows")
osq = input(": ")
if osq == "A" or osq == "a":
clear = 'clear'
if osq == "B" or osq == "b":
clear = 'clear'
if osq == "C" or osq == "c":
clear = 'cls'
return clear
platCheck() #Called for testing
os.system(clear)
print("\n \n \n \n Welcome to the CALibrate Robotics Robot UI\n")
Statics.brk()
target_file()
os.chdir(fpath)
run_mode()
""" THE LAND OF STUFF TO DO """
# TODO search for file name in super, child, and current dir [use current as primary]
# TODO set to save a config file. More options setting for program reset, self test, and others.
# TODO make separate menus for specific things in the UI
# TODO make it actually run the robot based off of the OS. have to figure out os.system() variable issue first.
# TODO make a way to find if the user has RobotPy and PyGame installed
"""
Made by:
Trevor W. - Team 1571
Ethan A. - Team 5183
"""
|
07999243a551f3948b311e36ed14d6c5129076d9 | v0rs4/project_euler_solutions | /python/p004_1.py | 212 | 3.609375 | 4 | def isPalindrome(n):
return str(n) == str(n)[::-1]
def solve():
return max(x * y for x in range(100, 1000) for y in range(100, 1000) if isPalindrome(x * y))
if __name__ == "__main__":
print(solve()) |
6230fd200e52ea05cb0fc8bb59b14621431607ac | 06Prakash/python-training-codes | /iterablesCommon.py | 705 | 4.03125 | 4 | import itertools
def sprint(x):
'''
Special Print
:param x: Any iterable or not will be printed
'''
for c in x :
try :
for v in c :
print (v, end=" " )
except :
print(c)
print("")
if __name__ == "__main__" :
list1 = [ 1, 2, 3, 4, 5]
list2 = [ 'a', 'b', 'c', 'd']
print("Zip")
sprint(zip(list1,list2))
print("Product")
sprint(itertools.product(list1,list2))
print("Combination")
sprint(itertools.combinations(list2,3))
print("Permutations")
sprint(itertools.permutations(list2,3))
print("PowerSets")
#sprint(itertools.powerset(list1)) |
143f8ea31c7f3a3255098a375f1b2a2f853902f0 | Andross78/Kaizer | /min_max.py | 8,361 | 3.546875 | 4 | def minmax_1(array):
if not array:
return (None,None)
n = len(array)
min_int = array[0]
for i in range(1,n):
next_int = array[i]
if min_int > next_int:
min_int = next_int
max_int = array[0]
for i in range(1,n):
next_int = array[i]
if max_int < next_int:
max_int = next_int
return(min_int, max_int)
def minmax_2(array):
n = len(array)
area_list = []
for i in array:
area_list.append(i[0]*i[1])
min_area = area_list[0]
for i in range(1,n):
next_area = area_list[i]
if min_area > next_area:
min_area = next_area
return area_list, min_area
def minmax_3(array):
n = len(array)
p_list = []
for i in array:
p_list.append(2*(i[0]+i[1]))
max_p = p_list[0]
for i in range(1,n):
next_p = p_list[i]
if max_p < next_p:
max_p = next_p
return p_list, max_p
def minmax_4(array):
n = len(array)
min_int = array[0]
i_int = 0
for i in range(1,n):
if array[i] < min_int:
min_int = array[i]
i_int = i
return array, i_int
def minmax_5(array)
'''prosto'''
...
def minmax_6(array):
n = len(array)
min_int = array[0]
max_int = array[0]
for i in range(1,n):
if array[i] < min_int:
min_int = array[i]
min_i = i
elif array[i] > max_int:
max_int = array[i]
max_i = i
return min_i, min_int, max_i, max_int
def minmax_8(array):
n = len(array)
_min = array[0]
int_1 = 0
int_2 = 0
for i in range(1,n):
if array[i] < _min:
_min = array[i]
int_1 = i
int_2 = i
if array[i] == _min:
int_2 = i
return int_1, int_2
def minmax_12(array):
n = len(array)
max_int = array[0]
for i in range(1,n):
if max_int < array[i]:
max_int = array[i]
if max_int <= 0:
return 0
else:
return max_int
def minmax_13(array):
n = len(array)
max_int = None
max_i = 0
for i in range(1,n):
if array[i] % 2 != 0:
if max_int is None or max_int < array[i]:
max_int = array[i]
max_i = i
return max_i
def minmax_16(array):
min_int = min(array)
index_i = array.index(min_int)
for i in range(0, index_i):
print(array[i])
def minmax_22(array):
n = len(array)
min_1 = array[0]
min_2 = array[0]
for i in range(1,n):
if min_1 >= array[i]:
min_1,min_2 = array[i], min_1
return min_1,min_2
def minmax_24(array):
n = len(array)
max_sum = array[0]+ array[1]
for i in range(2,n):
sum = array[i-1] + array[i]
if sum > max_sum:
max_sum = sum
return max_sum
# *****************************************************
def minmax_7(array):
n = len(array)
max_digit = array[0]
min_digit = array[0]
max_i = 0
min_i = 0
for i in range(1,n):
if max_digit <= array[-i]:
max_digit = array[-i]
max_i = n-i
if min_digit >= array[i]:
min_digit = array[i]
min_i = i
return max_i, min_i
def minmax_8(array):
n = len(array)
f_i = 0
l_i = 0
min_el = array[0]
for i in range(1,n):
if min_el > array[i]:
min_el = array[i]
l_i = i
if array[i] == min_el:
l_i = i
return f_i, l_i
def minmax_9(array):
n = len(array)
f_i = 0
l_i = 0
max_el = array[0]
for i in range(1,n):
if max_el < array[i]:
max_el = array[i]
f_i = i
if array[i] == max_el:
l_i = i
return f_i, l_i
def minmax_10(array):
n = len(array)
_min = array[0]
_max = array[0]
min_i = 0
max_i = 0
for i in range(1,n):
if _min > array[i]:
_min = array[i]
min_i = i
if _max < array[i]:
_max = array[i]
max_i = i
if min_i < max_i:
return min_i
else:
return max_i
def minmax_11(array):
n = len(array)
_min = array[0]
_max = array[0]
min_i = 0
max_i = 0
for i in range(1,n):
if _min >= array[i]:
_min = array[i]
min_i = i
if _max <= array[i]:
_max = array[i]
max_i = i
if min_i > max_i:
return min_i
else:
return max_i
def minmax_12(array):
n = len(array)
new_arr = []
for i in array:
if array[i] >= 0:
new_arr.append(array[i])
if new_arr == []:
return 0
n = len(new_arr)
_min = new_arr[0]
for i in range(1,n):
if _min > new_arr[i]:
_min = new_arr[i]
return _min
def minmax_13(array):
n = len(array)
max_i = 0
max_int = None
for i in range(n):
if array[i] % 2 != 0:
if max_int is None or max_int < array[i]:
max_int = array[i]
max_i = i
if max_i == None:
return 0
return max_i
def minmax_14(array,b):
_min = None
n = len(array)
min_i = 00
for i in range(n):
if array[i] > b:
if _min is None or _min > array[i]:
_min = array[i]
min_i = i
return min_i
def minmax_15(array,b,c):
_max = None
n = len(array)
max_i = 0
for i in range(n):
if array[i] > n and array[i] < c:
if _max is None or _max < array[i]:
_max = array[i]
max_i = i
return max_i
def minmax_16(array):
n = len(array)
_min = array[0]
min_i = 0
for i in range(1,n):
if _min > array[i]:
_min = array[i]
min_i = i
return len(array[:min_i])
def minmax_17(array):
n = len(array)
_max = array[0]
max_i = 0
for i in range(1,n):
if _max <= array[i]:
_max = array[i]
max_i = i
return len(array[max_i:])
def minmax_18(array):
n = len(array)
_max = array[0]
m_1 = None
m_2 = None
for i in range(1,n):
if _max < array[i]:
_max = array[i]
m_1 = i
if array[i] == _max:
m_2 = i
return len(array[m_1+1:m_2])
def minmax_19(array):
n = len(array)
_min = array[0]
counter = 1
for i in range(1,n):
if _min > array[i]:
_min = array[i]
counter = 0
if array[i] == _min:
counter += 1
return counter
#/////////////////////
def minmax_20(array):
n = len(array)
_min = array[0]
_max = array[0]
c_min = 1
c_max = 1
for i in range(1,n):
if _min > array[i]:
_min = array[i]
c_min = 0
if _max < array[i]:
_max = array[i]
c_max = 0
if array[i] == _max:
c_max += 1
if array[i] == _min:
c_min += 1
return c_min+c_max
# def minmax_21(array):
# n = len(array)
# summ = 0
# counter = 0
# _min = array[0]
# _max = array[0]
# for i in range(1,n):
# if _min > array[i]:
# counter += 1
# summ += _min
# _min = array[i]
# if _max < array[i]:
# counter += 1
# summ += _max
# _max = array[i]
# else:
# counter +=1
# summ += array[i]
def minmax_22(array):
n = len(array)
min_1 = array[0]
min_2 = array[0]
for i in range(1,n):
if min_1 > array[i]:
min_2 = min_1
min_1 = array[i]
return min_1, min_2
def minmax_23(array):
n = len(array)
max_1 = array[0]
max_2 = array[0]
max_3 = array[0]
for i in range(1,n):
if max_1 < array[i]:
max_3,max_2,max_1 = max_2,max_1,array[i]
elif max_1 > array[i] and max_2 < array[i]:
max_3, max_2 = max_2, array[i]
return max_1, max_2, max_3
def minmax_25(array):
n = len(array)
prod = array[0]*array[1]
i_1 = 0
i_2 = 0
for i in range(2,n):
if prod > array[i-1]*array[i]:
prod = array[i-1]*array[i]
i_1 = i-1
i_2 = i
return i_1, i_2
|
2e38b50b436eb0352955cbc69f589bd43f5c25c0 | toxa1711/helper | /Input_Audio.py | 510 | 3.515625 | 4 | import speech_recognition as sr
def input_audio():
r = sr.Recognizer(language="ru")
with sr.Microphone() as source: # use the default microphone as the audio source
audio = r.listen(source) # listen for the first phrase and extract it into audio data
try:
return r.recognize(audio) # recognize speech using Google Speech Recognition
except LookupError: # speech is unintelligible
return " "
|
6e3314329a350e7b716b6332fddc713fc464482b | vengadam2001/iot | /hello.py | 151 | 3.890625 | 4 | l = int(input("enter a number"))
def oe(n=1):
if (n % 2 == 0):
return "even"
else:
return "odd"
print(f"{l} is a ", oe(l))
|
8b0e52b691e3fe832804bbe32847eb97577b1b6b | jguarni/Python-Labs-Project | /Lab 2/testme1.py | 82 | 3.65625 | 4 | def divide_by_5(number):
hello = (number/5)
print(hello)
divide_by_5(3)
|
2dd5c760bf9cf7b41a808cae47a621981dbb9997 | jguarni/Python-Labs-Project | /Lab 6/testclass.py | 1,186 | 4.0625 | 4 | from cisc106 import *
class Employee:
"""
An employee is a person who works for a company.
position -- string
salary -- integer
"""
def __init__(self,position,salary,age):
self.position = position
self.salary = salary
self.age = age
"""
def employee_function(aEmployee,...):
return aEmployee.position
aEmployee.salary
"""
def employee_status(self):
"""
Gives you the positon and salary of the employee
Employee -- Employee
return -- string
"""
print(self.position)
print("The Salary of the employee is", self.salary)
print("The age of the employee is", self.age)
return(self.position)
def change_salary(self,change):
"""
Changes the position of the employee
Position - Position
return - String
"""
self.salary = self.salary + (self.salary * change)
aEmployee1 = Employee("CEO",500000,24)
aEmployee2 = Employee("Programmer",100000,19)
aEmployee1.employee_status
aEmployee2.change_salary(.50)
assertEqual(aEmployee1.employee_status(),'CEO')
|
075463a7832a8638a6cb22fad6258a401432b9e3 | jguarni/Python-Labs-Project | /Lab 4/lab4.py | 5,585 | 4.28125 | 4 | # Lab 4
# CISC 106 6/24/13
# Joe Guarni
from cisc106 import *
from random import *
#Problem 1
def rand(num):
"""
This function will first set a range from 0 to an input parameter,
then prompt the user to guess a number in that range. It will then
notify the user weather their input was correct, too high, or too low
compared to the random number.
num -- number
return - nothing as this function prints its output
"""
randvar = randrange(0,num+1)
number = int(input("Please enter a number between 0 and " + str(num ) +": "))
if (number == randvar):
print("Congratulations! You guessed the number!")
elif (number > randvar):
print("Your guess was too high")
elif (number < randvar):
print("Your guess was too low")
rand(10)
rand(100)
rand(1000)
# Problem 2
def hort():
"""
This function will ask the user for heads or tails and compare
thier answer to a randomly generated true or false, and return
weather their guess was correct.
return -- boolean
"""
randvar = randrange(0,2)
guess = int(input("Heads[Press 0] or Tails[Press 1] ?: "))
if (guess == 1) and (randvar == 1) or (guess == 0) and (randvar == 0):
return True
else:
return False
def hort2():
"""
This function will determine the winner of the best of 5 game. If the user
or computer wins 3 times the loop will stop as one of the players has won.
"""
time = 0
user = 0
computer = 0
while(time < 5):
if hort():
user = user + 1
else:
computer = computer + 1
if (user >= 3):
print('The user has beaten the computer!')
return
if (computer >= 3):
print('The computer has beaten the user!')
return
time = time + 1
hort2()
#Problem 3
def addition(x):
"""
This function will take a numerical input and return the sum
of all the numbers from 0 until the input number.
x -- number
return -- number
"""
total = 0
while(x > 0):
total = total + x
x = x - 1
return total
assertEqual(addition(3),(6))
assertEqual(addition(4),(10))
assertEqual(addition(6),(21))
#Problem 4
def randsum(n):
"""
This function will generate n amount of numbers between 0 and 100
and print the random numbers and their sum total.
n -- number
return -- number
"""
endval = 0
print("Numbers: ")
while (n > 0):
randomv = randrange(0,101)
print(randomv)
endval = endval + randomv
n = n - 1
print("Total Sum: ", endval)
randsum(10)
randsum(15)
randsum(20)
#Problem 5
def practice(x):
"""
This function will generate a number between 0-10, and then ask the user
for the answer of that random number multiplied against the input x value.
If the user is correct, the function will return true, and if incorrect,
return false.
x -- Number
return -- Boolean
"""
randvar = randrange(0,11)
uinput = int(input("What is " + str(randvar ) + " times " + str(x ) + "? "))
answer = randvar * x
if (answer == uinput):
print("Correct")
return True
else:
print("Incorrect")
return False
practice(5)
practice(7)
#Problem 6
numbers1 = [2, 4, 6, 8, 1, 5, 7, 9, 10, 12, 14]
def square(valuelist):
"""
This function will take input as a list and print the square of each
number in that list.
valuelist -- number
print -- number
"""
for num in valuelist:
sq = num ** 2
print(sq)
square(numbers1)
#Problem 7
def blackjack():
"""
This function will emulate a game of blackjack. It will hand random card
numbers to the user and ask them each time if they want another card. It
will then test the users hand against the randomly generated computers
hand to see who won the game according to the rules of blackjack.
"""
print('Welcome to Wacky BlackJack!')
ans = 'yes'
uhand = 0
while (ans == 'yes'):
unumber = randrange(1,12)
print('Your card is',unumber)
uhand = uhand + unumber
print('Your hand total is',uhand)
if (uhand > 21):
print('You went over 21!')
ans = input('Would you like to try again? ')
uhand = 0
else:
ans = input('Do you wish to continue? ')
if (ans == 'no'):
dhand = randrange(11,31)
print('The dealers score is',dhand)
if (dhand > 21):
print('The user has won the game!')
elif (dhand <= 21) and (uhand > 21):
print('The computer has won the game!')
elif (dhand <= 21) and (dhand > uhand):
print('The computer has won the game!')
elif (uhand <= 21) and (uhand >= dhand):
print('The user has won the game!')
blackjack()
#Problem 8
def random_list(maxval,amount):
"""
This function will produce a input value(amount) list of random numbers between 0 and
specified maxvaule input with legnth N
maxval -- number
amount -- number
return -- list with numbers
"""
rlist = []
for i in range(amount):
rlist.append(randrange(0,maxval+1))
return rlist
assertEqual(len(random_list(100, 1000)), 1000)
assertEqual(min(random_list(100, 1000)) >= 0, True)
assertEqual(max(random_list(1, 1000)) <= 1, True)
|
bd7938eb01d3dc51b4c5a29b68d9f4518163cc92 | jguarni/Python-Labs-Project | /Lab 5/prob2test.py | 721 | 4.125 | 4 | from cisc106 import *
def tuple_avg_rec(aList,index):
"""
This function will take a list of non-empty tuples with integers
as elements and return a list with the averages of the elements
in each tuple using recursion.
aList - List of Numbers
return - List with Floating Numbers
"""
newList = []
if len(aList) == 0:
return 0
if (len(aList) != index):
newList.append((sum(aList[index])/len(aList[index])))
newList.extend((sum(aList[index])/len(aList[index])))
print(aList[index])
tuple_avg_rec(aList, index+1)
return newList
assertEqual(tuple_avg_rec(([(4,5,6),(1,2,3),(7,8,9)]),0),[5.0, 2.0, 8.0])
|
e63dc201a8e29e4227ff4ce0871c3e50377b529e | yveslym/Herd_Immunity_Project | /person.py | 3,259 | 3.703125 | 4 | import random
# TODO: Import the virus clase
import uuid
from randomUser import Create_user
import pdb
'''
Person objects will populate the simulation.
_____Attributes______:
_id: Int. A unique ID assigned to each person.
is_vaccinated: Bool. Determines whether the person object is vaccinated against
the disease in the simulation.
is_alive: Bool. All person objects begin alive (value set to true). Changed
to false if person object dies from an infection.
infection: None/Virus object. Set to None for people that are not infected.
If a person is infected, will instead be set to the virus object the person
is infected with.
_____Methods_____:
__init__(self, _id, is_vaccinated, infected=False):
- self.alive should be automatically set to true during instantiation.
- all other attributes for self should be set to their corresponding parameter
passed during instantiation.
- If person is chosen to be infected for first round of simulation, then
the object should create a Virus object and set it as the value for
self.infection. Otherwise, self.infection should be set to None.
did_survive_infection(self):
- Only called if infection attribute is not None.
- Takes no inputs.
- Generates a random number between 0 and 1.
- Compares random number to mortality_rate attribute stored in person's infection
attribute.
- If random number is smaller, person has died from disease.
is_alive is changed to false.
- If random number is larger, person has survived disease. Person's
is_vaccinated attribute is changed to True, and set self.infected to None.
'''
class Person(object):
def __init__(self, is_vaccinated=False, infected=False, virus = None):
# TODO: Finish this method. Follow the instructions in the class documentation
# to set the corret values for the following attributes.
self._id = uuid.uuid4().hex[:10]
self.is_vaccinated = is_vaccinated
self.is_alive = True
self.survive = False
self.infected = infected #virus type object
self.virus = virus
self.interacted = False
user_obj = Create_user()
user = user_obj.create()
self.name = ('%s %s' %(user.first_name,user.last_name))
#pdb.set_trace()
def did_survive_infection(self):
# TODO: Finish this method. Follow the instructions in the class documentation
# for resolve_infection. If person dies, set is_alive to False and return False.
# If person lives, set is_vaccinated = True, infected = None, return True.
if self.infected is not None:
chance_to_survive = random.uniform(0.0,1.0)
if chance_to_survive > self.virus.mortality_rate:
self.is_alive = True
self.is_vaccinated = True
self.infected = False
return True
else:
self.is_alive = False
self.infected = False
return False
pass
#def resolve_infection():
#chance_to_survice
|
bc189bd3a9ffce0d504d932c4a0ff4a2199323a4 | donw385/DS-Unit-3-Sprint-2-SQL-and-Databases | /demo_data.py | 833 | 3.984375 | 4 | import sqlite3
conn = sqlite3.connect('demo_data.sqlite3')
curs = conn.cursor()
curs.execute(
"""
CREATE TABLE demo (
s str,
x int,
y int
);
"""
)
conn.commit()
curs.execute(
"""
INSERT INTO demo
VALUES
('g',3,9),
('v',5,7),
('f',8,7);
""")
conn.commit()
# Count how many rows you have - it should be 3!
query = 'SELECT count(*) FROM demo;'
print ('Rows:',conn.cursor().execute(query).fetchone()[0], '\n')
# How many rows are there where both x and y are at least 5?
query2 = 'SELECT count(s) FROM demo WHERE x >= 5 AND y >= 5;'
print ('Rows X and Y at least 5:',conn.cursor().execute(query2).fetchone()[0], '\n')
# How many unique values of y are there?
query3 = 'SELECT COUNT(DISTINCT y) FROM demo;'
print ('Unique Y Values:',conn.cursor().execute(query3).fetchone()[0], '\n')
|
3e561974952579ce8c2a42e263927912f9e87a53 | Sakshi-16-01/CBAP_13DEC | /03PythonBasics.py | 4,693 | 4.03125 | 4 |
#Topic : Basic Programming
#Numbers: Integers and floats work as you would expect from other languages:
x = 3
print(x)
print(type(x)) # Prints "3"
print(x + 1) # Addition; prints "4"
print(x - 1) # Subtraction; prints "2"
print(x * 2) # Multiplication; prints "6"
print(x ** 2) # Exponentiation; prints "9"
x=5
x += 1
x
x=x+1
print(x) # Prints "4"
x=5
x *= 2
print(x) # Prints "8"
x=5
x **= 2
print(x) # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"
#Python does not have unary increment (x++) or decrement (x--) operators
#%%
#Booleans: Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&, ||, etc.):
t = True
f = False
print(type(f)) # Prints "<class 'bool'>"
AND
0 0 0
0 1 0
1 0 0
1 1 1
OR
0 0 0
0 1 1
1 0 1
1 1 1
Not
0 1
1 0
Ex OR
0 0 0
0 1 1
1 0 1
1 1 0
t=1
f=0
print(t and f) # Logical AND; prints "False"
print(t or f) # Logical OR; prints "True"
print(not t) # Logical NOT; prints "False"
t=1
f=1
print(t != f) # Logical XOR; prints "True"
#%%
#Strings: Python has great support for strings:
Fname='vikas'
type(Fname)
Lname='khullar'
name = Fname +' ' + Lname
print(name)
h = 'hello' # String literals can use single quotes
w = "world" # or double quotes; it does not matter.
print(h) # Prints "hello"
print(len(h)) # String length; prints "5"
hw = h + ' ' + w # String concatenation
print(hw) # prints "hello world"
hw12 = '%s %s %s' % ('hello', 'world', 12)
hw12
# sprintf style string formatting
print(hw12) # prints "hello world 12"
#String objects have a bunch of useful methods; for example:
s = "hello"
s.capitalize()
print(s.capitalize()) # Capitalize a string; prints "Hello"
print(s.upper()) # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7)) # Right-justify a string, padding with spaces; prints " hello"
print(s.center(10)) # Center a string, padding with spaces; prints " hello "
s=s.replace('e', 'yyy')
s
print(s) # Replace all instances of one substring with another; # prints "he(ell)(ell)o"
s=s.replace('o', 'yyy')
print(s) # Replace all instances of one substring with another; # prints "he(ell)(ell)o"
s = "hello"
z=' world '
print(z)
print(z.strip()) # Strip leading and trailing whitespace; prints "world"
#%%%Containers
#Python includes several built-in container types: lists, dictionaries, sets, and tuples.
#ListsA list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
xs = [30, 10, "ff", 55, 888] # Create a list
xs
print(xs[2]) # Prints "[3, 1, 2] 2"
print(xs[-2]) # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo' # Lists can contain elements of different types
print(xs) # Prints "[3, 1, 'foo']"
xs.append('')
xs.append('bar') # Add a new element to the end of the list
print(xs) # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop() # Remove and return the last element of the list
x
xs
print(x, xs) # Prints "bar [3, 1, 'foo']"
#Slicing: In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:
x=range(5, 10)
x
a=100.6
b=a//10
b
import math
math.ceil(b)
a = range(10, 20)
type(a)
nums = list(a) # range is a built-in function that creates a list of integers
nums
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:5]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[5:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:3]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums) # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[-4:]) # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
nums
print(nums) # Prints "[0, 1, 8, 9, 4]"
#Some Builtin Functions
a= bin(17)
a
a=bool(0)
a
a=bytearray(10)
a
#a=bytes(6)
a
ASCII
a=chr(65)
a
a=eval("False or False")
a
help()
a=hex(19)
a
x = iter(["apple", "banana", "cherry"])
x
print(next(x))
print(next(x))
print(next(x))
len(a)
max(iter(["apple", "banana", "cherry"]))
a=range(2,10)
a
list_a=list(a)
list_a
round(22.6)
a=str(11.7)
a
x=iter([1,4,2])
a=sum(x)
a
type(a)
abs(-11.7)
mylist = [True, True, False]
x = any(mylist)
x
len(x)
x = ['apple', 'banana', 'cherry']
len(x)
print('Enter your name:')
x = input()
x
x= input("Enter a number")
x
x = pow(4, 3)
x
|
ef1d6ca5aa113b72984f55a10ddd9cf0561e190f | CHINAJR/Sort | /GenerateRandomArray.py | 238 | 3.546875 | 4 | import random
def GenerateRandomArray(size,maxnum):
n = []
size = random.randint(1,size)
for i in range(size):
n.append(random.randint(1,maxnum))
print(n)
if __name__ == '__main__':
for i in range(10):
GenerateRandomArray(5,10)
|
8656ff504d98876c89ead36e7dd4cc73c3d2249e | jlopezmx/community-resources | /careercup.com/exercises/04-Detect-Strings-Are-Anagrams.py | 2,923 | 4.21875 | 4 | # Jaziel Lopez <juan.jaziel@gmail.com>
# Software Developer
# http://jlopez.mx
words = {'left': "secured", 'right': "rescued"}
def anagram(left="", right=""):
"""
Compare left and right strings
Determine if strings are anagram
:param left:
:param right:
:return:
"""
# anagram: left and right strings have been reduced to empty strings
if not len(left) and not len(right):
print("Anagram!")
return True
# anagram not possible on asymetric strings
if not len(left) == len(right):
print("Impossible Anagram: asymetric strings `{}`({}) - `{}`({})".format(left, len(left), right, len(right)))
return False
# get first char from left string
# it should exist on right regardless char position
# if first char from left does not exist at all in right string
# anagram is not possible
char = left[0]
if not has_char(right, char):
print("Impossible Anagram: char `{}` in `{}` not exists in `{}`".format(char, left, right))
return False
left = reduce(left, char)
right = reduce(right, char)
if len(left) and len(right):
print("After eliminating char `{}`\n `{}` - `{}`\n".format(char, left, right))
else:
print("Both strings have been reduced\n")
# keep reducing left and right strings until empty strings
# anagram is possible when left and right strings are reduced to empty strings
anagram(left, right)
def has_char(haystack, char):
"""
Determine if a given char exists in a string regardless of the position
:param haystack:
:param char:
:return:
"""
char_in_string = False
for i in range(0, len(haystack)):
if haystack[i] == char:
char_in_string = True
break
return char_in_string
def reduce(haystack, char):
"""
Return a reduced string after eliminating `char` from original haystack
:param haystack:
:param char:
:return:
"""
output = ""
char_times_string = 0
for i in range(0, len(haystack)):
if haystack[i] == char:
char_times_string += 1
if haystack[i] == char and char_times_string > 1:
output += haystack[i]
if haystack[i] != char:
output += haystack[i]
return output
print("\nAre `{}` and `{}` anagrams?\n".format(words['left'], words['right']))
anagram(words['left'], words['right'])
# How to use:
# $ python3 04-Detect-Strings-Are-Anagrams.py
#
# Are `secured` and `rescued` anagrams?
#
# After eliminating char `s`
# `ecured` - `recued`
#
# After eliminating char `e`
# `cured` - `rcued`
#
# After eliminating char `c`
# `ured` - `rued`
#
# After eliminating char `u`
# `red` - `red`
#
# After eliminating char `r`
# `ed` - `ed`
#
# After eliminating char `e`
# `d` - `d`
#
# Both strings have been reduced
#
# Anagram!
#
# Process finished with exit code 0
|
035899efa2286718b1862f03d39cd36936a2283b | Giioke/SacredTexts_Scraper | /Web_Scrapper.py | 1,271 | 3.703125 | 4 | #Web Scraper for SacredTexts.com
# Source - https://www.youtube.com/watch?v=7SWVXPYZLJM&t=397s
import requests
from bs4 import BeautifulSoup
url = "http://www.sacred-texts.com/index.htm"
resp = requests.get(url)
#Ability to read the HTML in python
soup = BeautifulSoup(resp.text, 'lxml')
WebCode = soup.prettify()
print(WebCode)
# Find the names and links to the books in the website's menu elements
topicMenu = soup.find('span', class_='menutext')
#print(topicMenu)
#Extract topic names
topicMenu_cut = topicMenu.find_all(string = True)
titles = [title.strip() for title in topicMenu_cut]
titles = list(filter(None, titles))
#print(titles)
# Extract Links
LinksMenu = [soup.find('a', href = True) for links in topicMenu]
#LinksMenu = LinksMenu.attrs['href']
#print(LinksMenu)
## Data Structure
# topics = {
# "topic1": {
# "descript": "content",
# "topicLink": "weblink"
# },
# "topic2": {
# "descript": "content",
# "topicLink": "weblink"
# }
## Add more topics?
# }
##For-Loop each topic displays their name, description, and the link.
# for topicname, topicinfo in topics.items():
# print("\n")
# print(topicname)
# print(topicinfo['descript'])
# print(topicinfo['topicLink'])
# print("\n") |
71e6ac073a1488d1f9ce4abdc86aad30fcd67e25 | HannibalCJH/Leetcode-Practice | /002. Add Two Numbers/Python: Recursive Solution.py | 921 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
def addNumbers(list1, list2, carry):
if not list1 and not list2:
# Python的三元运算符,"True result" if True else "False result"
return ListNode(1) if carry else None
if not list1:
list1 = ListNode(0)
if not list2:
list2 = ListNode(0)
sum = list1.val + list2.val + carry
node = ListNode(sum % 10)
node.next = addNumbers(list1.next, list2.next, sum // 10)
return node
return addNumbers(l1, l2, 0)
|
95243651c271a0289c9879e90f86b29f0534cf10 | camilooob/pythonisfun | /errores.py | 246 | 3.890625 | 4 | paises = {
"colombia": 49,
"mexico": 244,
"argentina": 20
}
while True:
country = str(input("Ingrese el pais:")).lower()
try:
print("El pais {} tiene {}".format(country, paises[country]))
except KeyError:
print("No tenemos ese dato")
|
a0ee55e5165643eac48e2701eb0d4690b177df38 | camilooob/pythonisfun | /.history/discounted_20191130165043.py | 1,100 | 3.890625 | 4 | def main():
# # Inputs
price = 500
# # Process
DISCOUNT30 = 0.3
DISCOUNT20 = 0.2
DISCOUNT10 = 0.1
DISCOUNT5 = 0.05
DISCOUNT0 = 0
DISCOUNTO = 0
NEWPRICE = 0
if PRICE >= 300:
DESCUENTO = PRICE * DISCOUNT30
NEWPRICE = PRICE - DESCUENTO
print("discount= ", DISCOUNT30)
print("price = ", NEWPRICE)
elif PRICE >= 200 and PRICE < 300:
DESCUENTO = PRICE * DISCOUNT20
NEWPRICE = PRICE - DESCUENTO
print("discount= ", DISCOUNT20)
print("price = ", NEWPRICE)
elif PRICE >= 100 and PRICE < 200:
DESCUENTO = PRICE * DISCOUNT10
NEWPRICE = PRICE - DESCUENTO
print("discount= ", DISCOUNT10)
print("price = ", NEWPRICE)
elif PRICE < 100 and PRICE >= 0:
DESCUENTO = PRICE * DISCOUNT5
NEWPRICE = PRICE - DESCUENTO
print("discount= ", DISCOUNT5)
print("price = ", NEWPRICE)
elif PRICE < 0:
DESCUENTO = PRICE * DISCOUNT0
NEWPRICE = PRICE
print("No Discount")
print("price = ", NEWPRICE)
main()
|
8861ee4af0e8b701eeda7d304a4d2293f67f8132 | Pejoicen/CalcRtlCodeLineNumber | /检测有效代码行数.py | 5,293 | 3.796875 | 4 | #open file
#read one line contex,judge if code or comment
# if '--' in the head this line is comment
# if doesn’t has code this line is empty
# else this line is code line
filename = input('''要求文件编码格式为UTF-8
.vhd文件,支持识别 -- 注释,以及空行
.v 文件,支持识别 // 注释, /**/ 注释,以及空行
输入文件路径(包含文件名和扩展名):''')
# open file
#file = open(filename,encoding='ANSI')
#file = open(filename,encoding='UTF-8')
#file = open(filename)
totalline = 0
validline = 0
emptyline = 0
commentline = 0
commentcnt = 0
commentflag = 0
validcharcnt= 0
# .vhd => 1 .v => 2
FileType = 0
#file is .v or .vhd(.VHD)
#get filename length
length = len(filename)
if filename[length-3:length] == 'vhd' or filename[length-3:length] == 'VHD':
FileType = 1
elif filename[length-1:length] == 'v' or filename[length-3:length] == 'V':
FileType = 2
else:
FileType = 3
print('不支持该文件类型')
exit()
# open file with auto close
with open(filename,encoding='UTF-8') as file:
if FileType == 1 :
for line in file.readlines():
totalline = totalline +1
commentcnt = 0
commentflag = 0
validcharcnt = 0
#print(line)
for char in line:
if char == '-' and validcharcnt == 0: #if - over 2 means this line is comment line
commentcnt = commentcnt +1
#print('find - ,commentcnt =',commentcnt)
elif commentcnt == 1 and char == '-' and validcharcnt == 1: #because - is also validchar
commentflag = 1
#print('注释行+1')
break
if char !='' and char != ' ' and char !='\n' and char != '\r' : #if this line is not empty and not comment line so it is validline
validcharcnt = validcharcnt +1
#print('validcharcnt + 1',validcharcnt)
if validcharcnt==0: # 1 line for complete and validchar still = 0 so this line is empty line
emptyline = emptyline +1
elif commentflag == 0:
validline = validline +1 # 1 line for complete and validchar > 0 so this line is valid line
else:
commentline = commentline + 1
#print('one line compelte ,now validcharcnt is',validcharcnt)
print('总行数为:',totalline)
print('有效行数为:',validline)
print('空行数为:',emptyline)
print('注释行为:',commentline)
# when file type is verilog
else :
BlockCommentFlag1 =0 # for /**/ and # if 0 #endif
for line in file.readlines():
totalline = totalline +1
commentcnt = 0
commentflag = 0
validcharcnt = 0
#print(line) #for debug
for char in line:
if char == '/' and validcharcnt == 0: # the first valid char is '/' #if / over 2 means this line is comment line
commentcnt = commentcnt +1
#print('find - ,commentcnt =',commentcnt)
elif commentcnt == 1 and char == '/' and validcharcnt == 1: #because / is also validchar //
commentflag = 1
#print('注释行+1')
break
elif commentcnt == 1 and char =='*' and validcharcnt == 1: # /* start
BlockCommentFlag1 = 1
break
if char =='*' and validcharcnt == 0: # the first valid char is '*'
commentcnt = commentcnt +1
elif commentcnt == 1 and char =='/' and validcharcnt == 1 : # */ complete
BlockCommentFlag1 = 0
commentline = commentline +1 # because this line is also comment line
break
if char !='' and char != ' ' and char !='\n' and char != '\r' : #if this line is not empty and not comment line so it is validline
validcharcnt = validcharcnt +1
#print('validcharcnt + 1',validcharcnt)
if validcharcnt==0: # 1 line check complete and validchar still = 0 so this line is empty line
emptyline = emptyline +1
elif commentflag == 0 and BlockCommentFlag1 == 0 :
validline = validline +1 # 1 line check complete and validchar != 0 and it isn't comment line, so this line is valid line
else:
commentline = commentline +1
#print('one line compelte ,now validcharcnt is',validcharcnt)
print('总行数为:',totalline)
print('有效行数为:',validline)
print('空行数为:',emptyline)
print('注释行为:',commentline)
# close file
#file.close()
str = input('push any key exit') |
f70c55e08d97b515181b42d4f80798bbf7118e0a | hadrizia/coding | /hackerrank-challenges/Warm-up Challenges/Counting Valleys.py | 387 | 3.515625 | 4 | # Complete the countingValleys function below.
'''
Time efficienty: O(n)
'''
def countingValleys(n, s):
count = 0
if n > 1:
alt = 0
for step in s:
if step == 'U':
alt += 1
if alt == 0:
count += 1
else:
alt -= 1
return count
n = 8
s = ["U", "D", "D", "D", "U", "D", "U", "U", "D", "D", "U", "U"]
print countingValleys(n, s) |
5e824e80b1fc165be33154f8d1c69028f5814e3c | hadrizia/coding | /code/advanced_algorithms_problems/list_2/resort.py | 1,415 | 3.78125 | 4 | '''
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Link: http://codeforces.com/problemset/problem/350/B
'''
def create_graph():
n = int(input())
input_types = input().split(" ")
types = [int(i) for i in input_types]
input_vertex = input().split(" ")
prev = [0 for i in range(n)]
cntFrom =[0 for i in range(n)]
for i in range(n):
prev[i] = int(input_vertex[i])
prev[i] -= 1
if (prev[i] != -1):
cntFrom[prev[i]] += 1
ans = []
for i in range(n):
if types[i] == 1:
curV = i
cur = []
while prev[curV] != -1 and cntFrom[prev[curV]] <= 1:
cur.append(curV)
curV = prev[curV]
cur.append(curV)
if len(ans) < len(cur):
ans = cur
ans_alt = [str(i + 1) for i in ans[::-1]]
print(len(ans_alt))
return(' '.join(ans_alt))
print(create_graph())
|
df3d3df41e0297e35e83104db05f588db460cc8b | hadrizia/coding | /hackerrank-challenges/Dictionaries and Hashmaps/Hash Tables: Ransom Note.py | 1,044 | 3.921875 | 4 | def addWordsToDict(arr):
availableDict = {}
for word in arr:
if word not in availableDict:
availableDict[word] = 1
else:
availableDict[word] = availableDict[word] + 1
return availableDict
'''
Given that
o = number of different words in note array
Time efficiency: O(m + n + o)
'''
def checkMagazine(magazine, note):
answer = 'Yes'
availableDictInMagazine = addWordsToDict(magazine)
noteDict = addWordsToDict(note)
for word in noteDict:
if word not in availableDictInMagazine or availableDictInMagazine[word] < noteDict[word]:
answer = 'No'
break
print answer
#magazine = ["give", "me", "one", "grand", "today", "night"]
#note = ["give", "one", "grand", "today"]
magazine = ["avtq", "ekpvq", "z", "rdvzf", "m", "zu", "bof", "pfkzl", "ekpvq", "pfkzl", "bof", "zu", "ekpvq", "ekpvq", "ekpvq", "ekpvq", "z"]
note = ["m", "z", "z", "avtq", "zu", "bof", "pfkzl", "pfkzl", "pfkzl", "rdvzf", "rdvzf", "avtq", "ekpvq", "rdvzf", "avtq"]
checkMagazine(magazine, note)
|
392277285a7b7a96b240f6fe2967ea8382bdc168 | hadrizia/coding | /code/data_structures/linkedlist/singly_linkedlist.py | 3,222 | 4.0625 | 4 | from code.data_structures.linkedlist.node import Node
class LinkedList(object):
def __init__(self, head = None):
self.head = head
def insert(self, data):
new_node = Node(data)
node = self.head
if self.size() == 0:
self.head = new_node
else:
while node.next:
node = node.next
node.next = new_node
def insertNode(self, new_node):
node = self.head
if self.size() == 0:
self.head = new_node
else:
while node.next:
node = node.next
node.next = new_node
def insertToHead(self, data):
new_node = Node(data)
if self.size() == 0:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def search(self, data):
head = self.head
node = head
if node.data == data:
self.head = node.next
return head
else:
while node.next:
if node.next.data == data:
deleted_node = node.next
node.next = deleted_node.next
return deleted_node
node = node.next
raise ValueError("Data not in list")
def size(self):
node = self.head
count = 0
while node:
count += 1
node = node.next
return count
def delete(self, data):
head = self.head
node = head
if node.data == data:
self.head = node.next
return head
else:
while node.next:
if node.next.data == data:
previous = node
next = node.next
deleted_node = node.next
self.deleteByIndex(previous, next)
return deleted_node
node = node.next
raise ValueError("Data is not in list")
def deleteByIndex(self, previous, node):
if node.data == self.head.data:
self.head = node.next
else:
previous.next = node.next
def deleteHead(self):
if not self.size() == 0:
deleted_head = self.head
self.head = self.head.next
return deleted_head
# The next functions are related to questions from Cracking the Coding Interview
def countOccurences(self, data):
node = self.head
occurences = 0
while node:
if node.data == data:
occurences += 1
node = node.next
return occurences
def getKthToLast(self, k):
node = self.head
last = 0
# Get the index of last element
while node.next:
node = node.next
last += 1
# Kth to last
kth_to_last = last - k
# Search for kth_to_last
index = 0
node = self.head
while index != kth_to_last and node.next:
node = node.next
index += 1
if index == kth_to_last:
return node
raise ValueError("The Kth number does not exists!")
def prettify(self):
node = self.head
array = []
while node.next:
array.append((node.data, node.next.data))
node = node.next
array.append((node.data, node.next))
return array
def tail(self):
node = self.head
while node.next:
node = node.next
return node
def is_empty(self):
return self.size() == 0
def addAll(self, ll):
node = ll.head
while node.next:
self.insertNode(node)
node = node.next |
d4f790b54e2279548c4c00fa1fff63bfc578e2df | hadrizia/coding | /code/cracking-the-coding-interview/cap_1_strings_and_arrays/1.7.rotate-matrix.py | 1,309 | 3.625 | 4 | '''
Given a matrix NxN,
Time efficiency: O((N / 2) * N) = O(N^2)
Memory efficiency: O(1)
'''
def rotateMatrix(matrix):
n = len(matrix)
if n == 0:
return False
layers = n / 2
for layer in xrange(layers):
offset_begin = layer
offset_end = n - 1 - layer
for i in xrange(offset_begin, offset_end):
# temp variable to store top
temp = matrix[offset_begin][i]
# rotating left to top
matrix[offset_begin][i] = matrix[offset_end - i][offset_begin]
# rotating bottom to left
matrix[offset_end - i][offset_begin] = matrix[offset_end][offset_end - i]
# rotating right to bottom
matrix[offset_end][offset_end - i] = matrix[i][offset_end]
# rotating top to right
matrix[i][offset_end] = temp
return matrix
matrix_4x4 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
matrix_3x3 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
rotated_matrix_4x4 = [
[13, 9, 5, 1],
[14, 10, 6, 2],
[15, 7, 11, 3],
[16, 12, 8, 4]
]
rotated_matrix_3x3 = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
def tests():
assert rotateMatrix(matrix_3x3) == rotated_matrix_3x3
assert rotateMatrix(matrix_4x4) == rotated_matrix_4x4
assert rotateMatrix([[]]) == False
if __name__ == "__main__":
tests() |
f0ae1b82091f7d4a57ae39e8c2786ca7528db526 | hadrizia/coding | /code/data_structures/queue/queue.py | 571 | 4.0625 | 4 | from code.data_structures.linkedlist.node import Node
class Queue(object):
def __init__(self, head = None, tail = None):
self.head = head
self.tail = tail
def enqueue(self, value):
node = Node(value)
if self.is_empty():
self.head = node
self.tail = node
else:
n = self.head
while n.next:
n = n.next
n.next = node
self.tail = node
def dequeue(self):
if not self.is_empty():
n = self.head
self.head = self.head.next
return n
def is_empty(self):
return self.head == None |
fbb84944da05457e470013b116dc9bca78423a14 | hadrizia/coding | /code/advanced_algorithms_problems/list_2/laser_sculpture.py | 1,421 | 3.8125 | 4 | '''
Input
The input contains several test cases. Each test case is composed by two lines. The first line of a test case contains two integers A and C, separated by a blank space, indicating, respectively, the height (1 ≤ A ≤ 104) and the length (1 ≤ C ≤ 104) of the block to be sculpted, in milimeters. The second line contains C integers Xi, each one indicating the final height, in milimeters of the block between the positions i and i + 1 through the length (0 ≤ Xi ≤ A, for 0 ≤ i ≤ C - 1). Consider that on each step, a layer of width 1 mm is removed on the parts of the block where the laser is turned on.
The end of the input is indicated by a line that contains only two zeros, separated by a blank space.
Output
For each test case, your program must print a single line, containing an integer, indicating the number of times that the laser must be turned on to sculpt the block in the indicated format.
Link: https://www.urionlinejudge.com.br/judge/en/problems/view/1107
'''
def laser_sculpture():
raw_input = input()
while raw_input != "0 0":
h = int(raw_input.split(" ")[0])
l = int(raw_input.split(" ")[1])
last_block = h
moves = 0
blocks = [int(x) for x in input().split(" ")]
for b in blocks:
if last_block > b:
moves += (h - b) - (h - last_block)
last_block = b
print(moves)
raw_input = input()
laser_sculpture() |
cd9996229b3da37855c54db0bbfd8d404c2c0479 | hadrizia/coding | /code/cracking-the-coding-interview/cap_3_stacks_and_queues/3.3.stack_of_plates.py | 1,949 | 3.75 | 4 | from code.data_structures.stack.stack import Stack
from code.data_structures.linkedlist.node import Node
class SetOfStacks(object):
def __init__(self, stacks = [], capacity_of_stacks = 0):
self.stacks = stacks
self.capacity_of_stacks = capacity_of_stacks
def is_empty(self):
return len(self.stacks) == 0
def add_new_stack_to_set(self, value):
stack = Stack()
stack.push(value)
self.stacks.append(stack)
def push(self, value):
if self.is_empty():
self.add_new_stack_to_set(value)
else:
last_stack = self.stacks[-1]
if last_stack.size() < self.capacity_of_stacks:
last_stack.push(value)
else:
self.add_new_stack_to_set(value)
def pop(self):
if not self.is_empty():
last_stack = self.stacks[-1]
deleted_node = last_stack.pop()
if last_stack.is_empty():
self.stacks.remove(last_stack)
return deleted_node
def pop_at(self, index):
indexed_stack = self.stacks[index]
if indexed_stack != None:
deleted_node = indexed_stack.pop()
if indexed_stack.size() == self.capacity_of_stacks - 1:
for i in range(index, len(self.stacks) - 1):
self.stacks[i].push(self.stacks[i + 1].remove_bottom().data)
if self.stacks[i + 1].is_empty():
self.stacks.remove(self.stacks[i + 1])
break
return deleted_node
def tests():
set_of_stacks = SetOfStacks(capacity_of_stacks = 2)
set_of_stacks.push(1)
set_of_stacks.push(2)
set_of_stacks.push(3)
assert len(set_of_stacks.stacks) == 2
set_of_stacks.pop()
assert len(set_of_stacks.stacks) == 1
set_of_stacks.push(3)
set_of_stacks.push(4)
set_of_stacks.push(5)
assert len(set_of_stacks.stacks) == 3
set_of_stacks.pop_at(0)
assert len(set_of_stacks.stacks) == 2
assert set_of_stacks.stacks[0].top.data == 3
assert set_of_stacks.stacks[1].top.data == 5
if __name__ == "__main__":
tests() |
f3974732df9e9a3124cdffb22f7664f3e35892c1 | hadrizia/coding | /code/data_structures/heap/heap.py | 881 | 3.90625 | 4 | class Heap(object):
def __init__(self, heap=[]):
self.heap = heap
def heapify(self, i, n):
biggest = i
left = i * 2 + 1
right = i * 2 + 2
if left < n and self.heap[left] > self.heap[i]:
biggest = left
if right < n and self.heap[right] > self.heap[biggest]:
biggest = right
if biggest != i:
self.heap[biggest], self.heap[i] = self.heap[i], self.heap[biggest]
self.heapify(biggest, n)
else:
return
def build_heap(self):
n = len(self.heap)
for i in range(len(h.heap) // 2 - 1, -1, -1):
h.heapify(i, n)
def heapsort(self):
self.build_heap()
n = len(self.heap)
for i in range(n - 1, 0, -1):
self.heap[i], self.heap[0] = self.heap[0], self.heap[i]
self.heapify(0, i)
h = Heap([4, 6, 2, 3, 1, 9])
h.build_heap()
h.heapsort()
assert h.heap == [1, 2, 3, 4, 6, 9]
|
32235f471cbf55cbe6a643306112c62f66dd756e | hadrizia/coding | /code/advanced_algorithms_problems/list_2/where_are_my_keys.py | 1,210 | 3.890625 | 4 | '''
Input
The first line contains two integers Q(1 ≤ Q ≤ 1*103) and E(1 ≤ E ≤ Q) representing respectively the number of offices that he was in the last week and the number of offices that he was in the last two days.
The second line contains E integers Si (1 ≤ Si ≤ 1000) containing the Identification number of each office that he was in the last two days.
The next line contains Q integers Ci (1 ≤ Ci ≤ 1000) containing the identification number of each one of the offices that he was in the last week.
Output
For each office that he was in the last week your program should return “0” in case he has already visited that office while looking for the keys. Else your program should return “1” in case he hasn't visited that office yet while he was looking for the keys.
Link: https://www.urionlinejudge.com.br/judge/pt/problems/view/1800
'''
def was_room_visited():
total_offices = int(input().split(" ")[0])
visited_offices = [int(x) for x in input().split(" ")]
for _ in range(total_offices):
office = int(input())
if office not in visited_offices:
print(1)
visited_offices.append(office)
else:
print(0)
was_room_visited() |
4df464f1545fa3165344654a596eeedf5d78444d | hadrizia/coding | /code/cracking-the-coding-interview/cap_1_strings_and_arrays/1.6.string-compression.py | 647 | 3.875 | 4 | '''
Given that:
N = len(string),
Time efficiency: O(n)
Memory efficiency: O(n)
'''
def stringCompression(string):
occurrences = 0
compressedString = ''
for i in range(len(string)):
occurrences += 1
if (i + 1 >= len(string)) or string[i] != string[i + 1]:
compressedString += string[i] + str(occurrences)
occurrences = 0
return compressedString if len(compressedString) < len(string) else string
def tests():
assert stringCompression('aaaabbbbcccc') == 'a4b4c4'
assert stringCompression('abcde') == 'abcde'
assert stringCompression('aaaabbbbccccAA') == 'a4b4c4A2'
if __name__ == "__main__":
tests() |
2bbb704056da71a4f0e76263de4cf58ff9522979 | hadrizia/coding | /code/cracking-the-coding-interview/cap_2_linked_lists/2.1.remove_dups.py | 757 | 3.578125 | 4 | from code.data_structures.linkedlist.singly_linkedlist import LinkedList
'''
Given that N = linked_list.size(),
Time efficiency: O(N)
'''
def removeDups(linked_list):
node = linked_list.head
buffer = []
buffer.append(node)
while node:
if node.data not in buffer:
buffer.append(node.data)
else:
linked_list.delete(node.data)
node = node.next
return linked_list
def removeDupsWithoutBuffer(linked_list):
node = linked_list.head
if(linked_list.countOccurences(node.data) > 1):
linked_list.deleteByIndex(None, node)
while node.next:
count = linked_list.countOccurences(node.next.data)
if count > 1:
linked_list.deleteByIndex(node, node.next)
node = node.next
return linked_list
c |
9dfd3b48523e12e4bafac6630a48024e03c3bff8 | czarny25/pythonStudy | /PythonFundamentals/testingFolder/testnumpy.py | 270 | 3.859375 | 4 | '''
Created on 14 Apr 2020
@author: Marty
'''
import numpy as np # numpy is external library and need to be imported
# simple list
list = [1,2,3,4,5,6,7]
# variable of numpy array type take list as argument
x = np.array(list)
print(type(x))
print(x) |
723b4825326e39a7c363ea10bab1c4c634945e7a | Flipez/snippets | /python/list_dir.py | 784 | 3.8125 | 4 | #!/usr/bin/env python
import os, sys, sqlite3
def get_dirs(dir):
path = dir
dir_list = os.listdir( path )
return( dir_list )
print("This will list the dirs and save them to a sqlite database")
print("Please enter a valid path")
dir_list = get_dirs(input())
if os.path.exists("db.db"):
print("[db]database exists")
sys.exit
connection = sqlite3.connect("db.db")
cursor = connection.cursor()
sql = "CREATE TABLE dirs(" \
"name TEXT, " \
"number INTEGER PRIMARY KEY)"
cursor.execute(sql)
count = 0
for file in dir_list:
cursor.execute("INSERT INTO dirs (name, number) values (?,?)", (file, count))
count = count + 1
connection.commit()
connection.close
#fobj = open("db.txt", "w")
#for file in dir_list:
# fobj.write(file)
#fobj.close()
|
846cc6cd0915328b64f83d50883167e0d0910f6a | Teju-28/321810304018-Python-assignment-4 | /321810304018-Python assignment 4.py | 1,839 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## 1.Write a python function to find max of three numbers.
# In[5]:
def max():
a=int(input("Enter num1:"))
b=int(input("Enter num2:"))
c=int(input("Enter num3:"))
if a==b==c:
print("All are equal.No maximum number")
elif (a>b and a>c):
print("Maximum number is:",a)
elif (b>c and b>a):
print("Maximum number is:",b)
else:
print("Maximum number is:",c)
max()
# ## 2.Write a python program to reverse a string.
# In[6]:
def reverse_string():
A=str(input("Enter the string:"))
return A[::-1]
reverse_string()
# ## 3.write a python function to check whether the number is prime or not.
# In[13]:
def prime():
num=int(input("Enter any number:"))
if num>1:
for i in range(2,num):
if (num%i==0):
print(num ,"is not a prime number")
break
else:
print(num ,"is a prime number")
else:
print(num ,"is not a prime number")
prime()
# ## 4.Use try,except,else and finally block to check whether the number is palindrome or not.
# In[25]:
def palindrome():
try:
num=int(input("Enter a number"))
except Exception as ValueError:
print("Invalid input enter a integer")
else:
temp=num
rev=0
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
if(temp==rev):
print("The number is palindrome")
else:
print("Not a palindrome")
finally:
print("program executed")
palindrome()
# ## 5.Write a python function to find sum of squares of first n natural numbers
# In[27]:
def sum_of_squares():
n=int(input("Enter the number"))
return (n*(n+1)*(2*n+1))/6
sum_of_squares()
|
f65750847bc5cd37f7e53a50469f2db9498f84b4 | Ivan395/Python | /rfc.py | 961 | 3.859375 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
import curp
def letters(ap):
letras = [chr(x) for x in range(65, 91)] + [chr(x) for x in range(97, 123)]
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if(len(ap) == 13):
if(ap[0] in letras and ap[1] in letras and ap[2] in letras and ap[3] in letras):
if(ap[4] in numbers and ap[5] in numbers and ap[6] in numbers and ap[7] in numbers and ap[8] in numbers and ap[9] in numbers):
st = str('19' + ap[4:6] + '/' + ap[6:8] + '/' + ap[8: 10]).split('/')
if(ap[10] in numbers or ap[10] in letras and ap[11] in numbers or ap[11] in letras and ap[12] in numbers or ap[12] in letras):
return curp.dtval(st)
return False
def run():
tmp_rfc = input("Ingresa el RFC: ")
if(letters(tmp_rfc)):
print('El RFC es correcto')
else:
print('El RFC NO es correcto')
if __name__ == '__main__':
run()
|
adb2991ea7cc9e8c3a2c35d1698dee8949e84497 | NereBM/Python-Pandas | /Working with datasets.py | 4,483 | 4.1875 | 4 | import pandas as pd
########--------------------5:Concatenating and Appending dataframes------------
df1 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2001, 2002, 2003, 2004])
df2 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2005, 2006, 2007, 2008])
df3 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'Low_tier_HPI':[50, 52, 50, 53]},
index = [2001, 2002, 2003, 2004])
#simple concatenation, as df1 and df2 have same columns and different indexes
concat = pd.concat([df1,df2])
print(concat)
#here we have missing values
concat = pd.concat([df1,df2,df3])
print(concat)
#we use append to add at the end
df4 = df1.append(df2)
print(df4)
#BUT THIS HAPPENS IF WE APPEND DATA WITH THE SAME INDEX
df4 = df1.append(df3)
print(df4)
#It is important here to introduce the concept of "Series".A series is basically a single-columned dataframe.
#A series does have an index, but, if you convert it to a list, it will be just those values.
#Whenever we say something like df['column'], the return is a series.
s = pd.Series([80,2,50], index=['HPI','Int_rate','US_GDP_Thousands'])
df4 = df1.append(s, ignore_index=True)
print(df1)
print(df4)
#We have to ignore the index when appending a series, because that is the law, unless the series has a name.
#############--------------6:Joining and Merging Dataframes--------------------------
df1 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2001, 2002, 2003, 2004])
df2 = pd.DataFrame({'HPI':[80,85,88,85],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55]},
index = [2005, 2006, 2007, 2008])
df3 = pd.DataFrame({'HPI':[80,85,88,85],
'Unemployment':[7, 8, 9, 6],
'Low_tier_HPI':[50, 52, 50, 53]},
index = [2001, 2002, 2003, 2004])
#Here we merge by HPI
print(pd.merge(df1,df3, on='HPI'))
#We can also merge by several columns
print(pd.merge(df1,df2, on=['HPI','Int_rate']))
#Pandas is a great module to marry to a database like mysql? here's why
df4 = pd.merge(df1,df3, on='HPI')
df4.set_index('HPI', inplace=True)
print(df4)
#Now, what if HPI was already the index?
# Or, in our case, We'll probably be joining on the dates,
# but the dates might be the index. In this case, we'd probably use join.
df1.set_index('HPI', inplace=True)
df3.set_index('HPI', inplace=True)
print(df1)
print(df3)
joined = df1.join(df3)
print(joined)
#What happens if we have slightly different indexes?
df1 = pd.DataFrame({
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands':[50, 55, 65, 55],
'Year':[2001, 2002, 2003, 2004]
})
df3 = pd.DataFrame({
'Unemployment':[7, 8, 9, 6],
'Low_tier_HPI':[50, 52, 50, 53],
'Year':[2001, 2003, 2004, 2005]})
merged = pd.merge(df1,df3, on='Year')
print(merged)
merged = pd.merge(df1,df3, on='Year')
merged.set_index('Year', inplace=True)
print(merged)
#The parameters that ar not common are missing, how do we solve this? With the "how" parameter of merge:
#Left - equal to left outer join SQL - use keys from left frame only
#Right - right outer join from SQL- use keys from right frame only.
#Outer - full outer join - use union of keys
#Inner - use only intersection of keys.
merged = pd.merge(df1,df3, on='Year', how='left')
merged.set_index('Year', inplace=True)
print(merged)
#Merging on the left is literally on the left dataframe. We had df1, df3,
# the one on the left is the first one, df1. So, we wound up with an index
# that was identical to the left dataframe (df1).
merged = pd.merge(df1,df3, on='Year', how='outer')
merged.set_index('Year', inplace=True)
print(merged)
#With the "outer" all the indexes are shown
#Finally, "inner" is the intersection of keys, basically just what is shared between all the sets.(It is the defautl option)
#we an do the same with join:
df1.set_index('Year', inplace=True)
df3.set_index('Year', inplace=True)
joined = df1.join(df3, how="outer")
print(joined) |
a843bf881c50bb3f0dda17c4da2dca48d410fce4 | Jorgelsl/batchroja | /listas.py | 416 | 3.984375 | 4 | list1 = [2,3,1,4,5]
list2 = ["A","B","C","D"]
list3 = ["MATEMATICAS", "HISTORIA", 1999, 1992]
list4 = [list1, list2, list3]
'''
print(list1)
print(list2)
print(list3)
print(list4)
for i in list3:
print(i)
'''
frutas = ['naranja', 'manzana', 'pera', 'fresa', 'banana', 'manzana', 'kiwi']
print(frutas)
frutas.append('uva')
print(frutas)
frutas.extend(list2)
print(frutas)
frutas.insert(0,'melon')
print(frutas) |
186d9dcc93bb4b20c9f79a3460f00b2e2e0f0728 | sanjaylokula/100dayspython | /days/month/day8_23.py | 890 | 3.984375 | 4 | #Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
#Example:
#Input: [1,2,1,3,2,5]
#Output: [3,5]
#Note:
#The order of the result is not important. So in the above example, [5, 3] is also correct.
#Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
output_dict = dict()
for i in nums:
if i not in output_dict:
output_dict[i] = 1
else:
output_dict[i] += 1
return [key for key, value in output_dict.items() if value == 1]
if __name__=="__main__":
output=Solution().singleNumber([1,2,3,4,2,1,2])
print(output) |
b973afe64648468eb6bb9e8a83b8cfdba2e4c8b9 | CBASoftwareDevolopment2020/Exam-Notes | /Algorithms/Implementations/sorting.py | 3,607 | 3.53125 | 4 | from time import time
from random import choice, randint, shuffle
def selection_sort(arr, timeout=60):
n = len(arr)
if 0 <= n <= 1:
return
start = time()
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
if time() - start > timeout:
raise TimeoutError(f'Sorting took longer than {timeout} seconds')
def insertion_sort(arr, timeout=60):
n = len(arr)
if 0 <= n <= 1:
return
start = time()
for i in range(1, n):
for j in range(i, 0, -1):
if arr[j] < arr[j - 1]:
arr[j], arr[j - 1] = arr[j - 1], arr[j]
if time() - start > timeout:
raise TimeoutError(f'Sorting took longer than {timeout} seconds')
def merge_sort(arr):
def merge(l, r):
new = []
left_idx = right_idx = data_idx = 0
left_len, right_len = len(l), len(r)
while left_idx < left_len and right_idx < right_len:
if l[left_idx] < right[right_idx]:
new.append(l[left_idx])
left_idx += 1
else:
new.append(r[right_idx])
right_idx += 1
data_idx += 1
while left_idx < left_len:
new.append(l[left_idx])
left_idx += 1
data_idx += 1
while right_idx < right_len:
new.append(r[right_idx])
right_idx += 1
data_idx += 1
return new
data = arr[:]
n = len(data)
if n < 2:
return data
mid = len(data) // 2
left = merge_sort(data[:mid])
right = merge_sort(data[mid:])
data = merge(left, right)
return data
def quick_sort(items):
arr = items.copy()
n = len(arr)
if 0 <= n <= 1:
return arr
shuffle(arr)
# if the sub array has 15 items or less use insertion sort
if n <= 15:
insertion_sort(arr)
return arr
else:
idx = randint(0, n - 1)
arr[0], arr[idx] = arr[idx], arr[0]
pivot = arr[0]
less = []
greater = []
for x in arr[1:]:
if x < pivot:
less.append(x)
else:
greater.append(x)
return quick_sort(less) + [pivot] + quick_sort(greater)
def quick_sort_3way(items):
arr = items.copy()
n = len(arr)
if 0 <= n <= 1:
return arr
shuffle(arr)
# if the sub array has 15 items or less use insertion sort
if n <= 15:
insertion_sort(arr)
return arr
else:
pivot = choice(arr)
less = []
equal = []
greater = []
for x in arr:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
else:
greater.append(x)
return quick_sort_3way(less) + equal + quick_sort_3way(greater)
def heapify(data, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and data[left] > data[largest]:
largest = left
if right < n and data[right] > data[largest]:
largest = right
if largest != i:
data[i], data[largest] = data[largest], data[i]
heapify(data, n, largest)
def heap_sort(arr):
n = len(arr)
if n < 2:
return arr
for i in range(n, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
return arr
|
22b5a162408555fa5aea974ebafc6dbd56ea8f18 | BercziSandor/pythonCourse_2020_09 | /DataTransfer/json_1.py | 1,153 | 4.21875 | 4 | # https://www.w3schools.com/python/python_json.asp
# https://www.youtube.com/watch?v=9N6a-VLBa2I Python Tutorial: Working with JSON Data using the json Module (Corey Schaefer)
# https://lornajane.net/posts/2013/pretty-printing-json-with-pythons-json-tool
# http://jsoneditoronline.org/ JSON online editor
###################
# JSON: JavaScript Object Notation. Adatcseréhez, konfigurációs fájlokhoz használják,
# a legtöbb nyelvben van illesztő egység hozzá.
# loads: Sztringből beolvasás.
import json
str_1 = '{"name": "John", "age":30.5, "cities": ["New York", "Budapest"]}'
x = json.loads(str_1)
print(x) # {'name':'John', 'age':30.5, 'cities': ['New York', 'Budapest']}
# A sztringeknél idézőjelet kell használni, aposztrofot nem fogad el.
str_1 = '{'name': "John"}'
x = json.loads(str_1) # SyntaxError
# A dict kulcsoknak sztringeknek kell lenniük.
# tuple-t, set-et nem ismer.
###################
# dumps: sztringbe írás.
import json
lst_1 = ['John', 30.5, ['New York', 'Budapest']]
str_1 = json.dumps(lst_1)
print(str_1, type(str_1)) # ["John", 30.5, ["New York", "Budapest"]] <class 'str'>
###################
|
efca8c666dfa01890679fb36817da3abc2a8c586 | BercziSandor/pythonCourse_2020_09 | /Lecture_11/mix_11.py | 350 | 3.953125 | 4 | # Else ág ciklusoknál: akkor megy rá a vezérlés, ha nem volt break
for i in range(5):
print(i)
else:
print('végigment a for ciklus')
for i in range(5):
print(i)
if i == 3:
break
else:
print('no break')
# Üres ciklusnál is működik:
for i in range(5,0):
print(i)
else:
print('végigment a for ciklus')
|
0fd245e6318b5016856b46828f1e397779bf3da6 | BercziSandor/pythonCourse_2020_09 | /Lecture_3/break_continue_1.py | 365 | 3.9375 | 4 | # Kilépés while és for ciklusból: break utasítás
lst = [1, 2, 3, 4, 5, 6]
for e in lst:
if e > 2:
break
print(e)
# 10
# 20
# while ciklusban ugyanígy működik.
lst = [1, 2, 3, 4, 5, 6]
# Ciklus folytatása:
for e in lst:
if e % 3 == 0:
continue
print(e)
# 1
# 2
# 4
# 5
|
62b18cc42a6e7a4bbca94ed532807160b5e56cdc | BercziSandor/pythonCourse_2020_09 | /Num_py/numpy_8.py | 2,047 | 4.09375 | 4 | # Fancy indexing
# Egyes szerzőknél a boolean indexelés (maszkolás) is ezen címszó alá tartozik.
# Én csak az integer listával való indexelést hívom így.
# http://scipy-lectures.org/intro/numpy/array_object.html#fancy-indexing
# https://medium.com/better-programming/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d
# http://jalammar.github.io/visual-numpy/
# Fancy indexing: tetszőleges indexeket összegyűjtök egy listába és ezzel indexelem a tömböt.
# Ellentétben a slicing-gal itt nem kell semmilyen szabályosságnak fennállnia.
import numpy as np
arr_1 = np.array([10, 20, 30, 40, 50])
arr_2 = arr_1[[1, 2, 4]]
print(arr_2) # [20 30 50]
# Ezt helyettesíti:
arr_2 = np.array([arr_1[1], arr_1[2], arr_1[4]])
# Az indexet sokszor egy változóba tesszük:
ix = [1, 2, 4]
arr_2 = arr_1[ix]
print(arr_2) # [20 30 50]
#############################
# Két dimenziós tömböknél persze külön indexelhetjük a sorokat és az oszlopokat:
arr_1 = np.array([
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]
])
row = np.array([0, 1, 2])
col = np.array([2, 1, 3])
arr_2 = arr_1[row, col]
print(arr_2) # [2, 5, 11]
#############################
# A keletkező tömb másolat, NEM referencia (view).
arr_1 = np.array([10, 20, 30, 40, 50])
arr_2 = arr_1[[1, 2, 4]]
print(arr_2) # [20 30 50]
arr_2[0] = 99
print(arr_2) # [99 30 50]
print(arr_1) # [10 20 30 40 50] -- nem változott
# ****** Amikor egy adatszerkezetet előállítunk egy másikból, MINDIG vizsgáljuk
# ****** meg, hogy másolat (copy) keletkezett-e, vagy referencia (view).
#############################
# Viszont a fancy indexeléssel kiválasztott elemeket módosítani is tudjuk.
arr_1 = np.array([10, 20, 30, 40, 50])
ix = [1, 2, 4]
arr_1[ix] = 99
print(arr_1) # [10 99 99 40 99]
# Nem csak egyetlen értékkel írhatjuk fölül a tömb elemeit, a broadcast itt is működik:
arr_1 = np.array([10, 20, 30, 40, 50])
ix = [1, 2, 4]
arr_1[ix] = [97, 98, 99]
print(arr_1) # [10 97 98 40 99]
#############################
|
bbd8632e442e9f7ab0812a7a1942e157ecdfc26b | BercziSandor/pythonCourse_2020_09 | /Lecture_2/tippmix_2.py | 1,719 | 3.703125 | 4 | # Mi lesz a kimenet? Lehet hibajelzés is.
# NE futtassuk le, mielőtt tippelnénk!
# Órán a szabályok:
# Amikor valaki úgy gondolja, hogy van ötlete a megoldásra, akkor bemondja, hogy: VAN TIPP!
# Amikor azt mondom, hogy "Kérem a tippeket" és valaki egy kicsit még gondolkodni szeretne, akkor bemondja, hogy: IDŐT KÉREK!
# Egyébként pedig nyilván sorra mindenki bemondja, hogy mit gondolt ki.
###########################################################
# 1.
def f(x, y, z):
print(x, y, z)
f(z=30, y=20, x=10)
###################
# 2.)
def f(x, y, z):
print(x, y, z)
f(z=30, y=20, 10)
###################
# 3.)
lst = [3, (10, 20, 30),['A', 'B']]
print(lst[1][2])
print(lst[1],[2])
###################
# 4.)
lst = [3, (10, 20, 30),['A', 'B']]
print(len(lst[2][1]))
print(len(lst[1][2]))
###################
# 5.)
def f(x, y, z):
print(x, y, z)
f(10, y=20, z=30)
###################
# 6.)
dic = {'a': 10, 'b': 20}
print(dic['B'])
###################
# 7.)
for i in range(1,2):
print(10*i)
###################
# 8.)
def f(*, x, y, z):
print(x, y, z)
f(10, y=20, z=30))
###################
# 9.)
x = 100
X = 10
print(x + X)
###################
# 10.)
for x in range(3, 1, -2):
print(x)
###################
# 11.)
def f(x, y, z):
print(x, y, z)
f(30, y=20, x=10)
###################
# 12.)
r = range(1, 4)
for x in r:
print(x, end=' ')
print()
###################
# 13.)
def func(param):
return y + param
y = 'abc'
print(func('xxx'))
y = [10, 20, 30]
print(func([99]))
y = (100)
print(func((5, 4, 3)))
###################
# 14.)
def func(param):
y += 100
return y + param
y = 30
print(func(1))
################### |
e26bfd8720509b619de1ce671ea3ca273f606b9a | BercziSandor/pythonCourse_2020_09 | /Lecture_8/solutions_7.py | 2,668 | 3.515625 | 4 | # Lecture_7\exercises_7.py megoldásai
# 1.)
# A dict-té alakítás felesleges, ráadásul 3.7-es verzió előtt hibás is lehet az eredmény,
# mert a dict-ből kiolvasásnál nincs definiálva a sorrend.
names_reversed = [ e[0] for e in sorted(employees, key=lambda x: x[0], reverse=True)]
print(names_reversed) # ["Zach","James", "Cecilia", "Ann"]
####################################
# 2.)
# A.
# Ha az lst-ben vannak többször előforduló elemek, ezek a kimeneten csak egyszer
# fognak szerepelni:
lst = [10, 11, 5, 6, 7, 4, 6] # 6 kétszer van
tup = (10, 11, 7, 4)
# [25, 36]
# B.
res = [e*e for e in lst if e not in tup]
# [25, 36, 36]
####################################
# 3.)
lines = ['AA BB CC', 'AA EE FF', 'GG HH II']
s_list = ('AA', 'EE', 'XX')
result = find_any(lines, s_list)
print(result) # ['AA BB CC', 'AA EE FF', 'AA EE FF']
# Ha több keresett sztring is előfordul egy sorban, akkor az a sor többször meg
# fog jelenni a kimeneten.
# B.
def find_any(lines, search_list):
out_lst = []
for line in lines:
for searched in search_list:
if searched in line:
out_lst. append(line)
break # ez hiányzott
return out_lst
####################################
# 4.)
def find_all(lines, search_list):
out_lst = []
for line in lines:
do_it = True
for searched in search_list:
if searched not in line:
do_it = False
break
if do_it:
out_lst.append(line)
return out_lst
lines = ['AA BB CC', 'AA EE FF', 'GG HH II']
s_list = ('AA', 'EE')
result = find_all(lines, s_list)
print(result)
####################################
# 5.)
def merge_func(series_1, series_2):
x_1 = None; x_2 = None
it_1 = iter(series_1)
it_2 = iter(series_2)
while True:
try:
if x_1 is None:
x_1 = next(it_1)
except StopIteration:
x_1 = None
try:
if x_2 is None:
x_2 = next(it_2)
except StopIteration:
x_2 = None
if x_1 is None and x_2 is None:
return
if x_2 is None:
yield x_1
x_1 = None
continue
if x_1 is None:
yield x_2
x_2 = None
continue
if x_1 <= x_2:
yield x_1
x_1 = None
else:
yield x_2
x_2 = None
lst_1 = [10, 20, 30, 40, 40]
lst_2 = [15, 25, 25, 50]
lst = [x for x in merge_func(lst_1, lst_2)]
print(lst) # [10, 15, 20, 25, 25, 30, 40, 40, 50]
####################################
|
3d72b228e7f5806f8d20bd160fe166ad496f39bc | BercziSandor/pythonCourse_2020_09 | /Lecture_13/exercises_13.py | 772 | 3.78125 | 4 | # 1.)
# Lecture_12\exercises_12.py 3. feladathoz térünk vissza, módosítjuk egy kicsit.
# Írjunk generátor-függvénnyel megvalósított iterátort, amely inicializáláskor egy
# iterálható obkektumot és egy egész számot kap paraméterként. Azokat az elemeket
# adja vissza a számmal elosztva a bemeneti objektum által szolgáltatott sorozatból,
# amelyek oszthatóak a számmal. A bemeneti sorozat lehet inhomogén; amely elemeken nem
# végezhető el a modulo művelet, azokat az iterátor adja ki változatlanul a kimenetre.
def modIterFunc_2(inputSeries, number):
pass
m = modIterFunc_2([1, 'A', [10, 20], 66, 8, 12, (24, 36)], 6)
for e in m:
print(e)
# 'A'
# [10, 20]
# 11.0
# 2.0
# (24, 36)
############################################
|
f81b9e4fdf5b0d1dc28194beb061bd140d6996b9 | BercziSandor/pythonCourse_2020_09 | /Functions/scope_2.py | 2,977 | 4.21875 | 4 | # Változók hatásköre 2.
# Egymásba ágyazott, belső függvények
# global kontra nonlocal
# https://realpython.com/inner-functions-what-are-they-good-for/
# Függvényen belül is lehet definiálni függvényt. Ezt sok hasznos dologra fogjuk tudni használni.
# Első előny: információrejtés. Ha a belső függvény csak segédművelet, amit kívül nem
# használunk, akkor jobb, ha a függvényen kívül nem is látszik.
# A változót belülről kifelé haladva keresi a futtató rendszer.
def func():
def inner():
x = 'x inner' # x itt definiálódott
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x inner
######################################
def func():
def inner():
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x func local
######################################
def func():
def inner():
print(x)
inner()
x = 'x global'
func() # x global
######################################
def func():
def inner():
print(x) # itt használom
x = 'x inner' # de csak itt definiálom
inner()
x = 'x global'
func() # hiba, először használom, aztán definiálom
######################################
def func():
def inner():
global x
print(x)
x = 'x inner'
inner()
x = 'x global'
func() # x global
print('x func() után:', x) # x func() után: x inner
######################################
# A global-nak deklarált változókat a tartalmazó függvényben NEM keresi.
def func():
def inner():
global x
print(x)
x = 'x func local' # nem ezt találja meg
inner()
x = 'x global'
func() # x global
######################################
# A nonlocal-nak deklarált változókat a legkülső függvényen kívül (modul szinten) nem keresi.
# Ez rendben van:
def func():
def inner():
nonlocal x
print(x)
x = 'x func local'
inner()
x = 'x global'
func() # x func local
# De ez nem működik:
def func():
def inner():
nonlocal x
print(x) # itt használná
inner()
x = 'x global'
func() # hiba
# x hiába van modul-szinten definiálva, ott már nem keresi.
# Ez sem működik:
def func():
def inner():
nonlocal x
print(x) # itt használná
inner()
x = 'x func local' # de csak itt definiálódik
x = 'x global'
func() # hiba
# A felhasználáskor még nem volt definiálva x.
######################################
# A belső függvény a tartalmazó függvénynek a bemenő paramétereit is látja.
def func(outerParam):
def inner():
print('inner:',outerParam)
inner()
x = 'x global'
func('func parameter') # func parameter
# Ezt sok helyen fogjuk használni.
##################
|
e7fa14ad1683f757c0af7cb0b591d2e67a9b53df | BercziSandor/pythonCourse_2020_09 | /Datastructures/index_2.py | 2,457 | 3.921875 | 4 | # Értékadás slicing segítségével.
lst = [10, 20, 30, 40, 50]
# Az 1, 2, 3 indexű elemeket le akarjuk cserélni erre: [-2, -3, -4]
lst[1:4] = [-2, -3, -4]
print(lst) # [10, -2, -3, -4, 50]
#######################################
# Ha slicing segítségével végzünk értékadást, akkor az új elemnek egy iterálható
# sorozatnak kell lennie, amelynek az elemei kerülnek be. Ez tehát NEM működik:
lst = [10, 20, 30, 40, 50]
lst[1:4] = 99 # TypeError: can assign only an iterable
#######################################
# Az új sorozat lehet más elemszámú, mint az eredeti:
lst = [10, 20, 30, 40, 50]
lst[1:4] = [-100]
print(lst) # [10, -100, 50]
# A felső határ túlcímzése most sem okoz gondot:
lst = [10, 20, 30, 40, 50]
lst[1:100] = [-2, -3, -4]
print(lst) # [10, -2, -3, -4]
# Ha a kezdő index túl van a lista végén, akkor az elemek hozzáfűződnek a lista végéhez:
lst = [10, 20, 30, 40, 50]
lst[10:100] = [-2, -3, -4]
print(lst) # [10, 20, 30, 40, 50, -2, -3, -4]
# Ha a kezdő index túl van a lista elején, akkor az elemek hozzáfűződnek a lista
# eleje elé:
lst = [10, 20, 30, 40, 50]
lst[-6:1] = [-2, -3, -4]
print(lst) # [-2, -3, -4, 10, 20, 30, 40, 50]
#######################################
# Nyilván egyetlen elemet is le lehet cserélni:
lst = [10, 20, 30, 40, 50]
lst[1:1] = [99, 100]
print(lst) # [10, 99, 100, 30, 40, 50]
#######################################
# A lista helyben marad megváltozott tartalommal:
lst_1 = [10, 20, 30, 40, 50]
lst_2 = lst_1
lst_1[1:1] = [99, 100]
print(lst_2) # [10, 99, 100, 30, 40, 50]
# Így tudunk tehát helyben új listát létrehozni:
lst_1 = [10, 20, 30, 40, 50]
lst_2 = lst_1
lst_1[:] = [99, 100]
print(lst_2) # [99, 100]
#######################################
# A beillesztendő értéksorozat persze nem csak lista, hanem tetszőleges iterálható
# sorozat lehet:
lst = [10, 20, 30, 40, 50]
lst[1:4] = (-2, -3, -4)
print(lst) # [10, -2, -3, -4, 50]
lst = [10, 20, 30, 40, 50]
lst[1:4] = range(5)
print(lst) # [10, 0, 1, 2, 3, 4, 50]
lst = [10, 20, 30, 40, 50]
dic = {'A': 1, 'B': 2}
lst[1:4] = dic.keys()
print(lst) # [10, 'A', 'B', 50] -- a sorrend 3.6 verzió előtt nem garantált!
#######################################
# Törlés slicing segítségével.
lst = [10, 20, 30, 40, 50]
del(lst[1:4])
print(lst) # [10, 50]
lst = [10, 20, 30, 40, 50]
del(lst[1:100])
print(lst) # [10]
#######################################
|
fdda3d6a9e9284bf7f2a2379a7a328554c423bbc | BercziSandor/pythonCourse_2020_09 | /Datastructures/list_1.py | 3,101 | 4.34375 | 4 | # https://www.python-course.eu/python3_sequential_data_types.php
# Listák 1.
# append() metódus, for ciklus
# elem törlése: del() és lista törlése
# memóriacím lekérdezése: id()
x = [10, 20, 30]
print(x, type(x), len(x)) # [10, 20, 30] <class 'list'> 3
# A hosszat ugyanúgy a len() függvénnyel kérdezzük le, mint a sztringeknél.
# Különféle típusú elemeket tartalmazhat
x = [10, 'John', 32.5]
print(x) # [10, 'John', 32.5]
# Nemcsak alaptípusokat tartalmazhat, hanem listát és egyéb összetett típusokat is.
lst = [1, ['A', 2], 'B'] # a második elem egy lista
print(lst, len(lst)) # [1, ['A', 2], 'B'] 3
# Üres lista készítése
x = []
y = list()
print(x, y) # [] []
#################################
# Indexelhető
x = [10, 'John', 32.5]
print(x[0], x[len(x) - 1]) # 10 32.5
#################################
# Iterálható, for ciklussal bejárható
for e in x:
print(e, end=' ') # 10 John 32.5
print()
# Nem pythonikus for ciklus - működik, de szószátyár és ezért utáljuk.
# Az i változóra semmi szükség nincs!
for i in range(len(x)): # hivatalból üldözendő!
print(x[i], end=' ')
print() # 10 John 32.5
#################################
# Módosítható
x[1] = 'Jane'
print(x) # [10, 'Jane', 32.5]
#################################
# Új elem hozzáfűzése (append)
x.append('new item')
print(x) # [10, 'Jane', 32.5, 'new item']
# Figyeljük meg, hogy a módosítás helyben történik. Miből látszik ez?
#################################
# Elem törlése (del)
del(x[1])
print(x) # [10, 32.5, 'new item']
# Itt is helyben történik a módosítás, az x lista memóriacíme nem változik.
#################################
# Teljes lista törlése
x = []
# Ekkor x egy ÚJ, üres listára mutat! Lássuk:
x = [1, 2, 3]
id_1 = id(x)
x = []
id_2 = id(x)
print(id_1, id_2) # 7202696 7202136
# id(x): az x változó által megjelölt elem memóriacíme decimálisan.
# Látható, hogy a két memóriacím nem egyezik; 7202696 címen van
# az eredeti lista, rá már egyetlen változó sem mutat, a futtató
# rendszer ezt észreveszi és felszabadítja a memóriát.
#################################
# Teljes lista törlése és a változó megsemmisítése.
# Ritkán csináljuk: Ha nagyon nagy a lista és kevés a
# memória --> mikor már nem kell, töröljük.
# Egyébként a futtató rendszer úgyis automatikusan felszabadítja
# a memóriát, amikor már egy változó sem mutat az illető elemre.
del(x) # megszüntetjük az x nevet
print(x)
# Traceback (most recent call last):
# File "test.py", line 51, in <module>
# print(x)
# NameError: name 'x' is not defined
# Csak a NÉV szűnik meg a del()-től!!!
x = [1, 2, 3]
y = x
print(y) # [1, 2, 3] y ugyanarra a memóriacímre mutat, mint x
del(x) # megszüntetjük az x nevet
print(y) # [1, 2, 3] y megmaradt
del(y)
print(y) # de most már nincs
# Traceback (most recent call last):
# File "test.py", line 57, in <module>
# print(y)
# NameError: name 'y' is not defined
#################################
|
e23b48fd83d62d7cd6c99b18dcb614edcfa61713 | BercziSandor/pythonCourse_2020_09 | /Num_py/numpy_1.py | 6,404 | 4.1875 | 4 | # numpy tömbök bemutatása
# shape, ndim, dtype, slicing
# https://www.w3schools.com/python/numpy_intro.asp
# https://www.w3schools.com/python/numpy_array_slicing.asp
# https://medium.com/better-programming/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d
# http://jalammar.github.io/visual-numpy/
# https://stackoverflow.com/questions/49751000/how-does-numpy-determine-the-array-data-type-when-it-contains-multiple-dtypes
# https://numpy.org/doc/stable/reference/arrays.dtypes.html
# https://www.geeksforgeeks.org/data-type-object-dtype-numpy-python/
import numpy as np
# Egy dimenziójú tömb (vektor):
arr_1 = np.array([10, 20, 30])
print(arr_1.ndim, arr_1.shape) # 1 (3,)
##################################
# Két dimenziós, egysoros tömb:
arr_1 = np.array([ [10, 20, 30] ])
print(arr_1.ndim, arr_1.shape) # 2 (1, 3)
##################################
# Két dimenziós, egyoszlopos tömb:
arr_1 = np.array([
[10],
[20],
[30]
]
)
# Persze így is írható:
arr_1 = np.array([ [10], [20], [30] ])
print(arr_1.ndim, arr_1.shape) # 2 (3,1)
##################################
# Kétsoros, három oszlopos tömb:
arr_1 = np.array([
[10, 20, 30],
[40, 50, 60]
]
)
# Leírhatjuk így is:
arr_1 = np.array([ [10, 20, 30], [40, 50, 60] ])
print(arr_1.ndim, arr_1.shape) # 2 (2, 3)
##################################
# Adattípusok
# Csupa egész szám van a tömbben:
arr_1 = np.array([10, 20, 30])
print(arr_1.dtype, arr_1.dtype.type) # int32 <class 'numpy.int32'>
##################################
# Sztring is van a tömbben::
arr_1 = np.array([10, 20, '30'])
print(arr_1.dtype, arr_1.dtype.type) # <U11 <class 'numpy.str_'>
# Ez az eset viszonylag gyakran előfordul, pl. fejléces táblázatoknál, vagy
# szövegként beírt számoknál.
# Az U betű azt jelenti, hogy Unicode kódolású sztring, a 11 azt, hogy legfeljebb 11
# karakteres, a < jel azt, hogy little endian (a legkisebb helyiértékű bájt van legelöl).
# Nem tudom, milyen heurisztika szerint számították ki, hogy itt (Windows alatt, ennél a
# numpy verziónál) a méret pont 11 karakter legyen.
# Egy 15 karakteres sztringnél 13 lesz az érték:
arr_1 = np.array([10, 20, '1235678901235'])
print(arr_1.dtype) # <U13
# Nincs nagy jelentősége - a lényeg: ha egyetlen sztring van a tömbben, akkor már az egész
# tömb is sztring típusú lesz; ami azt jelenti, hogy MINDEGYIK eleme sztring típusú:
print(arr_1[0].dtype) # <U2
# ami azt jelenti, hogy numerikus műveletet nem végezhetünk velük:
print(arr_1[0] + 2) # TypeError
# A sztringet az astype() metódussal számmá kell alakítanunk:
print(arr_1[0].astype(int) + 2, arr_1[0].astype(float) + 2) # 2 2.0
##################################
# Általánosabb esetben, egyéb típusoknál:
arr_1 = np.array([10, 20, {3}])
print(arr_1.dtype, arr_1.dtype.type) # object <class 'numpy.object_'>
###########################################
# A slicing ugyanúgy megy, mint az egydimenziós listáknál, az egyes dimenziókhoz
# tartozó kifejezések vesszővel vannak elválasztva. A hiányzó kifejezés itt is a
# default-ot jelenti. Ha egy dimenzióra teljesen hiányzik a kifejezés, akkor
# azon dimenzió szerint az összes elemet kell venni.
arr_1 = np.array([
[10, 20, 30],
[40, 50, 60]
]
)
arr_2 = arr_1[:,:] # teljes másolat: összes sor, összes oszlop
print(arr_2)
# [[10 20 30]
# [40 50 60]]
# Ugyanez másként:
arr_2 = arr_1[:] # összes sor, oszlopokról hallgatunk --> tehát az összes
arr_2 = arr_1[:,] # összes sor, oszlopokról semmit nem specifikálunk --> az összes
##################################
# Az első dimenzió (a sorok) helye nem lehet üres, ez:
arr_2 = arr_1[,1]
# szintaktikai hiba. Itt az ellipsis jelölést használhatjuk:
arr_2 = arr_1[...,1]
print(arr_2) # [20 50]
##################################
# Egy teljes sor kiválasztása többféle módon leírható.
# Egy dimenziós tömbbé alakítva:
print(arr_1[0]) # [10 20 30]
print(arr_1[0,]) # [10 20 30]
print(arr_1[0,:]) # [10 20 30]
print(arr_1[0,::]) # [10 20 30]
# A második változat a legolvashatóbb (bár ez szubjektív). Nekem azért ez tetszik
# legjobban, mert rövid, de látszik belőle, hogy két dimenziós tömbről van szó. Az
# első alakról nem tudjuk eldönteni, hogy egy- vagy kétdimenziós-e a tömb.
# Az, hogy indegyik esetben egy dimenziós tömbként kapjuk meg az eredményt, már a
# fenti kiíratásból is látszik (egyetlen szögletes zárójelpárban vannak az elemek).
print(arr_1[0,].shape) # (3,)
# Egy teljes sor kiválasztása egy soros kétdimenziós tömbként:
print(arr_1[0:1]) # [[10 20 30]]
print(arr_1[0:1,]) # [[10 20 30]]
print(arr_1[0:1,:]) # [[10 20 30]]
print(arr_1[0:1,::]) # [[10 20 30]]
print(arr_1[0:1].shape) # (1, 3)
##################################
# Összes sor, második oszloptól végig:
print(arr_1[:,1:])
# [[20 30]
# [50 60]]
##################################
# A teljes első oszlop egydimenziós tömbbé alakítva:
arr_2 = arr_1[:,0]
print(arr_2, arr_2.shape) # [10 40] (2,)
# Az első oszlop egyoszlopos két dimenziós tömbbé alakítva:
arr_2 = arr_1[:,0:1]
print(arr_2, arr_2.shape)
# [[10]
# [40]] (2, 1)
# Utolsó oszlop egydimenziós tömbbé alakítva:
arr_2 = arr_1[:,-1]
print(arr_2, arr_2.shape) # [30 60] (2,)
# Utolsó oszlop egyoszlopos két dimenziós tömbbé alakítva:
arr_2 = arr_1[:,-1:]
print(arr_2, arr_2.shape)
# [[30]
# [60]] (2, 1)
##################################
# Explicit típuskonverziók
arr_1 = np.array([10, 20, '30'])
arr_2 = arr_1.astype(int)
print(arr_2) # [10 20 30]
arr_1 = np.array([10, 20, 'xyz'])
arr_2 = arr_1.astype(int) # hiba
###########################################
# A slice másik objektum, de AZ EREDETI tömbre mutató referenciákat tartalmaz,
# azaz NEM másolat:
import numpy as np
arr_1 = np.array([1, 2, 3])
arr_2 = arr_1[:]
print(id(arr_1), id(arr_2)) # 7999064 66477016
arr_2[0] = 99
print(arr_1) # [99 2 3]
# A Python list-nél nem így van:
lst_1 = [1, 2, 3]
lst_2 = lst_1[:]
lst_2[0] = 99
print(lst_1) # [1, 2, 3]
# Itt a slice másolat.
##################################
# Ha másolatot akarunk létrehozni a numpy array-nél, akkor a copy() metódust kell meghívni:
arr_1 = np.array([1, 2, 3])
arr_2 = arr_1.copy()
arr_2[0] = 99
print(arr_1) # # [1 2 3]
##################################
|
f4b554f911103a63fd1ef840f986af810967c43a | UmaRathore/Regular_Expressions | /Password_Validation.py | 863 | 3.890625 | 4 | # email and password validation
import re
email_pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
while True:
email_id = input('Enter email address : ')
email_id_object = email_pattern.search(email_id)
if email_id_object is None:
print('Enter correct email address : ')
continue
else:
print('Email registered')
break
# password validation which is at least 8 characters long, has signs @#$% and ends with a number
pwd_pattern = re.compile(r"([a-zA-Z0-9$%#@]{7,}[0-9])")
while True:
pwd = input('Strong Password of at least 8 characters, numbers, @#$%: ')
pwd_object = pwd_pattern.fullmatch(pwd)
if pwd_object is None:
print("Enter correct password of at least 8 characters, numbers, @#$% :")
continue
else:
print("Welcome !!")
break
|
3fd7d0c449585ee03b8a378486025cf49bf098ac | KarolGOli/Praticas_em_Python | /exercicio_4.py | 2,318 | 3.9375 | 4 | from operator import itemgetter
lista = []
cont = 0
int(cont)
def cadastro_produto(produto_para_cadastrar: dict): # função que adiciona o objeto produto à lista
lista.append(produto_para_cadastrar) # o método append faz com que o produto seja adicionado na lista
return
while cont >= 0: # condição para manter em execução o 'menu' escolhas e valores a serem informados
cadastro = int(input('\nCADASTRAR NOVO PRODUTO? (0 - Não 1 - Sim) '))
cont += 1
if cadastro == 1:
new_product = {} # dicionário para armazenar os produtos, enquanto rodar ele vai ser atualizado com um novo produto armazenado
new_product['codigo'] = int(input('INFORME O CÓDIGO DO PRODUTO: '))
if new_product['codigo'] == 0: # condição para verificar se o valor inserido é válido
print('CÓDIGO 0, encerra o cadastro de produtos.')
break
new_product['atual'] = int(input('INFORME O ESTOQUE ATUAL: '))
new_product['minimo'] = int(input('INFORME O ESTOQUE MÍNIMO: '))
if new_product['atual'] < new_product['minimo']: # condição para informar a situação do estoque
print('ESTOQUE ATUAL ABAIXO D0 MÍNIMO INDICADO!')
cadastro_produto(new_product) # chamada da função de cadastro
elif cadastro == 0:
print('\nENCERRANDO CADASTRO DE PRODUTOS...')
break
visualizar = int(input('\nAPRESENTAR TABELA DE PRODUTOS? (2 - Visualizar | 3 - Cancelar) '))
if visualizar == 2 and len(lista) > 0: # se o usuário quiser visualizar a tabela e ela estiver preenchida ele à apresenta
print('TABELA DE PRODUTOS - ORDEM CRESCENTE:')
print("CÓDIGO".center(10), end='') # métodos utilizados para centralização e estruturação da tabela
print("EST. ATUAL".center(15), end='')
print("EST. MÍNIMO".center(18))
# linha de comando responsável por ordenar a lista de forma crescente, usando como referência o item código
for produto in sorted(lista, key=itemgetter('codigo')):
print(str(produto['codigo']).center(10), end='')
print(str(produto['atual']).center(15), end='')
print(str(produto['minimo']).center(18))
elif visualizar == 3:
print('FINALIZANDO...') |
612686443d9cda5b6aa2766a6a90cc997610abf2 | vivek28111992/DailyCoding | /problem_#56_11042019.py | 1,952 | 4.09375 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given an undirected graph represented as an adjacency matrix and an integer k, write a function to determine whether each vertex in the graph can be colored such that no two adjacent vertices share the same color using at most k colors.
https://www.geeksforgeeks.org/m-coloring-problem-backtracking-5/
"""
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
# A utility function to check if the current color assignment is safe for vertex v
def isSafe(self, v, colour, c):
print('v ', v)
print('color ', colour)
print('c ', c)
print('graph ', self.graph)
print('------------------')
for i in range(self.V):
if self.graph[v][i] == 1 and colour[i] == c:
return False
return True
# A recursive utility function to solve m coloring problem
def graphColourUtil(self, noOfColor, colour, v):
if v == self.V:
return True
for c in range(1, noOfColor+1):
if self.isSafe(v, colour, c) == True:
colour[v] = c
if self.graphColourUtil(noOfColor, colour, v+1) == True:
return True
colour[v] = 0
# Main function for graph Coloring
def graphColouring(self, noOfColor):
colour = [0] * self.V
if self.graphColourUtil(noOfColor, colour, 0) == None:
return False
# Print the solution
print("Solution exist and Following are the assigned colours:")
for c in colour:
print(c, end=', ')
return True
if __name__ == '__main__':
g = Graph(4)
g.graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]]
noOfColor = 3
g.graphColouring(noOfColor)
|
39f3c7125d985d4a7d5c494884e16ed2fc27c844 | vivek28111992/DailyCoding | /problem_#98.py | 2,258 | 4.0625 | 4 | """
Given a 2D board of characters and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example, given the following board:
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
exists(board, "ABCCED") returns true, exists(board, "SEE") returns true, exists(board, "ABCB") returns false.
"""
r = 4
c = 4
# Function to check if a word exists in a grid starting from the first match in the grid level: index till which pattern is matched x, y: current position in 2D array
def findMatch(mat, pat, x, y, nrow, ncol, level):
l = len(pat)
# Pattern matched
if level == l:
return True
# out of boundry
if (x < 0 or y < 0) or (x >= nrow or y >= ncol):
return False
# If grid matches with a letter while recursion
if (mat[x][y] == pat[level]):
# Marking this cell as visited
temp = mat[x][y]
mat[x].replace(mat[x][y], "#")
# finding subpattern in 4 directions
res = ((mat, pat, x - 1, y, nrow, ncol, level + 1) or
(mat, pat, x + 1, y, nrow, ncol, level + 1) or
(mat, pat, x, y+1, nrow, ncol, level + 1) or
(mat, pat, x, y-1, nrow, ncol, level + 1))
# marking this cell as unvisited again
return res
else: # Not matching then false
return False
# Function to check if the word exists in the grid or not
def checkMatch(mat, pat, nrow, ncol):
l = len(pat)
# if total characters in matrix is less then pattern lenghth
if (l > nrow * ncol):
return False
# Traverse in the grid
for i in range(nrow):
for j in range(ncol):
# If the first letter matches then recur and check
if mat[i][j] == pat[0]:
if (findMatch(mat, pat, i, j, nrow, ncol, 0)):
return True
return False
if __name__ == "__main__":
grid = ["axmy", "bgdf","xeet", "raks"]
# Function to check if word
# exists or not
if (checkMatch(grid, "geeks", r, c)):
print("Yes")
else:
print("No") |
c9087ee72e96521122ccb48f9995ab7a8e9e1d39 | vivek28111992/DailyCoding | /problem_#26_13032019.py | 1,507 | 3.921875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be smaller than the length of the list.
The list is very long, so making more than one pass is prohibitively expensive.
Do this in constant space and in one pass.
https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/
https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/
"""
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# createNode and make linked list
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def removeNthFromEnd(self, n):
dummy = Node(0)
dummy.next = self.head
first = dummy
second = dummy
# Advances first pointer so that the gap between first and second is n nodes apart
for i in range(n):
first = first.next
# Move first to the end, maintaining the gap
while first.next != None:
first = first.next
second = second.next
second.next = second.next.next
return second.next.data
# Driver Code
llist = LinkedList()
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
print(llist.removeNthFromEnd(2))
|
404bdfdf31e4aa00015b74c58ff37c103f84df8f | vivek28111992/DailyCoding | /problem_#48_03042019.py | 2,435 | 3.921875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given pre-order and in-order traversals of a binary tree, write a function to reconstruct the tree.
For example, given the following preorder traversal:
[a, b, d, e, c, f, g]
And the following inorder traversal:
[d, b, e, a, f, c, g]
You should return the following tree:
a
/ \
b c
/ \ / \
d e f g
https://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
"""
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
Recursive function to construct binary of size len from Inorder traversal in[] and Preorder traversal pre[]. Initialize values of inStrt and inEnd should be 0 and len - 1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree
"""
def buildTree(inOrder, preOrder, inStrt, inEnd):
if(inStrt > inEnd):
return None
# Pinch current node from Preorder traversal using preIndex and increment preIndex
tNode = Node(preOrder[buildTree.preIndex])
buildTree.preIndex += 1
# If this node has no children then return
if inStrt == inEnd:
return tNode
# Else find the index of this node in Inorder traversal
inIndex = search(inOrder, inStrt, inEnd, tNode.data)
# Using index in Inorder Traversal, construct left and right subtrees
tNode.left = buildTree(inOrder, preOrder, inStrt, inIndex-1)
tNode.right = buildTree(inOrder, preOrder, inIndex+1, inEnd)
return tNode
# UTILITY FUNCTIONS
# Function to find index of value in arr[start...end]
# The function assumes that value is present inOrder[]
def search(arr, start, end, value):
for i in range(start, end + 1):
if arr[i] == value:
return i
def printInorder(node):
if node is None:
return
# first recur on left child
printInorder(node.left)
# then print the data of node
print(node.data, end=' ')
# now recur on right child
printInorder(node.right)
inOrder = ['D', 'B', 'E', 'A', 'F', 'C']
preOrder = ['A', 'B', 'D', 'E', 'C', 'F']
# Static variable preIndex
buildTree.preIndex = 0
root = buildTree(inOrder, preOrder, 0, len(inOrder) - 1)
# Let us test the build tree by priting Inorder traversal
printInorder(root)
|
a9169a0606ef75c17087acce0c610bb5aa8e1660 | vivek28111992/DailyCoding | /problem_#99.py | 624 | 4.1875 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
def largestElem(arr):
s = set(arr)
m = 0
for i in range(len(arr)):
if arr[i]+1 in s:
j = arr[i]
m1 = 0
while j in s:
j += 1
m1 += 1
m = max(m, m1)
print(m)
return m
if __name__ == "__main__":
largestElem([100, 4, 200, 1, 3, 2])
|
f96e8a52c38e140ecf3863d1ea138e15b78c7aa8 | vivek28111992/DailyCoding | /problem_#28_15032019.py | 1,687 | 4.125 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified.
More specifically, you should have as many words as possible in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any, distributed starting from the left.
If you can only fit one word on a line, then you should pad the right-hand side with spaces.
Each word is guaranteed not to be longer than k.
For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you should return the following:
["the quick brown", # 1 extra space on the left
"fox jumps over", # 2 extra spaces distributed evenly
"the lazy dog"] # 4 extra spaces distributed evenly
https://leetcode.com/problems/text-justification/discuss/24891/Concise-python-solution-10-lines.
"""
def fulljustify(words, maxWidth):
res, cur, num_of_letters = [], [], 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - num_of_letters):
cur[i%(len(cur)-1 or 1)] += ' '
res.append(''.join(cur))
cur, num_of_letters = [], 0
cur += [w]
num_of_letters += len(w)
return res + [' '.join(cur).ljust(maxWidth)]
words = ["the quick brown",
"fox jumps over",
"the lazy dog"]
print(fulljustify(words, 16))
|
03dc0512b0e47789f95ea5628c4f84f5cfad6b16 | vivek28111992/DailyCoding | /#825.py | 135 | 3.9375 | 4 | # [-9, -2, 0, 2, 3]
def square(arr):
sq_arr = [i * i for i in arr]
sq_arr.sort()
return sq_arr
print(square([-9, -2, 0, 2, 3])) |
370ff8761ac2230627a5b2d37ec47c0141c1339b | vivek28111992/DailyCoding | /problem_#62_17042019.py | 1,060 | 3.96875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down.
For example, given a 2 by 2 matrix, you should return 2, since there are two ways to get to the bottom-right:
Right, then down
Down, then right
Given a 5 by 5 matrix, there are 70 ways to get to the bottom-right.
https://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
https://www.youtube.com/watch?v=GO5QHC_BmvM
"""
def nWays(n, m):
nWaysArr = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m):
if i == 0:
nWaysArr[i][j] = 1
elif j == 0:
nWaysArr[i][j] = 1
else:
nWaysArr[i][j] = nWaysArr[i][j-1] + nWaysArr[i-1][j]
return nWaysArr[n-1][m-1]
if __name__ == '__main__':
print(nWays(3, 3))
|
b19cc3a733b21cb61cf7aaf717e316809ee00220 | vivek28111992/DailyCoding | /problem_#70.py | 619 | 3.96875 | 4 | """
A number is considered perfect if its digits sum up to exactly 10.
Given a positive integer n, return the n-th perfect number
"""
def findNthPerfect(n):
count = 0
curr = 19
while True:
# Find sum of digits in current no.
sum = 0
x = curr
while x > 0:
sum += x % 10
x = int(x/10)
# If sum is 10, we increment count
if sum == 10:
count += 1
# If count becomes n, we return current number
if count == n:
return curr
curr += 9
return -1
# Driver Code
print(findNthPerfect(5))
|
dc0a57534f9f646355c49d9714ebdbfc14ab5adf | vivek28111992/DailyCoding | /problem_#21_08032019.py | 1,236 | 3.765625 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Snapchat.
Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/
"""
from operator import itemgetter
from itertools import chain
def noOfRooms():
data = [(30, 75), (0, 50), (60, 150)]
lectures_start = list(list(zip(*data))[0])
lectures_start.sort()
lectures_end = list(list(zip(*data))[1])
lectures_end.sort()
rooms_req = 0
j = 0
i = 0
max_rooms = 0
n = len(lectures_start)
while i < n and j < n:
if lectures_start[i] < lectures_end[j]:
rooms_req += 1
max_rooms = rooms_req if rooms_req > max_rooms else max_rooms
i += 1
else:
while lectures_end[j] < lectures_start[i]:
rooms_req -= 1
j += 1
print(max_rooms)
# data = list(chain.from_iterable(data))
#
# print(data)
# data = sorted(data, key=itemgetter(0))
# print(data)
noOfRooms()
|
cbb259086c41bdc29d9569b3c4cecebfc355bad9 | vivek28111992/DailyCoding | /problem_#101.py | 1,336 | 4.03125 | 4 | """
Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number.
A solution will always exist. See Goldbach’s conjecture.
Example:
Input: 4
Output: 2 + 2 = 4
If there are more than one solution possible, return the lexicographically smaller solution.
If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, then
[a, b] < [c, d]
If a < c OR a==c AND b < d.
"""
def sieveOfEratosthenes(n, isPrime):
# Initialize all entries of boolean array as True. A value in isPrime[i] will finally be False if i is not a Prime, else Ture bool isPrime[n+1]
isPrime[0] = isPrime[1] = False
for i in range(2, n+1):
isPrime[i] = True
p = 2
while p*p <= n:
# If isPrime[p] is not changed, then it is a Prime
if (isPrime[p] == True):
# Update all multiples of p
i = p * p
while i <= n:
isPrime[i] = False
i += p
p += 1
def findPrimePair(n):
# Generating primes using Sieve
isPrime = [0] * (n+1)
sieveOfEratosthenes(n, isPrime)
# Traversing all numbers to find first pair
for i in range(n):
if (isPrime[i] and isPrime[n-i]):
return (i, (n-i))
if __name__ == "__main__":
n = 74
print(findPrimePair(n))
|
f6a83bb9d12fae8b81bd522dfec9fcb93952e5a9 | vivek28111992/DailyCoding | /problem_#93.py | 1,887 | 4 | 4 | """
Given a tree, find the largest tree/subtree that is a BST.
Given a tree, return the size of the largest tree/subtree that is a BST.
"""
INT_MIN = -2147483648
INT_MAX = 2147483647
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.
class newNode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Returns Information about subtree. The
# Information also includes size of largest
# subtree which is a BST
def largestBSTBT(root):
# Base cases : When tree is empty or it has
# one child.
if root == None:
return 0, INT_MIN, INT_MAX, 0, True
if root.left == None and root.right == None:
return 1, root.data, root.data, 1, True
# Recur for left subtree and right subtree
l = largestBSTBT(root.left)
r = largestBSTBT(root.right)
# Create a return variable and initialize its
# size.
ret = [0, 0, 0, 0, 0]
ret[0] = (1 + l[0] + r[0])
# If whole tree rooted under current root is
# BST.
if (l[4] and r[4] and l[1] <
root.data and r[2] > root.data):
ret[2] = min(l[2], min(r[2], root.data))
ret[1] = max(r[1], max(l[1], root.data))
# Update answer for tree rooted under
# current 'root'
ret[3] = ret[0]
ret[4] = True
return ret
# If whole tree is not BST, return maximum
# of left and right subtrees
ret[3] = max(l[3], r[3])
ret[4] = False
return ret
if __name__ == '__main__':
"""Let us construct the following Tree
60
/ \
65 70
/
50 """
root = newNode(60)
root.left = newNode(65)
root.right = newNode(70)
root.left.left = newNode(50)
print("Size of the largest BST is",
largestBSTBT(root)[3])
|
4277764dd9fe0ae8877436cd014f4b52e900dfa9 | vivek28111992/DailyCoding | /problem_#14_01032019.py | 846 | 3.984375 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x2 + y2 = r2.
https://www.geeksforgeeks.org/estimating-value-pi-using-monte-carlo/
"""
import random
def pi(interval):
circle_points = 0
square_points = 0
i = 0
while i < (interval*interval):
x = float(random.randint(0, interval) % (interval+1)) / interval
y = float(random.randint(0, interval) % (interval+1)) / interval
d = x*x + y*y
if d <= 1:
circle_points += 1
square_points += 1
est_pi = float(4 * circle_points) / square_points
i += 1
return est_pi
if __name__ == '__main__':
print(pi(100))
|
140a539e327bd9608796fb12d68d343b4f1a18a8 | acneuromancer/problem_solving_python | /graphs_2/word_ladder.py | 1,313 | 3.53125 | 4 | from collections import defaultdict
from collections import deque
from itertools import product
# import os
def build_graph(words):
buckets = defaultdict(list)
graph = defaultdict(set)
for word in words:
for i in range(len(word)):
bucket = '{}_{}'.format(word[:i], word[i+1:])
buckets[bucket].append(word)
for bucket, mutual_neighbours in buckets.items():
for word1, word2 in product(mutual_neighbours, repeat = 2):
if word1 != word2:
graph[word1].add(word2)
graph[word2].add(word1)
return graph
def get_words(vocabulary_file):
with open(vocabulary_file, 'r') as words_file:
for line in words_file:
yield line[:-1]
def traverse(graph, starting_vertex):
visited = set()
queue = deque([[starting_vertex]])
while(queue):
path = queue.popleft()
vertex = path[-1]
yield vertex, path
for neighbour in graph[vertex] - visited:
visited.add(neighbour)
queue.append(path + [neighbour])
word_graph = build_graph(get_words('words_shorter.txt'))
for k, v in word_graph.items():
print('{} -> {}'.format(k, v))
for vertex, path in traverse(word_graph, 'fool'):
if vertex == 'sage':
print(' -> '.join(path)) |
8a07b97ab69c6716d99564830d3625a9fa9ca17c | acneuromancer/problem_solving_python | /trees/binary_tree/bin_tree_parser.py | 3,545 | 3.984375 | 4 | class BinaryTree:
def __init__(self, root):
self.key = root
self.left_child = None
self.right_child = None
def insert_left(self, new_node):
if self.left_child == None:
self.left_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.left_child = self.left_child
self.left_child = t
def insert_right(self, new_node):
if self.right_child == None:
self.right_child = BinaryTree(new_node)
else:
t = BinaryTree(new_node)
t.right_child = self.right_child
self.right_child = t
def get_right_child(self):
return self.right_child
def get_left_child(self):
return self.left_child
def set_root_val(self, obj):
self.key = obj
def get_root_val(self):
return self.key
def preorder(self):
print(self.key)
if self.left_child:
self.left_child.preorder()
if self.right_child:
self.right_child.preorder()
def postorder(self):
if self.left_child:
self.left_child.postorder()
if self.right_child:
self.right_child.postorder()
print(self.key)
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
'''
1. If the current token is a ‘(’, add a new node as the left child of the current node, and
descend to the left child.
2. If the current token is in the list [‘+’,‘−’,‘/’,‘*’], set the root value of the current node to
the operator represented by the current token. Add a new node as the right child of the
current node and descend to the right child.
3. If the current token is a number, set the root value of the current node to the number and
return to the parent.
4. If the current token is a ‘)’, go to the parent of the current node.
'''
def build_parse_tree(fp_exp):
fp_list = fp_exp.split()
p_stack = Stack()
e_tree = BinaryTree('')
p_stack.push(e_tree)
current_tree = e_tree
for i in fp_list:
if i == '(':
current_tree.insert_left('')
p_stack.push(current_tree)
current_tree = current_tree.get_left_child()
elif i not in ['+', '-', '*', '/', ')']:
current_tree.set_root_val(int(i))
parent = p_stack.pop()
current_tree = parent
elif i in ['+', '-', '*', '/']:
current_tree.set_root_val(i)
current_tree.insert_right('')
p_stack.push(current_tree)
current_tree = current_tree.get_right_child()
elif i == ')':
current_tree = p_stack.pop()
else:
raise ValueError
return e_tree
import operator
def evaluate(parse_tree):
opers = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv
}
left = parse_tree.get_left_child()
right = parse_tree.get_right_child()
if left and right:
fn = opers[parse_tree.get_root_val()]
return fn(evaluate(left), evaluate(right))
else:
return parse_tree.get_root_val()
pt = build_parse_tree("( ( 10 + 5 ) * 3 )")
pt.postorder()
print(evaluate(pt))
|
e23bb077affd2781fd36113b03fe55755ae16b9f | acneuromancer/problem_solving_python | /basic_data_structures/queue/queue_test.py | 200 | 3.890625 | 4 | from Queue import Queue
q = Queue()
q.enqueue('hello')
q.enqueue('dog')
q.enqueue(3)
print("Size of the queue is %d." % q.size())
while not q.is_empty():
print(q.dequeue(), end = " ")
print()
|
9914dde414bc7ad3df7543e58d0e478ecef3b013 | acneuromancer/problem_solving_python | /python_basics/list_comprehension.py | 621 | 3.9375 | 4 | def practice_1():
sq_list = [x * x for x in range(1, 11)]
print(sq_list)
sq_list = [x * x for x in range(1, 11) if x % 2 != 0]
print(sq_list)
ch_list = [ch.upper() for ch in "Hello World!" if ch not in 'aeiou']
print(ch_list)
def method_1():
word_list = ['cat', 'dog', 'rabbit']
letter_list = []
for word in word_list:
for ch in word:
letter_list.append(ch)
print(letter_list)
def method_2():
word_list = ['cat', 'dog', 'rabbit']
ch_list = []
[ch_list.append(ch) for word in word_list for ch in word if ch not in ch_list]
print(ch_list)
|
bf7c8573149487a85dbcb6e971ccee8afc0b5e76 | acneuromancer/problem_solving_python | /recursion/reverse_string.py | 346 | 3.96875 | 4 | def reverse_str(str):
if len(str) == 1:
return str[0]
last = len(str) - 1
return str[last] + reverse_str(str[0:last])
def reverse_str_2(str):
if str == "":
return str
return reverse_str_2(str[1:]) + str[0]
print(reverse_str_2("Hello World!"))
print(reverse_str_2("abcdefgh"))
print(reverse_str_2("xyz"))
|
152e728c543b491be4f8b0135ace70778fc6734a | runt1m33rr0r/python_homeworks | /homework_2/F87134_L3_T2.py | 668 | 3.671875 | 4 | import sys
import string
input = sys.argv[1:]
text = input[0].strip().upper().translate(string.maketrans('', ''), string.punctuation)
key = input[1].strip().upper().translate(string.maketrans('', ''), string.punctuation)
# extend the key
initial_len = len(key)
current_letter = 0;
while len(key) < len(text):
key += key[current_letter]
current_letter = (current_letter + 1) % initial_len
# encode the text
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = []
for text_let, key_let in zip(text, key):
key = alphabet.index(key_let)
encoded = alphabet[(alphabet.index(text_let) + key) % len(alphabet)]
result.append(encoded)
print ''.join(result)
|
7e9b02feb9177e628d4774559beb4104a0c240de | runt1m33rr0r/python_homeworks | /homework_1/F87134_L2_T1.py | 164 | 3.78125 | 4 | import sys
input = sys.argv[1:]
for i in range(len(input) - 1):
if input[i] > input[i + 1]:
print("unsorted")
break
else:
print("sorted")
|
91d0c13f973959afb4d736ea75bed6043e5d0fec | Brucehanyf/python_tutorial | /base/param.py | 888 | 4.03125 | 4 | # 参数相关语法
def param (param="123456"):
print("123123")
# 函数的收集参数和分配参数用法(‘*’ 和 ‘**’)
# arg传递的是实参, kvargs传递的是带key值的参数
# 函数参数带*的话,将会收集非关键字的参数到一个元组中;
# 函数参数带**的话,将会收集关键字参数到一个字典中;
# 参数arg、*args、必须位于**kwargs之前
# 指定参数不会分配和收集参数
def param_check(*args,value = 'param', **kvargs):
print(value)
print(args)
print("args--------start")
for arg in args:
print(arg)
print("args--------end")
print(kvargs)
print("kvargs--------start")
for k, v in kvargs.items():
print("key: " + str(k) + " value:" + str(v))
print("kvargs--------end")
# **参数需要指定key值
param_check(1, 2, 3,value="1024",k=5,v=6,a=7,b=8)
|
f2ddc408fe7ca9f5fc5da16dcdca4a83fbce9c54 | Brucehanyf/python_tutorial | /base/day01.py | 1,041 | 3.78125 | 4 | ### 字符串相关语法
print('hello,world')
message = "hello,message"
print(message)
message = "hello world"
print(message)
# 变量名不能以数字开头, 中间不能包含空格,其中可以包含下划线
# 字符串字母首字母大写 字符串大写 字符串小写
name = "hello bruce"
print(name.title())
print(name.upper())
print(name.lower())
# 合并字符串
first_name = "Bruce"
last_name = "Han"
full_name = first_name + " " + last_name
print(full_name.title()+"!")
# 使用制表符或者换行符来添加空白
# 制表符 \t 换行符 \n
print("language java \n\tpython js ")
# 删除空白
# rstrip() 删除右侧空格
# lstrip() 删除左侧空格
# strip() 删除两侧空格
favorite_language = " python "
print(favorite_language)
favorite_language = favorite_language.rstrip()
print(favorite_language)
favorite_language = favorite_language.lstrip()
print(favorite_language)
# 使用str() 避免类型错误
age = 23
message = "hello Bruce "+ str(age) + "rd birthday!";
print(message)
|
9ab9305ebf7869b1b9576730ec40163260cd0e12 | Brucehanyf/python_tutorial | /api/a_zip.py | 672 | 3.890625 | 4 | # zip函数
# zip() 函数用于将可迭代的对象作为参数,
# 将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,
# 这样做的好处是节约了不少的内存。
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,9]
zipped = zip(c,a)
# print(list(zipped))
# 之后取出最小集配对
# 解压
# a1, a2 = zip(*zip(a,b))
a1, a2 = zip(*zipped)
print(a1)
print(a2)
from itertools import groupby
# 测试无用变量 y_list = [v for _, v in y]
map = []
for x,y in groupby(sorted(zip(c,a),key=lambda _:_[0])):
list = [v for _,v in y]
print(x,list)
map.append([x,sum(list)/len(list)])
z1, z2 = zip(*map)
print(z1, z2) |
c80b26a41d86ec4f2f702aab0922b86eec368e84 | Brucehanyf/python_tutorial | /file_and_exception/file_reader.py | 917 | 4.15625 | 4 | # 读取圆周率
# 读取整个文件
# with open('pi_digits.txt') as file_object:
# contents = file_object.read()
# print(contents)
# file_path = 'pi_digits.txt';
# \f要转义
# 按行读取
file_path = "D:\PycharmProjects\practise\\file_and_exception\pi_digits.txt";
# with open(file_path) as file_object:
# for line in file_object:
# print(line)
# file_object.readlines()
# with open(file_path) as file_object:
# lines = file_object.readlines()
# for line in lines:
# print(line)
# 使用文件中的内容
with open(file_path) as file_object:
lines = file_object.readlines()
result = '';
for line in lines:
result += line.strip()
print(result)
print(result[:10]+'......')
print(len(result))
birthday = input('请输入您的生日')
if birthday in result:
print("your birthday appears in pai digits")
else:
print("your birthday does not appears in pai digits")
|
7642b6f57230a3f436cb3bec38286f227b7df9a2 | moscowjh/fullstack-nanodegree-vm | /vagrant/tournament/tester.py | 2,436 | 3.671875 | 4 | from tournament import *
def test():
"""Test various functions of tournament project
Most particularly, playerStandings may be tested along with BYE insertion
and deletion prior to match results. Also allows clearing of players and/or
matches, and registration of players.
"""
print ""
print "s -- player standings"
print "p -- to register players"
print "c -- clear players *note* Players cannot be cleared if they have \
matches."
print "m to clear matches *note* Clearing matches will not clear players."
print "bye -- delete bye"
print "Press any other key to exit"
print ""
answer = raw_input("What would you like to do? \n")
if answer == "s":
standings = playerStandings()
current = countPlayers()
print ""
print standings
print ""
print "Current number of players:"
print current
test()
elif answer == "p":
print ""
number = countPlayers()
print "Current Players:"
print number
print ""
player = raw_input("Enter a new Player's name: \n")
registerPlayer(player)
number2 = countPlayers()
print "New current players:"
print number2
print ""
test()
elif answer == "m":
print ""
print "WARNING:"
print "THIS WILL DELETE ALL MATCHES!"
print ""
player = raw_input("Are you sure? [ y or n] \n")
if player == "y":
deleteMatches()
num = countPlayers()
print ""
print "Current players:"
print num
print ""
test()
else:
print ""
print "Okay... Going back..."
print ""
test()
elif answer == "c":
print ""
print "WARNING:"
print "THIS WILL DELETE ALL PLAYERS!"
print ""
player = raw_input("Are you sure? [ y or n] \n")
if player == "y":
deletePlayers()
num = countPlayers()
print ""
print "Current players:"
print num
print ""
test()
else:
print ""
print "Okay... Going back..."
print ""
test()
elif answer == "bye":
deleteByes()
test()
else:
end
if __name__ == '__main__':
test()
|
7bef62a6cee86d61bc1bd5323e7d8c47bbc7f8ae | ardus-uk/anagrams | /anagram2.py | 573 | 3.78125 | 4 | #!/usr/bin/python3
def unique(listx):
listy=[]
for x in listx:
if x not in listy:
listy.append(x)
return listy
with open('./wordsEn.txt') as f:
lines = f.readlines() # lines is a list of words
word = 'refined'
letters = list(word) # letters is a list of the letters
unique_letters = unique(letters)
n = len(letters)
cands = [elem for elem in lines if (len(elem)==n+1)]
i=0
for letter in unique_letters:
num = letters.count(letter)
cands = [elem for elem in cands if (letter in elem) and elem.count(letter) == num]
for cand in cands:
print (cand)
|
6669d87b8795e1d8b062f2b25ca4eeea00ecc79f | thekevinsmith/project_euler_python | /9/special_pythagorean_triplet.py | 1,238 | 4.0625 | 4 | # Problem 9 : Statement : Special Pythagorean triplet
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a**2 + b**2 = c**2
# For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
# Some math and the thinking process:
# must: a**2 + b**2 = c**2 TRUE
# and a + b + c = 1000 TRUE
# find a*b*c = ? QUESTION
# #variables and 2 true statements
# (a**2 + b**2)**(-1) = c
# 1000 - a - b = c
# 1000 - a - b = (a**2 + b**2)**(-1)
# (1000 - a - b)**2 = a**2 + b**2
# (1000 - a - b)*(1000 - a - b) = a**2 + b**2
# 1000*1000 -1000a -1000b -1000a +a**2 ab -1000b +ab + b**2 = a**2 + b**2
# 1 000 000 - 2000a -2000b = 0
# 500 - a = b -> this is replaced in another formulae
# code:
# for a
# for b
# 1000 - a - b = c
# if c > 0
# if c*c = b*b + a*a
# if a < b
def main():
output = 0
for a in range(1,1000):
for b in range(1,1000):
c = 1000 - a - b
if c > 0:
if c*c == (b*b + a*a):
if a < b:
output = a*b*c
print(a, b, c)
print(output)
if __name__ == '__main__':
main() |
62bd9b81b6ace8f9bab84fb293710c50ca0bcf29 | thekevinsmith/project_euler_python | /4/largest_palindrome_product.py | 1,778 | 4.125 | 4 | # Problem 4 : Statement:
# A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def main():
largest = 0
for i in range(0, 1000, 1):
count = 0
Num = i
while Num > 0:
Num = Num//10
count += 1
if count == 3:
prodNum.append(i)
for p in range(len(prodNum)):
for n in range(len(prodNum)):
result = prodNum[p] * prodNum[n]
test = result
count = 0
while test > 0:
test = test // 10
count += 1
if count == 6:
sixNum.append(result)
if (result // 10 ** 5 % 10) == (result // 10 ** 0 % 10):
if (result // 10 ** 4 % 10) == (result // 10 ** 1 % 10):
if (result // 10 ** 3 % 10) == (result // 10 ** 2 % 10):
palindromeNum.append(result) # all that fit criteria
if result > largest:
largest = result
print("Largest palindromic: %d" % largest)
if __name__ == '__main__':
palindromeNum = []
prodNum = []
sixNum = []
main()
# Dynamic attempt: Technically its possible but very difficult as we need to
# consider set points if a for or while is used to do verification
# Think on this...
# largest = 0
# count = 6
# result = 994009
# for c in range(0, count // 2, 1):
# if (result // 10 ** (count - 1 - c) % 10) == (result // 10 ** (c) % 10):
# if result > largest:
# largest = result
# print(result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.