blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
0a59e34aebbfa91a9234994b98f3b9674b1ab7b5 | TedYav/CodingChallenges | /leetcode/word_break_2.py | 7,887 | 3.859375 | 4 | """
Word Break II:
Given non-empty string s and non-empty non-empty word containing dictionary d, return all possible sentences formable from s.
Solutions:
Brute Force: try all possible combinations of spaces. O(2^n) to try all possible combinations. Could take O(n) to verify each, so this is O(n2^n) SLOW.
Better: use dynamic programming and prefix tries.
Let f(i) be all possible sentences I can from from s starting at letter i.
Answer to the problem is f(0)
let w(i) be all words I can form starting at letter i in s.
f(i) = [] if w(i) == []
[""] if i == len(s)
[w_i + all sentences in f(i+len(w_i)) for all w_i in w(i)] otherwise
can solve forwards or backwards.
forwards will be recursive and may result in lots of extra work.
backwards is our better bet. We will store all possibilities at each step.
STRATEGY:
* Convert wordDict into prefix trie
* Create list of possible sentences for i = 0 to len(s) - 1 containing empty list at each index
* Iterate backwards from n-1 to 0
* Check how many words we can form at letter i using prefix trie, for each of them, compound with other sentences in table
* Return list_of_sentences[0]
"""
class TrieNode(object):
def __init__(self,letter="",prefix=""):
self.children = {}
self.letter = letter
self.prefix = prefix + self.letter
self.complete_word = False
def add_child(self,letter):
if letter not in self.children:
self.children[letter] = TrieNode(letter,self.prefix)
"""
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
"""
class PrefixTrie(object):
def __init__(self,word_list):
"""
:type word_list: List[str]
:rtype: PrefixTrie
"""
self.word_list = word_list
self._root = TrieNode()
self.__build_trie()
def __build_trie(self):
for word in self.word_list:
self.add_word(word)
def add_word(self,word):
node = self._root
for c in word:
node.add_child(c)
node = node.children[c]
node.complete_word = True
def possible_words_at_index(self,s,i):
"""
:type s: str
:type i: int
:type word_trie: PrefixTrie
:rtype: List[str]
"""
words = []
node = self._root
while i < len(s) and s[i] in node.children:
node = node.children[s[i]]
if node.complete_word:
words.append(node.prefix)
i += 1
return words
def make_sentences(start_index,word,possible_sentences):
if start_index + len(word) == len(possible_sentences):
return [[word]]
else:
return [[word] + sentence for sentence in possible_sentences[start_index + len(word)]]
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
word_trie = PrefixTrie(wordDict)
possible_sentences = [[] for i in range(len(s))]
for i in range(len(s)-1,-1,-1):
possible_words = word_trie.possible_words_at_index(s,i)
for word in possible_words:
possible_sentences[i].extend(make_sentences(i,word,possible_sentences))
return [" ".join(sentence) for sentence in possible_sentences[0]]
"""
Word Break II:
Given non-empty string s and non-empty non-empty word containing dictionary d, return all possible sentences formable from s.
Solutions:
Brute Force: try all possible combinations of spaces. O(2^n) to try all possible combinations. Could take O(n) to verify each, so this is O(n2^n) SLOW.
Better: use dynamic programming and prefix tries.
Let f(i) be all possible sentences I can from from s starting at letter i.
Answer to the problem is f(0)
let w(i) be all words I can form starting at letter i in s.
f(i) = [] if w(i) == []
[""] if i == len(s)
[w_i + all sentences in f(i+len(w_i)) for all w_i in w(i)] otherwise
can solve forwards or backwards.
forwards will be recursive and may result in lots of extra work.
backwards is our better bet. We will store all possibilities at each step.
STRATEGY:
* Convert wordDict into prefix trie
* Create list of possible sentences for i = 0 to len(s) - 1 containing empty list at each index
* Iterate backwards from n-1 to 0
* Check how many words we can form at letter i using prefix trie, for each of them, compound with other sentences in table
* Return list_of_sentences[0]
"""
class TrieNode(object):
def __init__(self,letter="",prefix=""):
self.children = {}
self.letter = letter
self.prefix = prefix + self.letter
self.complete_word = False
def add_child(self,letter):
if letter not in self.children:
self.children[letter] = TrieNode(letter,self.prefix)
"""
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
"""
class PrefixTrie(object):
def __init__(self,word_list):
"""
:type word_list: List[str]
:rtype: PrefixTrie
"""
self.word_list = word_list
self._root = TrieNode()
self.__build_trie()
def __build_trie(self):
for word in self.word_list:
self.add_word(word)
def add_word(self,word):
node = self._root
for c in word:
node.add_child(c)
node = node.children[c]
node.complete_word = True
def possible_words_at_index(self,s,i):
"""
:type s: str
:type i: int
:type word_trie: PrefixTrie
:rtype: List[str]
"""
words = []
node = self._root
while i < len(s) and s[i] in node.children:
node = node.children[s[i]]
if node.complete_word:
words.append(node.prefix)
i += 1
return words
def make_sentences(start_index,word,possible_sentences):
if start_index + len(word) == len(possible_sentences):
return [[word]]
else:
return [[word] + sentence for sentence in possible_sentences[start_index + len(word)]]
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
word_trie = PrefixTrie(wordDict)
possible_sentences = [[] for i in range(len(s))]
for i in range(len(s)-1,-1,-1):
print(i)
possible_words = word_trie.possible_words_at_index(s,i)
for word in possible_words:
possible_sentences[i].extend(make_sentences(i,word,possible_sentences))
return [" ".join(sentence) for sentence in possible_sentences[0]]
# import timeit.timeit
def test_word_break():
sut = Solution()
# solution breaks because we're assembling sentences too early
# first we need to check IF we can MAKE any sentences :)
s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
words = ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
result = sut.wordBreak(s,words)
print(result)
test_word_break()
|
b71c6a4a8425bcb64d0ccad9825f1b98091ed62a | brittainhard/py | /cookbook/data_structures/chainmaps.py | 824 | 4.0625 | 4 | from collections import ChainMap
"""
If you delete an item from a dictionary, it always deletes it from the latest
dictionary.
This will make those dictionaries incongruent.
"""
a = {"x": 1, "z": 3}
b = {"y": 2, "z": 4}
c = ChainMap(a, b)
del c["z"]
print(c)
"""
Scoped variables?
Lets you keep a dict that has a chain of variables, kind of like a stack.
"""
values = ChainMap()
values["x"] = 1
values = values.new_child()
values["x"] = 2
values = values.new_child()
values["x"] = 3
print(values["x"])
print(values)
print(values.parents["x"])
print(values.parents)
print(values.parents.parents["x"])
print(values.parents.parents)
"""
If you use dictionary update to combine multiple dictionaries, it creates a new
copy. With chainmap you can keep copies of all the dictionaries.
"""
d = dict(b)
d.update(a)
print(d)
|
3227ad6dac7ba4551b9a3180cfb3e7c03be1f58f | AmigaTi/Python3Learning | /interface/ui-tkinter-widgets/tkinter-spinbox.py | 943 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from tkinter import *
# Spinbox
root = Tk() # 初始化TK()
root.title('Tkinter - Spinbox') # 设置窗口标题
root.geometry('300x200') # 设置窗口大小
root.resizable(width=False, height=True) # 设置窗口的长宽是否可变
Spinbox(root,
from_=0, # 最大值
to=100, # 最小值
increment=5 # 步进值
).grid(row=0, column=0, padx=5, pady=5)
# 使用values属性来指定步进值序列
# 使用command属性来指定回调函数
def get_spin_value():
print("current value of spin: ", sp.get())
sp = Spinbox(root,
values=(0, 2, 3, 5, 7, 11, 13, 17), # 更次更新使用values指定的值
command=get_spin_value) # 回调函数
sp.grid(row=0, column=1, padx=5, pady=5)
root.mainloop() # 进入消息循环
|
3fa4549d4fd5b3c29823d6cbf510fa8a95df79a9 | CateGitau/Python_programming | /LeetCode/top_interview_questions/MaximumDepthBinaryTree.py | 942 | 4.1875 | 4 | '''
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path
from the root node down to the farthest leaf node.
'''
#Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxDepth(root):
"""
:type root: TreeNode
:rtype: int
"""
depth = 0
level = [root] if root else []
while level:
depth +=1
queue = []
for el in level:
if el.left:
queue.append(el.left)
if el.right:
queue.append(el.right)
level = queue
return depth
root = TreeNode(1)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print ("Height of tree is %d" %(maxDepth(root))) |
837f52385ba68a21474c0e30f72c6f3a135834df | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/mphkam003/boxes.py | 756 | 4 | 4 | def print_square():
print("*****")
print("* *")
print("* *")
print("* *")
print("*****")
def print_rectangle(width, height):
print("*"*width)
for i in range(height-2):
print("*"+" "*(width-2)+"*")
print("*"*width)
k=0
def get_rectangle(width, height):
x= "*"*width + "\n"
y=""
for i in range(height-2):
k= "*"+" "*(width-2)+"*"
y+=k + "\n"
z=x+y+x
return z
#if name =="__main__":
#choice= input("Choose test:\n")
#if choice=="a":
#print_square()
#elif choice== b and width and height :
#print_rectangle(width,height)
#elif choice == c and width and height:
#get_rectangle(width,height)
|
d28c340712b09038f390803949c8cb4474238263 | GrigoriyPL/10.04.21 | /13.03.2021(3).py | 218 | 3.921875 | 4 | x = int(input('x = '))
y = int(input('y = '))
def xyz():
z=0
if y>0:
if x > 0: z = "I"
else: z = "II"
else:
if x < 0: z = "III"
else: z = "IV"
print(z)
xyz()
|
245318b875d16486271e0449582613926afd021d | kemar1997/Python_Tutorials | /Challenge1.py | 241 | 3.9375 | 4 | """
Creating a for loop that loops through zero to one hundred and only prints a multiple of 4
until it reaches to 100.
"""
for x in range(4, 101, 4):
print(x)
if 100 < x:
print("Whoa you have exceeded your normal capacity.") |
4b020de7ef67b58b38868881e7b0285e206c5151 | Syuanbo/code_collection | /code/FindStrinFile | 1,759 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os
import chardet
ftype =['.txt', '.html', '.php'] #要查找包含字符的文件后缀
def findstr(dirname, fstr):
for filenames in os.listdir(dirname):
filenames = os.path.join(dirname, filenames)
if os.path.splitext(filenames)[1] in ftype: #找到要处理后缀的文件
with open(filenames, 'rb') as f: #判断文件编码方式
buf = f.read()
result = chardet.detect(buf)
try:
with open(filenames, 'r', encoding=result["encoding"]) as f:#查找字符串
str1 = f.read()
if fstr in str1:
print('找到要查找的文件',filenames)
input('找到要查找的文件了还要继续吗?')
#else:
# print(filenames)
except:
print('文件打开出错,可能是编码问题',result["encoding"],filenames)
elif os.path.isdir(filenames): #目录文件继续递归
#print(filenames)
findstr(filenames, fstr)
if __name__ == '__main__':
dirname = input('输入文件名:')
fstr = str(input('输入要查找的字符串:'))
findstr(dirname, fstr)
print('全部文件查找完毕')
'''
---------------------
作者:hello怡红公子
来源:CSDN
原文:https://blog.csdn.net/hello_world2008/article/details/77478364
'''
|
e332d5c39195ae966ade0c65b72de501ff088625 | jpmcb/interview-problems | /ctci/2_4.py | 848 | 4.03125 | 4 | # Partition
from LinkedList import LinkedList
def make_partition(llist, val):
# generate two linked lists around the partition
llist_a = LinkedList()
llist_b = LinkedList()
node = llist.head
while(node != None):
if node.data < val:
llist_a.add(node.data)
else:
llist_b.add(node.data)
node = node.next
# Merge the linked lists around the partition
llist_final = LinkedList()
node = llist_a.head
while(node != None):
llist_final.add(node.data)
node = node.next
node = llist_b.head
while(node != None):
llist_final.add(node.data)
node = node.next
return llist_final
ll = LinkedList()
print("\nTesting partition\n")
ll.generate(10, 0, 9)
print(ll)
returned = make_partition(ll, 5)
print("Result:")
print(returned) |
a2bfc0fd5dec69dcc25815040039bb8aedd70093 | DenizenB/advent-of-code | /2019/2a.py | 1,108 | 3.828125 | 4 | class Computer:
def __init__(self, memory):
self.pc = 0
self.memory = memory
def execute(self):
while self.pc >= 0 and self.pc < len(self.memory):
self.step()
return self.memory[0]
def step(self):
op = self.memory[self.pc]
if op is 99:
self.pc = -1
elif op is 1:
self.put(3, self.get(1) + self.get(2))
self.pc += 4
elif op is 2:
self.put(3, self.get(1) * self.get(2))
self.pc += 4
else:
print("Unknown op: {}".format(op))
self.pc = -1
def get(self, offset):
pointer = self.memory[self.pc + offset]
return self.memory[pointer]
def put(self, offset, value):
pointer = self.memory[self.pc + offset]
self.memory[pointer] = value
def main():
with open("2.txt") as f:
memory = f.read().split(",")
memory = list(map(int, memory))
memory[1] = 12
memory[2] = 2
output = Computer(memory).execute()
print("Computation: {}".format(output))
main() |
016e2bc6e020899bb307877c28d95a74eff5bfff | omgimanerd/trump-clinton-analyzer | /analyze.py | 1,303 | 3.53125 | 4 | #!/usr/bin/python
from collections import defaultdict
import json
import re
def aggregate(filename):
with open(filename) as f:
return " ".join(json.load(f))
def get_stopwords():
with open('data/stopwords.txt') as f:
return f.read().strip().split('\n')
def word_frequency(string):
string = re.sub('[^\w \']', ' ', string)
string = re.sub('\s+', ' ', string)
string = string.lower().split(' ')
stopwords = get_stopwords()
words = defaultdict(int)
for word in string:
if word not in stopwords:
words[word] += 1
return {
'total_words': len(string),
'frequencies': words,
'sorted_words': sorted(words, key=words.get)[::-1]
}
if __name__ == '__main__':
clinton = word_frequency(aggregate('clinton.json'))
clinton_freq = clinton['frequencies']
trump = word_frequency(aggregate('trump.json'))
trump_freq = trump['frequencies']
print("Trump's 35 most used words:")
for word in trump['sorted_words'][:35]:
print("{} {}".format(word, trump_freq[word]))
print("Clinton's 35 most used words:")
for word in clinton['sorted_words'][:35]:
print("{} {}".format(word, clinton_freq[word]))
print(len(trump['sorted_words']))
print(len(clinton['sorted_words']))
|
5525e6f9f6d733d70fdc2da8f0083c0987258bd2 | bexshinderman/DSMI_Code | /Code/hello.py | 6,974 | 4 | 4 | import random #libraries
import time
print("Hello World!")
print("*****************************************")
print("****************user input********************")
userName = input("What is your name?") #Python 3.X or later
print("hello " + userName)
counter = 3 # An integer assignment
weight = 80.5 # A floating point
name = "David" # A string
temperatures = [18, 15, 20, 22, 17] # A list
print("*****************************************")
print("****************dctionariesi********************")
grades = {'peter': 79, 'john': 84, 'scott': 92} # A dictionary of key value pairs
print("peters grade is" + str(grades['peter'])) # Prints value for 'peter' key - wrap in up in a str
print(grades)
print("*****************************************")
print("************random numbers***************")
random.seed(time.time()) # "this needs to be called before any other random functions"
randomnum = random.choice([5,2,3,0])
print(randomnum)
print(randomnum)
print(randomnum)
print(random.choice([5,2,3,0]))
print(random.choice([5,2,3,0]))
print(random.choice([5,2,3,0]))
print("*****************************************")
print("****************lists********************")
list = [1,2,3,4,5];
random.shuffle(list)
print("Reshuffled list : ", list)
list = [ 'old', 786 , 2.23, 'john', 70.2 ]
tinylist = [66, 'peter']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[-1]) # Prints last element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(tinylist * 3) # Prints list 3 times
print(list + tinylist) # Prints concatenated lists
list[0] = 'new' #replaces the 0th part of list
print(list)
list = [1,2,3,4,5];
print(len(list)) #Gives the total length of the list.
print(max(list)) #Returns item from the list with max value.
print(min(list)) #Returns item from the list with min value.
print("*****************************************")
print("****************strings********************")
name = "Peter"
print(name) # Prints complete string
print(name[0]) # Prints first character of the string
print(name[2:4]) # Prints characters starting from 3rd to 5th
print(name[2:]) # Prints string starting from 3rd character
print(name * 3) # Prints string three times
print(name + " TEST") # Prints concatenated string
print("a" in name)
print("e" in name)
print("My name is %s and I am %d years old!" % (name, 23)) #format string
name = "maria"
print(name.capitalize()) #Capitalizes first letter of string
print(name.upper()) #Converts lowercase letters in string to uppercase
print(name.count("a")) #Counts how many times argument occurs in string
print(name.find("i")) #Determine if argument occurs in string and returns index of match
print(name.find("x")) #Determine if argument occurs in string and returns -1 if it doesn't exist
print(len(name)) #Returns the length of the string
print(name.split("a")) #Splits string according to delimiter argument
print("*****************************************")
print("****************conditional statements********************")
print("****************if statements********************")
positiveInteger = 2
if positiveInteger <= 5:
print("Value of positiveInteger variable is less or equal to 5")
elif positiveInteger <= 10:
print("Value of positiveInteger variable is larger than 5 but less or equal than 10")
else:
print("Value of positiveInteger is larger than 10")
print("****************while statements********************")
count = 0
while (count < 5):
print('The count is:', count)
count = count + 1
print("Good bye!")
print("****************break statements********************")
for letter in 'Python':
if letter == 'h':
break
print('Current Letter :', letter)
print("****************continue statements********************")
for letter in 'Python':
if letter == 'h':
continue
print('Current Letter :', letter)
print("*****************************************")
print("****************functions********************")
def printUpperCase(string):
"This funtions turns the input argument string into upper case and prints the result"
stringUpperCase = string.upper()
print(stringUpperCase)
printUpperCase("i am now uppercase") #In this line we are calling the function previously defined
total = 0; # This is global variable.
# Function definition
def sum( arg1, arg2 ):
# Add both input parameters and return their sum."
total = arg1 + arg2; # Here total is local variable.
print("Inside the function local total : ", total)
return total;
# function invocation
returnedTotal = sum( 10, 20 );
print("Outside the function global total : ", total)
print("Value returned by function: ", returnedTotal)
print("*****************************************")
print("****************classes ********************")
class Employee:
'Common base class for all employees' #documentation string
empCount = 0
def __init__(self, name, salary): #constructor
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self): #method
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self): #another method
print("Name: ", self.name, ", Salary: ", self.salary)
print(Employee.__doc__) # the documentation string can be accessed as Classname.__doc__
print("****************inheritance ********************")
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print("Calling parent constructor")
def parentMethod(self):
print('Calling parent method')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("Parent attribute :", Parent.parentAttr)
class Child(Parent): # define child class which inherits from Parent
def __init__(self):
super().__init__() #Calling parent class constructor
print("Calling child constructor")
def childMethod(self):
print('Calling child method')
c = Child() # instance of child
print("------------")
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self): #Print method overloading
return('Vector (%d, %d)' % (self.x, self.y))
def __add__(self,other): #plus operator overloading
return Vector(self.x + other.x, self.y + other.y)
a = Vector(4,2)
b = Vector(1,5)
c=a+b # we use the plus operator which has been overloaded by the vector class implementation
print(c) # the vector class also overloaded the print method |
dd12416e62cdb9ec1748f796b29b62e02925413a | yycang/Bucciarat | /剑指offer/two.py | 906 | 3.75 | 4 | # 实现单例
"""使用new方法, 将类的实例绑定在类变量上,判断是否为none,
如果没有的话,new一个该类的实例并返回,没有的话直接返回类变量"""
class Singleton:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
singer = super(Singleton, cls)
cls._instance = singer.__new__(cls, *args, **kwargs)
return cls._instance
class TestClass(Singleton):
a = 1
one = TestClass()
two = TestClass()
print(id(one))
print(id(two))
"""使用装饰器实现"""
def singleton(cls, *args, **kwargs):
instance = {}
def get_instance():
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return get_instance
@singleton
class TestClass2:
a = 1
three = TestClass2()
four = TestClass2()
print(id(three))
print(id(four))
|
fa3ee4f4b9232e11841c85f9abebf93ff0c1b974 | stasvorosh/pythonintask | /PINp/2014/KOROTKOVA_D_S/task_2_39.py | 608 | 3.78125 | 4 | # Задача 2 Вариант 39
# Текст задачи Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Гомер. Не забудьте о том, что автор должен быть упомянут на отдельной строке.
# Короткова Д.С.
# 05.03.2016
print("Женщину украшает молчание.")
print("\t\t\t\t\t\t\t\t\t\t\t\t\t\tГомер")
input("нажмите enter для выхода")
|
dd9b6f7df0fe7d3cb735525739cb2ef64531b80a | GuiGolfeto/curso-em-video | /mundo 1/Usando módulos do Python/exercicios/ex017.py | 204 | 3.6875 | 4 | from math import hypot
op = float(input('Digite o valor do Cateto oposto: '))
ad = float(input('Digite o valor do Cateto adjacente: '))
hip = hypot(op, ad)
print(f'O valor da hipotenusa é {hip :.2f}')
|
77ab262c7e603d3196a61f8d691b2a6896e6a46c | Littlemansmg/pyClass | /Week 5 Assn/Project 14/14-1.py | 1,506 | 4 | 4 | # created by Scott "LittlemanSMG" Goes on DD/MM/YYYY
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
def area(self):
return self.height * self.width
def perimeter(self):
return (self.height + self.width) * 2
def show_rect(self):
temp = len("* " * self.width)
print("* " * self.width)
for i in range(self.height - 2):
print("*" + " " * (temp - 3) + "*")
print("* " * self.width)
def main():
print("Rectangle Calculator")
while True:
height, width = 0, 0
while True:
try:
height = int(input('Height:\t '))
if height <= 0:
raise ValueError
except ValueError:
print("You must put in an integer.")
continue
break
while True:
try:
width = int(input('Width: \t '))
if width <= 0:
raise ValueError
except ValueError:
print("You must put in an integer.")
continue
break
new_shape = Rectangle(height, width)
print(f"Perimeter: {new_shape.perimeter()}")
print(f"Area:\t {new_shape.area()}")
new_shape.show_rect()
end = input("\nContinue? (y/n): ")
print()
if end.lower() == 'n':
exit()
if __name__ == "__main__":
main()
|
bd1e62da5fb9f1e9f5e630677171339e56bef3e9 | dianvaltodorov/learning-code | /learning-dsa/cracking_the_coding_interview/chapter_2/2.4.py | 574 | 3.625 | 4 | class Node:
def __init__(self, data, next=None):
self.next = next
self.data = data
n1 = Node(3)
n1.next = Node(1)
n1.next.next = Node(5)
n2 = Node(5)
n2.next = Node(9)
n2.next.next = Node(2)
def calculate_sum(n1, n2):
sentinel = Node(0)
head = sentinel
carry = 0
while n1 and n2:
val = n1.data + n2.data + carry
carry = val // 10
node = Node(val % 10)
head.next = node
head = head.next
n1 = n1.next
n2 = n2.next
return sentinel.next
n = calculate_sum(n1, n2)
print(10)
|
28af10f7274e2dafff250be4721ced2dafd28f2f | DIPEA/Newer-s-Python-program | /guess.py | 479 | 3.921875 | 4 | import random
secret = random.randint(1,99)
guess = 0
tries = 0
print("game start")
while guess != secret and tries < 6:
guess = input("what is your guess?")
if int(guess) < secret:
print("too low")
elif int(guess) > secret:
print("too high")
tries = tries + 1
if int(guess) == secret:
print("congratulations!")
input()
else:
print("you lose, game over.")
print("the secret number was:", secret)
input()
|
a9e3874be94922475f6d585a804fd6dd91134270 | MaxZN/Leetcode | /111.二叉树的最小深度.py | 691 | 3.609375 | 4 | #
# @lc app=leetcode.cn id=111 lang=python3
#
# [111] 二叉树的最小深度
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root: return 0
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if left ==0 and right==0:
return 1
elif (left == 0 and right!=0) or (left!=0 and right==0):
return max(left,right)+1
else:
return min(left,right)+1
# @lc code=end
|
7284f8d2221b932023475398c7e7b48c3975f1db | huangruihaocst/leetcode-python | /700. Search in a Binary Search Tree/solution.py | 957 | 3.828125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
# self.right = None
class Solution:
def searchBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
def DFS(node, v):
if node.val == v:
return node
elif node.val > v:
if node.left:
return DFS(node.left, v)
else:
return None
else:
if node.right:
return DFS(node.right, v)
return DFS(root, val)
if __name__ == '__main__':
s = Solution()
t = TreeNode(4)
t.left = TreeNode(2)
t.right = TreeNode(7)
t.left.left = TreeNode(1)
t.left.right = TreeNode(3)
res = s.searchBST(t, 2)
print(res.val)
print(res.left.val)
print(res.right.val)
|
3ac619ba22899ebc44b65599470c719007aa6519 | xinyang12/python_practice | /5/14.py | 430 | 3.96875 | 4 | def main():
file_name = input("输入文件名: ")
infile = open(file_name, "r")
line_count = 0
word_count = 0
char_count = 0
for line in infile:
line_count += 1
word = line.split()
word_count += len(word)
for ch in line:
char_count += 1
print("行数是:", line_count)
print("单词数是:", word_count)
print("字符数是:", char_count)
main()
|
eb4f5389153723596890858b0f7fd3c101930651 | alvarovdt/100-Days-Of-Code-Udemy | /100 Days of Code/2. Intermediate [15-31]/Day 15 Coffee Machine/main.py | 2,219 | 4.03125 | 4 | from data import MENU
from data import resources
my_money = 0.0
machine_money = 0.0
machine_on = True
def ask_and_insert_coins():
local_money = 0.0
print("Please insert coins")
quarters = int(input("How many quarters? (25cents)"))*0.25
dimes = int(input("How many dimes? (10cents)"))*0.10
nickels = int(input("How many nickles? (5cents)"))*0.05
pennies = int(input("How many pennies? (1cent)"))*0.01
local_money = pennies + nickels + dimes + quarters
return local_money
def check_available_ressources(type_of_drink):
if type_of_drink == 'espresso':
if resources['water'] > MENU['espresso']['ingredients']['water'] and resources['coffee'] > MENU['espresso']['ingredients']['coffee']:
print("OK")
return True
else:
print("KO")
return False
else:
if resources['water'] > MENU[type_of_drink]['ingredients']['water'] and resources['coffee'] > MENU[type_of_drink]['ingredients']['coffee'] and resources['milk'] > MENU[type_of_drink]['ingredients']['milk']:
return True
else:
return False
def check_money(mmoney, drink_price):
if mmoney >= drink_price:
return True
else:
return False
while machine_on == True:
option = input("What would you like? (espresso/latte/cappuccino): ").lower()
if option == "off":
print("Turning off the coffee machine")
machine_on = False
elif option == "report":
print(f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}g\nMoney: ${machine_money}")
else:
if check_available_ressources(option):
my_money = ask_and_insert_coins()
if check_money(my_money, MENU[option]["cost"]):
resources['water'] -= MENU[option]['ingredients']['water']
resources['coffee'] -= MENU[option]['ingredients']['coffee']
if option != 'espresso':
resources['milk'] -= MENU[option]['ingredients']['milk']
machine_money += MENU[option]['cost']
my_money -=MENU[option]['cost']
else:
print("Error, not enough money")
else:
print("Error, not enough ressources")
print(f"Machine money = {machine_money} returned money: {my_money}")
my_money=0 |
76c0a75284a69f412ede04aced2a1f0cbaa849bc | justinta89/Work | /PythonProgramming/Chapter 5/Exercises/quizzes.py | 449 | 4.1875 | 4 | # quizzes.py
# This program will take a user input quiz score 1 - 5, then output the appropriate grade.
def main():
# Get grade from user
grade = int(input("Enter grade (0 - 5): "))
# check to see what letter the number matches.
letters = ['F', 'F', 'D', 'C', 'B', 'A']
letterGrade = letters[grade]
# return the correct grade based on the given number.
print("The letter grade is: {0}".format(letterGrade))
main() |
fd027fdd603eeff950dffc8c237cd3408e7f6e37 | Aislingpurdy01/CA277 | /cities-in-state-1.py | 278 | 3.515625 | 4 | #!/usr/bin/env python
import sys
header = sys.stdin.readline()
x = header.split(",")
cities = sys.stdin.readlines()
field = sys.argv[1]
i = 0
while i < len(cities):
tokens = cities[i].strip().split(",")
if tokens[9] == field:
print cities[i].strip()
i = i + 1
|
48036e56ad6c2006c36ed2fc0a5097e16075a0ce | alechaka/algorithms-python | /mergesort.py | 1,346 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
def merge_sort(a, first = 0, last = None):
"""
Args:
a: A list of unsorted items.
first: The index of the first item.
last: The index of the last item.
Returns:
A list of sorted items.
Note:
time: const * n * log_2(n)
"""
def merge_v_1(a, first, mid, last):
left = a[first:mid + 1] + [float('Inf')]
right = a[mid + 1:last + 1] + [float('Inf')]
i = 0
j = 0
print 'L and R:', left, right
for k in range(first, last + 1):
if left[i] < right[j]:
a[k] = left[i]
i += 1
else:
a[k] = right[j]
j += 1
return a
def merge_v_2(a, first, mid, last):
left = a[first:mid + 1]
right = a[mid + 1:last + 1]
i = 0
j = 0
print 'L and R:', left, right
for k in range(first, last + 1):
if i < len(left) and j < len(right):
if left[i] < right[j]:
a[k] = left[i]
i += 1
else:
a[k] = right[j]
j += 1
elif i < len(left):
a[k] = left[i]
i += 1
elif j < len(right):
a[k] = right[j]
j += 1
return a
if last == None:
last = len(a) - 1
if not a or first == last:
return a
mid = (first + last) / 2
merge_sort(a, first, mid)
merge_sort(a, mid + 1, last)
return merge_v_1(a, first, mid, last)
if __name__ == '__main__':
print 'Input:', [5, 2, 4, 6, 1, 3, 5]
print merge_sort([5, 2, 4, 6, 1, 3, 5])
|
c9623e2723d6e86dcf06a83d6df2a5cff6d8d942 | limar63/study_folder | /PythonPrograms/OtherPythonGarbo/exam.py | 1,852 | 3.65625 | 4 | #'abc' ->
['bac','cab','acb','cba','bca','abc']
# n!=1*2*...*n
# 3!=1*2*3=6
# 'a','bc'
# ['bc','cb']
# ['bc','cb']
# ['abc','acb']
# 'b','ac'
# ['bac','bca']
# 'c','ab'
# ['cab','cba']
#permutations
a=[1,2]
b=[3,4]
c=[5,6]
[1,2,3,4,5,6]
a.append(b)
def permutations(s):
if s == '':
return [s] # since 'abc' => permutates to 'abc' (itself)
b = []
for i in range(len(s)):
b += [s[i] + j for j in permutations(s[:i] + s[i+1:])]
#s2 = s[i] + permutations(s1)
return b
#print(permutations('abcd'))
# for i in range(1,10):
# a=1
# a+=a
# sum=0
# for i in range(1,10):
# sum+=i
# a=[1,2,3]
# for i in a:
# b.append(i*2)
# print(b)
# 'abcd'
# "".join(['a','bcd'])
# [['a','bcd']
# ['ab','cd']
# ['abc','d']
# ['abcd'] ]
# 'abcd'
# 'a','bcd'
# [['b','cd'], ['bc','d'], ['b','c','d']]
# [['a','b','cd'], ['a','bc','d'], ['a', 'b','c','d']]
# [['ab','cd'], ['abc','d'], ['ab','c','d']]
# [['a','b','cd'], ['a','bc','d'], ['a', 'b','c','d'],['ab','cd'], ['abc','d'], ['ab','c','d']]
def breakups(s):
if len(s) <=1:
return [[s]]
first = s[0]
other = breakups(s[1:])
lst = [[first] + i for i in other]
lst_1 = [[first + i[0]] + i[1:] for i in other]
return lst + lst_1
# 'aabbb' -> False
# 'abcccccbb' -> True
# {'a','b','c'}
#print(breakups(''))
def odd(s):
return all(s.count(i)%2==1 for i in set(s))
# for i in set(s):
# if s.count(i)%2 == 1:
# return True
# return False
#print(odd('abcccccbb'))
#['a','b','cd'] -> 'a|b|cd'
def min_counts_odds(s):
lst = [i for i in breakups(s) if len(i) > 1 and all(odd(j) for j in i) ]
#print(lst)
a = min(lst,key = lambda x:len(x))
#print(a)
return '|'.join(a)
print(min_counts_odds('bacacababa'))
# join all funcs together in breakups |
1eaf6dbb00e0b654a1c35c435bf0313c2de0ca5d | anil0775/Python | /sumOfNumbers.py | 159 | 4.15625 | 4 | """Program for calculating sum of two number"""
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
sum = num1 + num2
print(sum) |
c9fb86add088dd70cfa867189a7209f4468e455e | QT-HH/Algorithm | /Programmers/Lv2/전화번호 목록.py | 356 | 3.765625 | 4 | def solution(phone_book):
answer = True
check_list = set()
for i in phone_book:
if len(i) == 2:
check_list.add(i[0])
continue
for j in range(1, len(i)):
check_list.add(i[:j])
for i in phone_book:
if i in check_list:
answer = False
break
return answer |
f3b4984a53a1b6625f79e50f9757689a6c03bc39 | RanChenSignIn/Numpy_Pandas_Seaborn | /Numpy/numpy_Netease_could/numpy_copy_deepcopy.py | 250 | 3.640625 | 4 | import numpy as np
#浅度复制
a=np.arange(4)
print(a)
b=a
c=a
d=b
a[0]=6
print(a)
print(b)
print(c)
print(b is a)#判断a是否是与b完全相同,成立返回true,否则返回FALSE
#deep copy
b=a.copy()
#或者 b=a[:]
print(b)
a[3]=33
print(a) |
237302a60c0cf49ad7c2edc0c6b61f52172ea703 | YeongEunLee/Algorithm | /백준/1_그리디/2839.py | 92 | 3.796875 | 4 | n = input()
if n % 5 == 0:
res = n // 5
elif n % 3 == 0:
res = n // 3
else:
m = n // 5 |
c42cc7e32ac446d66c46280fbc24250607e80c33 | pushon07/Project_Euler | /006_sum_square.py | 275 | 3.515625 | 4 | max_num = 100
sum_squares = 0
for i in xrange(1, max_num + 1):
sum_squares += i ** 2
square_sums = (max_num * (max_num + 1) / 2.0) ** 2
print ("Sum_of_squares=%d; Square_of_sums=%d" % (sum_squares, square_sums))
print ("The difference = %d" % (square_sums - sum_squares)) |
06025bde02deddbb05e070c302d54f2cc7e0d425 | vishalkumar95/ECE-4802-Cryptography-and-Communication-Security | /Vigenere_Cipher_Autokey_Plaintext.py | 1,331 | 3.859375 | 4 | # This function is an implementation of the autokey Vigenere cipher algorithm.
def decryptVigenere(ciphertext, key):
ciphertextbreak = []
ciphertextbreakextra = []
Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
smallLetters = 'abcdefghijklmnopqrstuvwxyz'
keylength = len(key)
ciphertextlength = len(ciphertext)
diff = ciphertextlength - keylength
finalplaintext = list('.' * ciphertextlength)
ciphertextbreak.append(ciphertext[0 : keylength])
ciphertextbreakextra.append(ciphertext[-diff:])
for i in range(0, len(ciphertextbreak)):
for j in range(0, keylength):
indkey = smallLetters.index(key[j])
indcipher = Letters.index(ciphertextbreak[i][j])
newindcipher = indcipher - indkey
modindcipher = newindcipher % 26
finalplaintext[j] = smallLetters[modindcipher]
for i in range(0, diff):
indkey = smallLetters.index(finalplaintext[i])
indcipher = Letters.index(ciphertextbreakextra[0][i])
newindcipher = indcipher - indkey
modindcipher = newindcipher % 26
finalplaintext[keylength + i] = smallLetters[modindcipher]
plaintext = "".join(finalplaintext)
plaintext = plaintext.upper()
print(plaintext)
|
b0e61d2d734e96f385135bccada46d9163e937f2 | johnathanachen/cs1 | /Grade_Book/Assignments.py | 428 | 3.671875 | 4 | class assignments(object):
def __init__(self, name):
self.name = name
with open('./db/students.txt', 'r') as student_db:
student_names = [line.strip() for line in student_db]
if self.name in student_names:
pass
else:
print(self.name, "is not in the class")
def get_average(self, average):
self.average = average
|
02489f84921f37f83902ccc272888414167273d8 | Cxiaojie91/python_basis | /python_basis/python_procedure/01_python_basis/07_condition.py | 731 | 4.1875 | 4 | # a = 17
# if a >=18:
# print('你的年龄是:', a)
# print('你已成年')
# else:
# print('你的年龄是:', a)
# print('你未成年')
#
# b = 2
# if b >= 18:
# print('adult')
# elif b >= 6:
# print('teenager')
# elif b >= 3:
# print('kid')
# else:
# print('baby')
#
# s = input('birth:')
# birth = int(s)
# if birth < 2000:
# print('00前')
# else:
# print('00后')
# 作业
w = input('weight:')
h = input('height:')
weight = float(w)
height = float(h)
bmi = weight / (height * height)
if bmi < 18.5:
print('过轻')
elif 18.5 <= bmi <= 25:
print('正常')
elif 25 <= bmi <= 28:
print('过重')
elif 28 <= bmi <= 32:
print('肥胖')
else:
print('严重肥胖') |
f3c02d6d08392f3b50233404a69ecfd0fc0f49d5 | gabriellaec/desoft-analise-exercicios | /backup/user_166/ch59_2019_06_07_00_02_59_313348.py | 188 | 3.5625 | 4 | def conta_a (string):
contador = 0
vezes_a=0
while contador < len(string):
if string[contador] == "a":
vezes_a += 1
contador += 1
return vezes_a |
76a45f3bae0da04a548684faab4e11751513caa0 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4000/codes/1828_1657.py | 341 | 3.671875 | 4 | from numpy import*
n = input("maior quantidade: ").split(',')
a=0
b=0
c=0
d=0
e=0
for i in range(size(n)):
if(n[i] == "AZ"):
a=a+1
elif(n[i]=="CA"):
b=b+1
elif(n[i]=="FL"):
c=c+1
elif(n[i]=="PA"):
d=d+1
elif(n[i]=="WI"):
e=e+1
v = zeros(5,dtype=int)
v[0]=a
v[1]=b
v[2]=c
v[3]=d
v[4]=e
j=max(v)
print(j)
print(v)
|
bbcd09a379145b066823ab81d0302c2d70418c1b | Noah-Schoonover/class | /lab6/lab6p12.py | 650 | 4.21875 | 4 | #lab6p12
#Prime Number Generation
#Noah Schoonover
def isPrime(num):
for x in range(2, int(num**.5)+1):
if num % x == 0:
return False
return True
def getPrimes(r):
print("The prime numbers between from 2 to {} are:".format(r))
nums = range(2,r+1)
for x in nums:
if isPrime(x):
print(x)
while True:
r = input("Up to what range (>1) do you want the primes for? ").strip()
try:
r = int(r)
except ValueError:
print("Range can be whole numbers only.")
else:
if r > 1:
getPrimes(r)
else:
print("Range must be greater than 1.")
|
f5ab498a6e801d219758be3ea6e8255966dc34a5 | rzc96/python-course | /sesion-8/game.py | 1,140 | 3.71875 | 4 | import pygame
ancho = 240
altura = 180
def main():
x = 50
y = 50
velocidad = 1
pygame.init()
pygame.display.set_caption("test")
pantalla = pygame.display.set_mode((ancho, altura))
corriendo = True
while corriendo:
pygame.time.delay(100) # delay siempre presente en lo que se ejecuta cada acción
for event in pygame.event.get():
if event.type == pygame.QUIT: # mientras no salga del juego, no se cierra
corriendo = False
teclas = pygame.key.get_pressed() # cual es la tecla que el usuario presiono
# validar la dirección del movimiento del rectangulo segun la tecla presionada
if teclas[pygame.K_LEFT]:
x -= velocidad
if teclas[pygame.K_RIGHT]:
x += velocidad
if teclas[pygame.K_UP]:
y -= velocidad
if teclas[pygame.K_DOWN]:
y += velocidad
pantalla.fill((0, 0, 0)) # limpia pantalla
pygame.draw.rect(pantalla, (255, 0, 0), (x, y, 40, 60)) # dibuja el rectangulo
pygame.display.update() # actualiza pantalla
main() |
2e1992fd0c518f8836df742358c8099969ceae85 | nagarajuiitm/PythonCorseJohn | /FlexibleNumberOfArguments.py | 274 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 13:15:44 2019
@author: SNR
"""
def add_numbers(a,b,c):
total = a +b+c
print(total)
def MultiplyNumber(a,b,c):
result= a * b* c
print (result)
MultiplyNumber(2,3,4)
add_numbers(2,3,4)
|
b32db9b2d86d49d93a4e79687d4d0ea483cad1fb | artpods56/Matura-Informatyka-Python | /2018 Maj - Rozszerzenie/zad4_2.py | 660 | 3.59375 | 4 | plik = open("sygnaly.txt","r")
strings = []
for linia in plik:
linia = linia.strip()
strings.append(linia)
naj_dl = 0
naj_string = ""
def ile_roznych(string):
litery = []
for letter in string:
if letter not in litery:
litery.append(letter)
len_litery = len(litery)
return string, len_litery
for string in strings:
# print(f"{string} oraz ilosc roznych liter {ile_roznych(string)[1]}")
if ile_roznych(string)[1] > naj_dl:
naj_dl = ile_roznych(string)[1]
naj_string = string
print(f"wyraz o najwiekszej ilosci roznych liter w liczbie {naj_dl} to {naj_string}")
|
a2cb30cfd7ca6e131c6eca8255ea072b824041b8 | vipul-royal/A7 | /rev.py | 189 | 4.34375 | 4 | def reverse(s):
str=" "
for i in s:
str=i+str
return str
s=str(input("Enter the string:"))
print("The original string is:",s)
print("The reversed string is:",reverse(s)) |
8234b4c9291420671eac2c6f1257e893abd1efe4 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_135/2436.py | 806 | 3.5625 | 4 | n_cases = int(raw_input())
def read_int():
return int(raw_input())
def read_arrangement():
return [eval("[ " + raw_input().replace(" ", ",") + " ]") for i in range(4)]
def transpose_arrangement(arr):
return [[ x[i] for x in arr] for i in range(4)]
for case in range(1, n_cases+1):
answer1 = read_int() - 1
arrange1 = read_arrangement()
answer2 = read_int() - 1
arrange2 = read_arrangement()
row1_nums = set(arrange1[answer1])
row2_nums = set(arrange2[answer2])
#arrange2_t = transpose_arrangement(arrange2)
#row2t_nums = set(arrange2_t[answer2])
solutions = set.intersection(row1_nums, row2_nums)
if len(solutions) == 1:
output = list(solutions)[0]
elif len(solutions) == 0:
output = "Volunteer cheated!"
else:
output = "Bad magician!"
print "Case #%d: %s" % (case, output)
|
1b6a81c583ab37a02fb2f2529fdbc19a50a1ccd8 | yangjiahao106/LeetCode | /Python3/09_Palindrome_Number.py | 1,407 | 3.84375 | 4 | #! python3
# __author__ = "YangJiaHao"
# date: 2018/2/3
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
tmp = x
rev = 0 # 反转后的数字, 其他语言需要考虑反转后溢出的问题
while tmp:
rev = rev * 10 + tmp % 10
tmp = tmp // 10
return rev == x
def isPalindrome2(self, x):
if x < 0:
return False
e = len(str(x))
for i in range(e // 2):
if x % 10 != x // 10 ** (e - 1 - i * 2):
return False
x = x // 10
x = x % (10 ** (e - 2 - i * 2))
return True
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
# 只反转一半数字,不会溢出,需要特殊处理 以0结尾的数字
if x % 10 == 0 and x != 0:
return False
rev = 0 # 反转后的数字, 其他语言需要考虑反转后溢出的问题
while x > rev:
rev = rev * 10 + x % 10
x = x // 10
return rev == x or x == rev // 10 # 偶数位则相等, 奇数位则 x == rev//10
if __name__ == '__main__':
s = Solution()
i = s.isPalindrome2(123321)
print(i)
# 12321
|
9a67a68d4f8b680ca491c98ce2a47d434b083154 | sapanp007/python_scripts | /min_chars_to_palindrome.py | 607 | 3.75 | 4 | from math import ceil
def find_min_chars_to_make_palindrome(s):
str_len = len(s)
st_pt = ceil(str_len/2) - 1
left = st_pt - 1
right = st_pt + 1
while right < str_len and left >= 0:
if s[left] == s[right]:
left = left - 1
right = right + 1
elif s[left] != s[right] and right != str_len-1:
st_pt = st_pt - 1
left = st_pt - 1
right = st_pt + 1
elif str_len == 3:
right = 1
return str_len-right
# s = "ABC"
# s = "AACECAAAA"
s = "GFGHGFGIII"
print(find_min_chars_to_make_palindrome(s))
|
3243c9b93aae4fb93e8591d16626126e299ba4e3 | Nidhintsajee/Test-answers | /image-puzzle/puzzle.py | 1,383 | 3.796875 | 4 | #!/usr/bin/python
import requests
def print_urls(file):
#Each line is of the form: GET /foo/bar/a.jpg
#remove the GET and print only /foo/bar/a.jpg
#use a for-loop to iterate through each line of `file'
#split the line and print second part
for line in f:
print line.split()[1]
f = open('1.txt')
print_urls(f)
def eliminate_duplicates_and_sort(file):
#remove duplicate lines from `file'
r = sorted(set(file))
for line in r:
print line,
if __name__ == '__main__':
eliminate_duplicates_and_sort(open('2.txt'))
def save_image(url, filename):
print url
r = requests.get(url)
f = open(filename, 'w')
f.write(r.content)
f.close()
def main():
filename = 1
url_base = 'http://code.google.com'
#open file 3.txt
#using a for loop, save each url to a file
#you can use the save_image function for doing
#this.
#The files to which you are saving the urls should
#be called 0.jpg, 1.jpg, 2.jpg etc.
for url in open('3.txt'):
save_image(url_base + url.strip(), "images/" + str(filename) + ".jpg")
print 'saved file %d' % filename
filename += 1
main()
print """<html>
<head><title>Images</title></head>
<body>
"""
for i in range(0,21):
print '<img src="%s">' % (str(i) + ".jpg")
print """</body></html>"""
|
1865d73948fd61456461bc10d4079d36ef1efea8 | Arjun-Pinpoint/InfyTQ | /Programming Fundamentals using Python/Day 2/Assignment 19.py | 2,002 | 4.03125 | 4 | '''
FoodCorner home delivers vegetarian and non-vegetarian combos to its customer based on order.
A vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs Rs.150 per plate. Their non-veg combo is really famous that they get more orders for their non-vegetarian combo than the vegetarian combo.Apart from the cost per plate of food, customers are also charged for home delivery based on the distance in kms from the restaurant to the delivery point. The delivery charges are as mentioned below:
Distance in kms Delivery charge in Rs per km
For first 3kms 0
For next 3kms 3
For the remaining 6
Given the type of food, quantity (no. of plates) and the distance in kms from the restaurant to the delivery point, write a python program to calculate the final bill amount to be paid by a customer.
The below information must be used to check the validity of the data provided by the customer:
• Type of food must be ‘V’ for vegetarian and ‘N’ for non-vegetarian.
• Distance in kms must be greater than 0.
• Quantity ordered should be minimum 1.
If any of the input is invalid, the bill amount should be considered as -1.
Solution:
'''
def calculate_bill_amount(food_type,quantity_ordered,distance_in_kms):
if quantity_ordered>=1 and distance_in_kms>0:
deli_cost = 0
bill_amount=0
dist = [(3,0),(6,3),(7,6)]
if food_type == 'V':
food_cost = quantity_ordered * 120
elif food_type == 'N':
food_cost = quantity_ordered * 150
else:
return -1
dist_covered = 0
while dist_covered<= distance_in_kms:
for distance in dist:
if dist_covered<= distance[0]:
value = distance[1]
break
deli_cost = deli_cost + value
dist_covered=dist_covered+1
bill_amount = food_cost + deli_cost
return bill_amount
else:
return -1
bill_amount=calculate_bill_amount("N",2,7)
|
c30fddbe359dfcf52c69ac0aa96edc866853391c | herrmannjob/DevTraining | /Languages/Python/Exercises/Meu Python Minha Vida.py | 915 | 3.9375 | 4 | print('=' * 35)
print('Programa Meu Python, Minha vida')
print('=' * 35)
casa = float(input('Qua o valor da casa? R$: '))
salario = float(input('Qual o seu salario? R$: '))
pres = int(input('Em quantos anos quer pagar? '))
pres1 = float(casa / (pres * 12))
sal = salario * 30 / 100
if pres1 > sal:
print('Com o salario de R${:.2f}, seu emprestimo nao pode ser aprovado, sentimos muito.'.format(salario))
else:
print('Com o salario de R${:.2f}, seu emprestimo pode ser aprovado, parabéns!!.'.format(salario))
casa = float(input('Valor da casa: R$ '))
salário = float(input('Salário do comprador: R$ '))
anos = int(input('Quantos anos de financiamentos? '))
prestação = casa / (anos * 12)
mínimo = salário * 30 / 100
print('Para pagar uma casa de R${:.2f} em {}anos. '.format(casa, anos), end='')
if prestação <= mínimo:
print(' Emprestimo pode ser CONCEDIDO!')
else:
print(' Emprestimo NEGADO')
|
727930e9c0a74bfc78c32e50bcacdece77fb0149 | neu-velocity/code-camp-debut | /codes/Aiamjay/Week3-Day4/126. Word Ladder II.py | 2,891 | 3.609375 | 4 | # encoding = utf-8
from collections import (
defaultdict, deque
)
from math import inf
class Solution1:
def ladderLength(self, beginWord: str, endWord: str, wordList: list):
if endWord not in wordList or not wordList:
return 0
# # wjcnote 创建图
word_dict = defaultdict(list)
word_len = len(beginWord)
for word in wordList:
for i in range(word_len):
word_dict[word[:i] + '*' + word[i + 1:]].append(word)
# wjcnote 搜索图 bfs
queue = deque([(beginWord, 1)])
visited = set()
graph = defaultdict(set)
distances = dict()
min_len = inf
while queue:
cur, length = queue.popleft()
for i in range(word_len):
key = cur[:i] + '*' + cur[i + 1:]
for word in word_dict[key]:
if word != cur and word not in graph[cur]:
graph[word].add(cur)
distances[word] = min(distances[word], length) if word in distances else length
if word not in visited:
if word == endWord:
min_len = min(min_len, length + 1)
visited.add(word)
queue.append((word, length + 1))
# for item in graph:
# print(item, " ", graph[item])
#
# for item in distances:
# print(item, " ", distances[item])
return self.find_all_path(distances, graph, endWord, beginWord, min_len - 1)
def find_all_path(self, distances, graph, node, end, length):
if length == 1:
return [[end, node]]
result = []
for parent in graph[node]:
if distances[parent] == length - 1:
result += [item + [node] for item in self.find_all_path(distances, graph, parent, end, length - 1)]
return result
def test_solution(self):
# case 1
# begin_word = "hit"
# end_word = "cog"
# word_list = ["hot", "dot", "dog", "lot", "log", "cog"]
# result = self.ladderLength(begin_word, end_word, word_list)
# print(result)
# assert sorted(result) == sorted(
# [
# ["hit", "hot", "lot", "log", "cog"],
# ["hit", "hot", "dot", "dog", "cog"],
# ])
# case 2
begin_word = "red"
end_word = "tax"
word_list = ["ted", "tex", "red", "tax", "tad", "den", "rex", "pee"]
print(self.ladderLength(begin_word, end_word, word_list))
assert sorted(self.ladderLength(begin_word, end_word, word_list)) == sorted(
[["red", "ted", "tad", "tax"], ["red", "ted", "tex", "tax"], ["red", "rex", "tex", "tax"]]
)
if __name__ == '__main__':
s = Solution1()
s.test_solution()
|
6f59d5224c5625c671a29e2b9c92108975094221 | qq854051086/46-Simple-Python-Exercises-Solutions | /problem_11.py | 560 | 4.4375 | 4 | '''
Define a function generate_n_chars()that takes
an integer n and a character c and returns a string,
n characters long, consisting only of c:s. For
example, generate_n_chars(5,"x")should return
the string "xxxxx". (Python is unusual
in that you can actually write an expression
5 * "x"that will evaluate to
"xxxxx". For the sake of the exercise you should
ignore that the problem can
be solved in this manner.)
'''
def generate_n_chars(n,c):
s = ''
for i in range(n):
s += c
return s
print(generate_n_chars(5,"x"))
|
d57fac16be388f429ee361680056bb39ef541698 | tanvir07-ops/python_oop | /another_app.py | 1,068 | 3.8125 | 4 | '''
p = {}
p['name'] = 'Tanvir Rifat'
p['email'] = '[email protected]'
print(p)
'''
class Person:
def __init__(self,name,email):
self.__name = name
self.__email = email
def log(self):
print(self.__dict__)
@property
def name(self):
print(self.__name)
@property
def email(self):
print(self.__email)
@name.setter
def name(self,name):
self.__name = name
@email.setter
def email(self,email):
self.__email = email
def __str__(self):
return f'Name : {self.__name}, Email : {self.__email}'
person= Person('Tanvir Rifat','[email protected]')
person.name = 'Tanvir Hassan Rifat'
person.email = '[email protected]'
person.log()
print(person)
class Guardian(Person):
def __init__(self,name,email,fee):
super().__init__(name,email)
self.__fee = fee
@property
def fee(self):
print(self.__fee)
@fee.setter
def fee(self,fee):
self.__fee = fee
guardian = Guardian('Rabeya Begum','[email protected]',200000)
guardian.log()
print(guardian)
|
f1aaa838a3e26ea33701272008b7441d779d5975 | Formation-CDA-Grenoble/S01-Algo-E05-POO | /Person.py | 2,579 | 3.640625 | 4 | import datetime
# Simulation de données que l'on pourrait récupérer d'une base de données
data = [
["Josette", "Martin", 25, False],
["Robert", "Durand", 45, True],
["Lucien", "Pinard", 33, True],
]
# Modèle permettant de créer des objets (instances) représentant des personnes
class Person:
# Propriétés des objets de type "personne"
firstName = ""
age = 0
lastName = ""
isMale = False
# Méthodes : fonctions encapsulées dans une classe, qui permettent à chacune de ses instances
# de connaître un comportement spécifique à elle-même
# En Python, chaque méthode prend comme premier paramètre une référence vers l'objet qui l'appelle,
# appelée "self" (soi-même) par convention
# Méthode permettant de renvoyer le nom complet d'une personne
def fullName(self):
return self.firstName + " " + self.lastName
# Méthode permettant de renvoyer un message de salutation de la part d'une personne
def sayHello(self):
return "Bonjour, je m'appelle " + self.fullName()
# Méthode permettant à une personne de saluer une autre personne
def sayHelloTo(self, otherPerson):
return "Bonjour " + otherPerson.firstName + ", je m'appelle " + self.fullName()
# Modèle permettant de créer des objets (instances) représentant des articles
class Article:
# Propriété des objets de type "article"
createdAt = datetime.datetime.now()
title = ""
content = ""
# La variable "auteur" de chaque article contient un objet de type "personne"
author = None
# Génère des objets de type "personne" en adéquation avec le tableau de données récupéré plus haut
people = []
for personData in data:
# Crée un objet de type "personne"
person = Person()
# Remplit les propriétés de l'objet nouvellement créé avec les données du tableau
person.firstName = personData[0]
person.lastName = personData[1]
person.age = personData[2]
person.isMale = personData[3]
# Ajoute l'objet nouvellement créé à une liste
people.append(person)
# Crée un nouvel objet de type "article"
article = Article()
article.title = "Le Python ça déchire"
article.content = "texte texte texte texte texte texte texte "
# Définit Robert comme auteur de cet article
article.author = people[1]
# Affiche le nom complet de l'auteur de l'article
print(article.author.fullName())
# Pour chaque personne générée
for person in people:
# Demande à cette personne de saluer Josette
print(person.sayHelloTo(people[0]))
|
6204dee29982170180d6d6efe80645ad2c6fb00c | garigari-kun/til | /src/codewars/python/6kyu/order.py | 1,080 | 4 | 4 | """
Your task is to sort a given string.
Each word in the String will contain a single number.
This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input String is empty, return an empty String. The words in the input String will only contain valid consecutive numbers.
For an input: "is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est"
Test.assert_equals(order("is2 Thi1s T4est 3a"), "Thi1s is2 3a T4est")
"""
import unittest
def order(sentence):
s_sentence = sentence.split(' ')
d_sentence = {}
for word in s_sentence:
for ch in word:
if ch.isdigit():
d_sentence[int(ch)] = word
return ' '.join(d_sentence.values())
class Test(unittest.TestCase):
def test_order(self):
self.assertEqual(order('is2 Thi1s T4est 3a'), 'Thi1s is2 3a T4est')
if __name__ == '__main__':
# result= order('is2 Thi1s T4est 3a')
# print(result)
unittest.main()
|
ac7ebe4762df32bd7a685a5f3d0e886b4cab2f7f | eduardoh27/IP-JAVERIANA202120 | /prueba.py | 530 | 3.671875 | 4 | """
Parcial 1 Barrera
"""
def main ():
total = int(input("Ingrese el # de casilleros: "))
abiertos = 0
cerrados = 0
i=1
while i <= total:
divs = divisores(i)
if divs%2 != 0:
print(i, " queda abierto")
abiertos += 1
i+=1
cerrados = total - abiertos
print(cerrados,"casilleros cerrados")
return None
def divisores(n):
divs = 0
i = 1
while i <= n:
if n%i == 0:
divs += 1
i+=1
return divs
main()
|
2dd5923a98201c18c936866b72aafa5b555c18d6 | allgoliot/Projet-python | /module/mathematiques.py | 638 | 3.96875 | 4 | #Fonction addition
def addition(a,b):
print("Somme =", a+b)
#Fonction soustraction
def soustraction(a,b):
print("Soustraction =", a-b)
#Fonction multiplication
def multiplication(a,b):
print("Multiplication =", a*b)
#Fonction division
def division(a=1,b=1):
resultat = 0
try:
resultat = a/b
print("Division =",resultat)
except ZeroDivisionError:
print('Division par zero impossible !!')
except TypeError:
print('Une des deux variable n`est pas un nombre !!')
def demomath():
addition(10,5)
soustraction(60,20)
multiplication(3,5)
division(6,3)
#demomath()
|
2432643ba6caef66100251966201aac767d82db1 | lonmiss/2020WinterHoliday | /数据结构与算法/20200125Class/par/十进制转换成任意进制.py | 374 | 3.53125 | 4 | from Stack import *
def divibeByany(decNumber,numCnt):
arr=Stack()
n=decNumber
while decNumber > 0:
n=decNumber % numCnt
arr.push(n)
decNumber//=2
binString= ""
while not arr.isEmpty():
binString+=str(arr.pop())
print("十进制的数{}转换成{}进制的数为:{}".format(n,numCnt,binString))
divibeByany(11,8) |
f49c7866f8d47b4174b206e9d24aef35c1d79937 | varungove/CS242 | /CSAir2.1/Assignment2.1/src/graph.py | 785 | 3.59375 | 4 | """
Graph class and functionality
"""
import parse
class Graph:
city_dict = {}
convert = {}
def __init__(self, control):
"""
Constructor for the Graph
"""
if(control == '1' or control == '2'):
self.city_dict, self.convert = parse.parse_graph(self.city_dict, self.convert, control)
if(control == '3'):
self.city_dict, self.convert = parse.parse_graph(self.city_dict, self.convert, '1')
self.city_dict, self.convert = parse.parse_graph(self.city_dict, self.convert, '3')
def save_file(self):
"""
Saves graph to file
"""
parse.save_file(self.city_dict)
|
400fe488e5caa65d30b256f1f73ba20960eaec21 | MgArreaza13/CifrarDescifrar | /package/menu.py | 476 | 3.8125 | 4 | #metodo que muestra el menu, y recoge la opcion valida que necesita ejecutar el usuario
import os
def menu(): #menu
opc = 0
while True:
os.system("cls")
print("Selecione una opcion que decea relizar \n"
+"\n1)Encriptar Texto Plano \n"
+"2)Desencriptar Texto Plano\n"
+"3)Encriptar Archivo .TXT \n"
+"4)Desencriptar Archivo .TXT \n"
+"5)SALIR"
)
opc = int(input("\nSeleccione una opcion valida: "))
if opc>=1 and opc<=5:
return opc
|
03959660d9e9e0a2fefc8920a2360594764f432f | SilvesterKnuut/Python | /Section_21_Interacting_with_Databases/SQLite_Connecting_Inserting_Data.py | 921 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 13:00:54 2019
@author: Silvester
Standart proces to interact with a db:
1. Connect to a database
2. Create a cursor object (Its a pointer to access rows from the table of a db)
3. Apply an SQL query
4. Commit the changes to the database
5. Close the conection to the db
"""
import sqlite3
DB_Connection = sqlite3.connect("MyFirstDB.db")
CursorObj = DB_Connection.cursor()
CursorObj.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
CursorObj.execute("INSERT INTO store VALUES ('Piggy', 8, 10.5)")
DB_Connection.commit()
DB_Connection.close()
def viewDB():
DB_Connection = sqlite3.connect("MyFirstDB.db")
CursorObj = DB_Connection.cursor()
CursorObj.execute("SELECT * FROM store")
rows=CursorObj.fetchall()
DB_Connection.close()
return rows
print(viewDB()) |
6f796c1b957c510905192ddb4afcc1f9be6ad5b6 | serebrov/so-questions | /python-abc/abc_test.py | 887 | 4.15625 | 4 | from abc import ABCMeta, abstractmethod
class ClassA:
def do(self):
print('A-do')
class ClassB:
def do(self):
print('B-do')
class ClassC:
pass
class Doable(metaclass=ABCMeta):
@abstractmethod
def do(self):
pass
# We can register existing classes as "Doable" without modifying them
Doable.register(ClassA)
Doable.register(ClassB)
Doable.register(ClassC)
try:
# Although in this case (no explicit inheritance from Doable), the ClassC()
# will NOT raise the type error
collect = [ClassA(), ClassB(), ClassC()]
for item in collect:
# here we will get `ClassC` object has no attribute `do`
if isinstance(item, Doable):
item.do()
except Exception as err:
print(err)
# TypeError: Can't instantiate abstract class ClassD with abstract methods do
class ClassD(Doable):
pass
d = ClassD()
|
24e66f84ec444fa169869163e067280670d5f9c9 | aselivan0v/home-work-beetroot | /lesson5/l5task2.py | 792 | 4.0625 | 4 | # Task 2
# Exclusive common numbers.
# Generate 2 lists with the length of 10 with random integers from 1 to 10,
# and make a third list containing the common integers between the 2 initial lists without any duplicates.
# Constraints: use only while loop and random module to generate numbers
import random
x = 0
list_of_numbers = []
list_of_numbers_two = []
list_of_numbers_res = []
while x < 10:
list_of_numbers.append(random.randint(1, 10))
list_of_numbers_two.append(random.randint(1,10))
x += 1
x = 0
while x < 10:
if list_of_numbers[x] in list_of_numbers_two and not list_of_numbers[x] in list_of_numbers_res:
list_of_numbers_res.append(list_of_numbers[x])
x += 1
print(list_of_numbers, list_of_numbers_two, sep='\n')
print('Result =', list_of_numbers_res) |
f1882189924a62864cc7b3b35e9a0975d8d848f1 | iftekharchowdhury/Problem-Solving-100-Days | /py_collections_namedtuple.py | 402 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import namedtuple
n = int(input())
fields = input().split()
total = 0
for i in range(n):
students = namedtuple('student', fields)
ID, NAME, MARKS, CLASS = input().split()
student = students(ID, NAME, MARKS, CLASS)
total = total + int(student.MARKS)
result = total / n
print(round(result,2)
|
f54effd5e5a3380936e0fa635e830c2f4c0ee80d | Hema113/python_puzzles | /fact.py | 206 | 4.1875 | 4 | def fact(n):
fact = 1
for i in range(1,n+1):
fact *= i
return fact
if __name__ == "__main__":
n=int(input("Enter number>>>"))
print("The Factorial of given number is", fact(n))
|
417e178ab859ef40492c6846f6e64f7116a96b04 | aflens/Learning-python | /Electron_configuration.py | 752 | 3.890625 | 4 | import math
# Calculates the electron configuration of atoms
Atomic_number =____ # number of electrons
o_name = ['s', 'p', 'd', 'f', 'g']
o_value = [2, 6, 10, 14, 18]
output_string = ""
end_period = 1
while Atomic_number > 0:
for i in range(math.floor((end_period-1)/2), -1, -1):
if(Atomic_number > o_value[i]):
output_string += "{0}{1}({2})".format(end_period -
i, o_name[i], o_value[i])
else:
output_string += "{0}{1}({2})".format(end_period -
i, o_name[i], Atomic_number)
Atomic_number = 0
break
Atomic_number -= o_value[i]
end_period += 1
print(output_string)
|
d49be0373c5c49c937143c224dbb37aa78ea7263 | yuxiaous/adventofcode | /2020/day21.py | 2,655 | 3.5 | 4 | #!/usr/bin/env python3
import re
class Food:
def __init__(self, info):
m = re.match(r'(.+) \(contains (.+)\)', info)
self.ingredients = m.group(1).split(' ')
self.allergens = m.group(2).split(', ')
class Day21:
def __init__(self, inputs):
self.foods = [Food(x) for x in inputs.split('\n')]
self.ingredients = set()
self.allergens = set()
self.counter = {}
for food in self.foods:
for ingredient in food.ingredients:
self.ingredients.add(ingredient)
for allergen in food.allergens:
self.allergens.add(allergen)
key = (ingredient, allergen)
if key not in self.counter:
self.counter[key] = 0
self.counter[key] += 1
def part1(self):
for allergen in self.allergens:
keys = [(ingr, alle)
for ingr, alle in self.counter if alle == allergen]
largest = max(keys, key=lambda k: self.counter[k])
removes = []
for ingr, alle in self.counter:
if alle == allergen:
if self.counter[(ingr, alle)] < self.counter[largest]:
removes.append((ingr, alle))
for remove in removes:
del self.counter[remove]
possibles = set(ingr for ingr, alle in self.counter)
inerts = set(
ingredient for ingredient in self.ingredients if ingredient not in possibles)
count = 0
for inert in inerts:
for food in self.foods:
if inert in food.ingredients:
count += 1
return count
def part2(self):
ingredients = set()
allergens = set()
for ingr, alle in self.counter:
ingredients.add(ingr)
allergens.add(alle)
# dairy fish nuts peanuts sesame shellfish soy wheat
# ltbj 13
# nrfmm 9
# pvhcsn 12
# jxbnb 6
# chpdjkf 14
# jtqt 7
# zzkq 10
# jqnhd 12
def main():
inputs = open("day21.txt").read().strip()
day21 = Day21(inputs)
print(f'Part 1: {day21.part1()}')
print(f'Part 2: {day21.part2()}')
if __name__ == "__main__":
main()
|
6f7a2bc9e63a1f52dd996eeb0005921d170f980d | yaswanthkoravi/Apsproject | /tests/insertion1.py | 492 | 3.546875 | 4 | import matplotlib.pyplot as plt
#inserting elements in rb tree in ascending order
y=[0.38,0.659,0.93,1.27,6.604,48.468]
x=[500,1000,1500,2000,10000,100000]
#inserting elements into splay tree in ascending order
y1=[0.14,0.278,0.362,0.44,2.022,13.32]
x1=[500,1000,1500,2000,10000,100000]
plt.ylabel("Time(ms)")
plt.xlabel("No of points")
plt.title("Inserting numbers in ascending order")
plt.plot(x,y,label="RB-Tree")
plt.plot(x1,y1,label="Splay-Tree")
plt.legend(loc="upper left")
plt.show()
|
9883b10a554507fbd879684074cbd55739adaebc | gbuchdahl/term_blackjack | /printing.py | 796 | 3.859375 | 4 | import typing
from typing import List
from card import Card
def print_piles(cards: List[Card]) -> None:
""" prints a 1D array of cards as they would be a hand"""
for i in range(len(cards)):
print("+----+", end=" ")
print()
for i in range(len(cards)):
print("| |", end=" ")
print()
for card in cards:
num = card.get_name()
if num == "10":
print(f"| {num}", end="")
else:
print(f"| {num} ", end="")
print(f"{card.get_suit()}|", end=" ")
print()
for i in range(len(cards)):
print("| |", end=" ")
print()
for i in range(len(cards)):
print("+----+", end=" ")
print()
if __name__ == "__main__":
x = [Card(a, "c") for a in range(1, 4)]
print_piles(x)
|
8a7b5e8e544f9df45c5c762cbc7c5d73dc057aa3 | icejoywoo/toys | /algorithm/leetcode/70_climbing_stairs.py | 577 | 3.84375 | 4 | #!/usr/bin/env python2.7
# encoding: utf-8
"""
@brief: https://leetcode.com/problems/climbing-stairs/
和斐波那契数列一样
@author: icejoywoo
@date: 2019-10-11
"""
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n+1)
dp[0] = 1
dp[1] = 1
for i in range(2, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
if __name__ == '__main__':
s = Solution()
assert s.climbStairs(2) == 2
assert s.climbStairs(3) == 3 |
b27aa79330db66571923d6529b9e59ad801424e8 | andrei-tarnauceanu/uhomeuponor | /custom_components/uhomeuponor/uponor_api/utilities.py | 333 | 3.6875 | 4 | def flatten(*args):
output = []
for arg in args:
if hasattr(arg, '__iter__'):
output.extend(flatten(*arg))
else:
output.append(arg)
return output
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n] |
25d8caf0f8af7e61453c84c6b2a3f2c68ea056b7 | jiaquan1/cracking-the-coding-interview-189-python | /Chapter5-bits/54next_number.py | 3,134 | 3.859375 | 4 | <<<<<<< HEAD
def next_numbers(number):
if number <=0:
return None,None
if number%2:
a = 1
c1=0
#large
while number&a and number>=a:
c1+=1
a<<=1
if number<a:
large = a+(1<<(c1-1))-1
else:
large = ((number//a+1)<<c1) + (1<<(c1-1))-1
#small
b = 1
c0=0
c00=0
while number&b:
b<<=1
c0+=1
if number<b:
small = None
else:
while not number&b:
b<<=1
c00+=1
print('b=',b,'c0=',c0,)
small = ((number//b-1)*b)+(((1<<(c0+1))-1)<<(c00-1))
else:
#large
a=1
c1=0
while not number&a:
a<<=1
while number&a and number>=a:
c1+=1
a<<=1
if number<a:
large = a+(1<<(c1-1))-1
else:
large = ((number//a+1)<<c1) + (1<<(c1-1))-1
#small
b=1
c0=0
while not number&b:
b<<=1
small = ((number//b-1)*b)+(b>>1)
return (small,large)
import unittest
class Test(unittest.TestCase):
def test_next_numbers(self):
self.assertEqual(next_numbers(8), (4, 16))
self.assertEqual(next_numbers(12), (10, 17))
self.assertEqual(next_numbers(15), (None, 23))
self.assertEqual(next_numbers(143), (124, 151))
self.assertEqual(next_numbers(159), (126, 175))
if __name__ == "__main__":
unittest.main()
=======
def next_numbers(number):
if number <=0:
return None,None
if number%2:
a = 1
c1=0
#large
while number&a and number>=a:
c1+=1
a<<=1
if number<a:
large = a+(1<<(c1-1))-1
else:
large = ((number//a+1)<<c1) + (1<<(c1-1))-1
#small
b = 1
c0=0
c00=0
while number&b:
b<<=1
c0+=1
if number<b:
small = None
else:
while not number&b:
b<<=1
c00+=1
print('b=',b,'c0=',c0,)
small = ((number//b-1)*b)+(((1<<(c0+1))-1)<<(c00-1))
else:
#large
a=1
c1=0
while not number&a:
a<<=1
while number&a and number>=a:
c1+=1
a<<=1
if number<a:
large = a+(1<<(c1-1))-1
else:
large = ((number//a+1)<<c1) + (1<<(c1-1))-1
#small
b=1
c0=0
while not number&b:
b<<=1
small = ((number//b-1)*b)+(b>>1)
return (small,large)
import unittest
class Test(unittest.TestCase):
def test_next_numbers(self):
self.assertEqual(next_numbers(8), (4, 16))
self.assertEqual(next_numbers(12), (10, 17))
self.assertEqual(next_numbers(15), (None, 23))
self.assertEqual(next_numbers(143), (124, 151))
self.assertEqual(next_numbers(159), (126, 175))
if __name__ == "__main__":
unittest.main()
>>>>>>> 45e00abd356375b5fb384fa23f21f34195b99a48
|
aefee984b8984c8187842127d050fed037d079ad | winterfellding/mit-cs-ocw | /6.006/clrs/chap8.py | 472 | 3.71875 | 4 | def count_sort(array, count_array):
for i in array:
count_array[i] += 1
for i in range(1, len(count_array)):
count_array[i] += count_array[i-1]
result = [0] * len(array)
for i in range(len(array)-1, -1, -1):
print(count_array)
print(i)
result[count_array[array[i]]-1] = array[i]
count_array[array[i]] = count_array[array[i]] - 1
return result
print(count_sort([6, 0, 2, 0, 1, 3, 4, 6, 1, 3, 2], [0]*7)) |
6036dede25545c9a8723fc6b3f4b31e350cb4955 | giuliocorradini/CryptoWorkshop | /cryptow/maths/maths.py | 903 | 3.796875 | 4 | import logging
def gcd(a, b):
'''
Computes the greatest common divisor using Euclid's extended
algorithm.
:param a: positive integer
:param b: positive integer <= a
:return: positive integer
'''
if b == 0:
return a
if b > a:
return gcd(b, a)
seq = [a, b, a%b]
while seq[2] != 0:
logging.debug(f"GCD compute step: {seq}")
seq.pop(0)
seq.append(seq[0] % seq[1])
return seq[1]
def phi(n):
'''
Computes Euler's phi function. First rough implementation.
:param n: Positive integer to compute the totient of
:return: The number of coprimes of n in range [1, N)
'''
# 1 is always coprime with every number, therefore is skipped
coprimes = 1
for i in range(2, n):
if gcd(i, n) == 1: # coprimes only share 1 as common divisor
coprimes += 1
return coprimes
|
451d7ab52a0fdf06d20495f3217c41d3702c8d97 | ash/amazing_python3 | /344-concat-string-list.py | 151 | 3.75 | 4 | # How to concatenate a few strings
# from a list to a single string
data = [
"This", "is",
"my", "message"
]
str = " ".join(data)
print(str)
|
590e9129b65336da3bf98020faaa05f12066b8dd | skreynolds/uta_cse_1309x | /mid_semester_exam/Test1.py | 84 | 3.5 | 4 | x = ["dog", 2, "cat", 34, 5.8]
m = 0
for i in range(len(x)):
m = m + i
print(m)
|
0644016412c650a8d59c67a61d0b63bfb2273b76 | shwetabhsharan/leetcode | /linkedin/sll.py | 1,597 | 3.828125 | 4 |
class Node(object):
def __init__(self, data):
self.data = data
class SLL(object):
def __init__(self):
self.head = None
def add(self, value):
node = Node(value)
node.next = self.head
self.head = node
def remove(self, value):
curr = self.head
while curr is not None:
prev = None
if curr.data == value:
prev.next = curr.next
curr.next = None
break
else:
prev = curr
curr = curr.next
def length(self):
curr = self.head
length = 0
while curr is not None:
length = length + 1
curr = curr.next
# def reverse(self):
# prev = None
# current = self.head
# while(current is not None):
# next = current.next
# current.next = prev
# prev = current
# current = next
# self.head = prev
def reverse(self):
prev = None
curr = self.head
while curr is not None:
next = curr.next
curr.next = prev
prev = curr
curr = next
self.head = prev
def sort_list(self):
pass
def get_max(self):
pass
def get_min(self):
pass
def traverse(self):
curr = self.head
while curr is not None:
print curr.data
curr = curr.next
obj = SLL()
obj.add(1)
obj.add(2)
obj.add(3)
obj.add(4)
obj.add(5)
obj.traverse()
obj.reverse()
obj.traverse() |
a4c38e64654a47e661bc0334a1bc3196f7510868 | balanikaran/College-Practicals-GLAU | /PythonClasses/primeComplexityKBvsHS.py | 985 | 4.03125 | 4 | import time
import math
def checkPrimeKB(number):
#true = prime false = not prime
if(number%2 == 0 and number != 2):
return False
else:
for i in range (3, int(math.sqrt(number)) + 1):
if(number%i == 0):
return False
return True
def checkPrimeHS(n):
#true = prime false = not prime
if (n == 2 or n == 3 or n == 5 or n == 7):
return True
elif (n % 2 == 0 or n % 3 == 0 or n % 5 == 0 or n % 7 == 0):
return False
elif (n == 1):
return False
else:
return True
upRange = input("Enter the max number to find primes: ")
start = time.time()
count = 0
for i in range (2, upRange + 1):
if(checkPrimeHS(i) != checkPrimeKB(i)):
print("Result KB: {}".format(checkPrimeKB(i)))
print("Result HS: {}".format(checkPrimeHS(i)))
print("{} Glitch".format(i))
count = count + 1
print("Time taken in seconds: {}".format(time.time() - start))
print(count)
|
156fda4ef1a2f9bd2c8a2fcbbab2a89e84206723 | mhill142/swc_newstuff | /stats.py | 410 | 4.15625 | 4 | def mean(vals):
"""Calculate the arithmetic mean of a list of numbers in vals"""
assert type(vals) is list, 'wrong input format'
total = sum(vals)
length = len(vals)
if length == 0:
return 0.0
else:
return total/length
def test_mean():
assert mean([2,4]) == 3.0
test_mean()
def test_empty_list():
assert mean ([]) == 0.0
test_empty_list()
#print(mean("hello"))
|
dea43d809227b6e100192d80bea0a341e27e8f8c | erdembozdg/coding | /python/python-interview/intermediate/recursive.py | 991 | 3.640625 | 4 | from itertools import permutations
perm = permutations([1, 2, 3])
print(list(perm))
def permute(s):
out = []
if len(s) == 1:
out = [s]
else:
for i, v in enumerate(s):
for perm in permute(s[:i] + s[i+1:]):
out += [v + perm]
return out
def word_split(phrase,list_of_words, output = None):
if output is None:
output = []
for word in list_of_words:
if phrase.startswith(word):
output.append(word)
word_split(phrase[len(word):],list_of_words, output)
return output
print(word_split('themanran',['the','ran','man']))
print(word_split('ilovedogsJohn',['i','am','a','dogs','lover','love','John']))
# staircase problem
cache = dict()
def stepPerms(n):
if n == 1:return 1
if n == 2:return 2
if n == 3:return 4
if n not in cache:
cache[n] = stepPerms(n-1)+stepPerms(n-2)+stepPerms(n-3)
return cache[n]
print(stepPerms(10)) |
cdb7c45a88a9840ce6e770308ee8732ccbe4aa4c | afsana1210/python-learning | /spy_game.py | 349 | 3.96875 | 4 | #SPY GAME-Write a function that takes in a list of integers and returns True if it contains 007 in order
def spy_game(nums):
code=[0,0,7,'x']
#check [0,7,'x'] x is some string
# [7,'x']
# ['x'] len is 1.
for num in nums:
if num == code[0]:
code.pop(0)
return len(code) == 1
res=spy_game([1,0,2,3,0,7,8,9])
print res
|
0b5fdc968a6c98b11f55428af3ca115a04bc6641 | wesleysilva2/Introdu-oPythomUSP | /Programas parte 2/Programas semana 1/LeMatrizes.py | 1,211 | 4.0625 | 4 | def cria_matriz(num_linhas, num_colunas):
"(int,int) -> matriz (lista de listas)"
"Cria e retorna uma matriz com nun_linhas linhas e num_colunas"
"colunas em que cada elemento é digitado pelo usuario"
matriz = [] # lista vazia, guarda as linhas da matriz
for i in range(num_linhas): # numero de vezes que ele vai executar
# cria a lista i
linha = [] # lista vazia, guarda as colunas
for j in range(num_colunas): # executa dependedo do numero de colunas
valor = int(input("Digite o elemento [" + str(i) + "][" + str(j) + "]: ")) # O str e apenas para converter o inteiro em string, isso e meramente para mostrar ao usuario qual posição ele esta adicionando
linha.append(valor) # adiciona o valor escolhido pelo usuario na coluna
# adiciona linha á matriz
matriz.append(linha) # acabou a coluna vai para proxima linha e reinicia
return matriz
def le_matriz():
lin = int(input("Digite o numedo de linhas da matriz: "))
col = int(input("Digite o numedo de colunas da matriz: "))
imprime = cria_matriz(lin,col)
organiza(imprime)
def organiza(matrix):
print(matrix)
|
314c3dd78b38e3394f2e4ecbaae4be42facb8b88 | Bravelemming/PushingAWSIotButton | /email_button.py | 2,201 | 3.59375 | 4 | # Generate Email from Raspberry Pi GPIO button press
# HSU LumberHacks Hackathon
# Team: Pressing Dave's button
# Contributors: Jack Kinne, Sam Alston, Max Lemos, Nathan Ortolan
# Last Modified: 3/24/18
# Standard time library
import time
# GPIO Control
import RPi.GPIO as GPIO
# Email
import smtplib
# To email complex messages (including subject line)
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
# Board = BCM
GPIO.setmode(GPIO.BCM)
# No warnings, thanks!
GPIO.setwarnings(False)
# -- GPIO PIN SETUP --
button = 18 #GPIO 18 (PIN #12)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def emailOnButton(toaddr, printer_id, location, subject):
'''emailOnButton(): null -> null
Expects nothing, returns nothing, has the side effects of
sending an email to [email protected]'''
fromaddr = '[email protected]'
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject
#msg['Subject'] = "Printer Help Request"
body = "Send help to printer station " + printer_id + ' located: ' + location + ' has requested help!'
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr,'ghostinthemachine')
text = msg.as_string()
server.sendmail(fromaddr, toaddr,text)
server.quit()
# -- -- -- -- -- --
# Listen for button click and call emailOnButton()
try:
while True:
input_value = GPIO.input(button)
if input_value == False:
print('The button has been pressed...')
#emailOnButton('[email protected]')
emailOnButton('[email protected]', '54b7894', 'Library floor 2', "We have pushed Dave's button.")
emailOnButton('[email protected]', '54b7894', 'Library floor 2', "We have pushed Dave's button.")
emailOnButton('[email protected]', '54b7894', 'Library floor 2', "We have pushed Dave's button.")
emailOnButton('[email protected]', '54b7894', 'Library floor 2', "We have pushed Dave's button.")
time.sleep(0.2)
finally:
print("cleaning")
# cleanup on normal exit
GPIO.cleanup()
print("cleaned")
|
55bfa0513194ff7d907e806792ae52b9281eb06c | admud/pythonforbeginners | /app.py | 1,780 | 4.09375 | 4 | # print("hello lul")
# use py -3 for python 3
# use py -2 for python 2
# or use special comment at the top of script
# print(" /|")
# print(" / |")
# print(" / |")
# print("/ |")
# character_name = "Kapp"
# print("my name is " + character_name)
# phrase = "omegalul"
# print(phrase.upper())
# print(phrase[2])
# name = input("Enter your name fam: ")
# print("Hi " + name)
# num1 = int(input("Enter the first number: "))
# num2 = int(input("Enter the second number: "))
# result = num1 + num2
# print(result)
# print("Result is " + str(result))
# color = input("Enter a color ")
# plural_noun = input("Enter a plural noun ")
# celebrity = input("Enter a celebrity ")
# print("My fav color is " + color)
# print("lulp my " + plural_noun)
# print("that " + celebrity +" is dope")
# LISTS
# friends = ["Kappa", "LUL", "Pepega","PogChamp","PepeHands"]
# lucky_numbers = [1,2,3,4,5,6,7,8,9,10]
# friends.extend(lucky_numbers)
# friends.append("XD")
# friends.remove("LUL")
# lucky_numbers.reverse()
# print(friends)
# print(lucky_numbers)
# # TYUPLES -> IMMUTABLEEE cannot be modified lad!
# coordinates = (4,5)
# Functions
# def sayKappa(name):
# print("Kappa? " + name)
# sayKappa("lulx")
# more functions
# is_male = True
# if is_male:
# print("You are a male")
# else:
# print("You are not a male")
# monthConversions = {
# "Jan" : "January",
# "Feb" : "February"
# }
# friends = ["a","b","c"]
# for index in range(len(friends)):
# print(friends[index])
# TRY EXCEPT handling errors
# try:
# number = int(input("Enter "))
# print(number)
# except:
# print("Kappa")
# file reading
# open =("tex.txt","r")
# import useful_tools
# print(useful_tools.roll_dice(10))
# class Student:
# def __init__(self,name,major, gpa):
|
93a2a10d61b6b53e6f11f0fe4c2d2bc54dc8e123 | MulengaKangwa/PythonCoreAdvanced_CS-ControlStatements | /53HandleZero.py | 206 | 4.34375 | 4 |
x = int(input("Enter a number:"))
if x==0:print(x, "is zero")
elif x%2 == 0:print(x,"is even")
else:print(x, "is odd")
# This simple demonstrates how to use the ELSE IF ladder, using the elif condition.
|
f07cbd7c7c1d4e8f037908b5a2baba27fd1ee8e4 | green-fox-academy/FKinga92 | /week-02/day-01/draw_square.py | 366 | 4.1875 | 4 | # Write a program that reads a number from the standard input, then draws a
# square like this:
#
#
# %%%%%
# % %
# % %
# % %
# % %
# %%%%%
#
# The square should have as many lines as the number was
n = int(input("Please enter a number: "))
for i in range(n):
if i==0 or i==(n-1):
print("%"*(n-1))
else:
print("%" + " "* (n-3) + "%") |
392a2a1e3da4b5807a0ed426c394cbe0f0307469 | CarolinaFCerqueira/Learning_Python2018 | /Exercise04_check_internet.py | 473 | 3.71875 | 4 | #Exercise 4
#Carolina
#Time spent: 10 minutes
# -*- coding: Latin-1 -*
""" Write a program to check a computer is connected to the internet. """
import requests
def check_internet():
url='http://www.google.com/'
timeout=5
try:
_ = requests.get(url, timeout=timeout)
return True
except requests.ConnectionError:
print("Internet is OFF.")
return False
if check_internet():
print "Internet is ON" |
e368c7a813fe1c088b5a2af53301bfb6a294be75 | hoang-ng/LeetCode | /Array/628.py | 1,182 | 4.03125 | 4 | # 628. Maximum Product of Three Numbers
# Given an integer array, find three numbers whose product is maximum and output the maximum product.
# Example 1:
# Input: [1,2,3]
# Output: 6
# Example 2:
# Input: [1,2,3,4]
# Output: 24
# Note:
# The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
# Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
class Solution1:
def maximumProduct(self, nums):
nums.sort()
n = len(nums)
return max(nums[n - 1] * nums[n - 2] * nums[n - 3], nums[0] * nums[1] * nums[n - 1])
class Solution2:
def maximumProduct(self, nums):
max1 = max2 = max3 = -float("inf")
min1 = min2 = float("inf")
for n in nums:
if n >= max1:
max3, max2, max1 = max2, max1, n
elif n >= max2:
max3, max2 = max2, n
elif n > max3:
max3 = n
if n <= min1:
min2, min1 = min1, n
elif n < min2:
min2 = n
return max(max1 * max2 * max3, max1 * min1 * min2) |
d90d6f814fc89f9d9145fc1e9fa8fd9e63c46562 | sbrew/cohort4 | /python/code.py | 205 | 3.671875 | 4 | f_name = input("Please give me your first name:")
l_name = input("Please give me your last name:")
address = "evolveu.ca"
print(f"Thank you for creating your new e-mail it is {f_name}.{l_name}@{address}") |
9c3dabc0cb7878af42f2d4a36a3ede6c6d9bbb74 | G0rocks/Honnunarverkefni-ortolvu-og-maelitaekni-2020 | /demo code/input_test.py | 658 | 3.890625 | 4 | def castAsInt(a):
"""
Function takes in value a and attempts to cast it as int, returns "null" if it fails
"""
try:
return int(a)
except:
return "null"
print("Ath 1 lota er 5 sek þ.e. 12 lotur mæla í 60 sek")
c = input("Hversu margar lotur viltu profa?: ")
c = castAsInt(c)
while (True): # Safety measure in case somebody puts "Fiskur" as a number
try:
while (c == "null" or castAsInt(c) < 0):
print("Sláðu inn heila tölu sem er stærri en 0")
c = castAsInt(input("Hversu margar lotur viltu prófa?"))
break
except ValueError as ex:
print('%s\nCan not convert %s to int' % (ex, c))
print("Prófum: ",c) |
9638690853557bdce179d4f8817cf348274674b3 | ecollins2307/HPM573S18_COLLINS_HW1 | /HW1_problem1.py | 405 | 4.03125 | 4 | #HW 1, Problem 1
#Part 1
#creating y1 as integer
y1 = int(17)
#creating y2 as float
y2 = float(17)
#creating y3 as string
y3 = "17"
#creating y4 as Boolean
y4 = (17==17)
#printing the above variable with their type
print(y1)
print(type(y1))
print(y2)
print(type(y2))
print(y3)
print(type(y3))
print(y4)
print(type(y4))
#Part 2
#create text variable using y3
text = "The value of x is "+y3
print(text)
|
b052b571aa430f6f1d1ba8ac8c232dfa6db83fff | raoashish10/NoCode-ML | /ML_Codes/Clustering.py | 2,015 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 05:22:49 2020
@author: nishantn
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
def KMeans(X, n=6):
kmeans = KMeans(n_clusters = n, init = 'k-means++')
y_kmeans = kmeans.fit_predict(X)
# plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
# plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
# plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
# plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')
# plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')
# plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids')
# plt.title('Clusters of customers')
# plt.xlabel('Annual Income (k$)')
# plt.ylabel('Spending Score (1-100)')
# plt.legend()
# plt.show()
return y_kmeans, kmeans
from sklearn.cluster import AgglomerativeClustering
def HC(X, n = 6):
hc = AgglomerativeClustering(n_clusters = n, affinity = 'euclidean', linkage = 'ward')
y_hc = hc.fit_predict(X)
# plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
# plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
# plt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
# plt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')
# plt.scatter(X[y_hc == 4, 0], X[y_hc == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')
# plt.title('Clusters of customers')
# plt.xlabel('Annual Income (k$)')
# plt.ylabel('Spending Score (1-100)')
# plt.legend()
# plt.show()
return y_hc, hc
|
937468dee6e73695f417b29876ee8c9b65935a77 | 72Roman/Data-Manipulation-at-Scale-Coursera | /assigment3/asymmetric_friendships.py | 1,038 | 3.53125 | 4 | import sys
import MapReduce
mr = MapReduce.MapReduce()
def mapper(record):
person, friend = record
mr.emit_intermediate(person, ("has_as_friend", friend))
mr.emit_intermediate(friend, ("is_friend_of", person))
def reducer(key, list_of_values):
person, friendships = key, list_of_values
friends = set()
friend_of = set()
all_other_persons = set()
for friendship in friendships:
kind, other_person = friendship
all_other_persons.add(other_person)
if kind == "has_as_friend":
friends.add(other_person)
elif kind == "is_friend_of":
friend_of.add(other_person)
for other_person in all_other_persons:
is_symetric_friend = other_person in friends and other_person in friend_of
if not is_symetric_friend: # and person > other_person: # Grader expects both (a, b) and (b, a) pairs
mr.emit((person, other_person))
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
764bfe6778573aaa9564593ded691601a93d9271 | Indhuu/git-github | /python/Name_prog.py | 316 | 3.953125 | 4 | # Name prog
Name = raw_input("Enter the Name:")
Age = raw_input ("Enter the Age:")
print ('Name of the person: ' + Name)
print ('Age of the person: ' + Age)
A = Name * 5
print A
B = float(Age)
print ('Age after converting to float:'+ str(B))
C = len(Name)
print ('length of the name:'+ str(C))
|
5f8469c69c8355675f74939ce0e80416f117ef1c | baloooo/coding_practice | /detect_html_tags.py | 426 | 3.65625 | 4 | """
https://www.hackerrank.com/challenges/detect-html-tags
"""
import re
regex = r"<\s*[a-zA-Z]{1,3}\s*>*"
n = int(raw_input().strip())
tags = set()
final_tags = []
for i in xrange(n):
inp = raw_input().strip()
tag_matches = re.finditer(regex, inp)
for match in tag_matches:
tags.add(re.sub(r'[<|>|\\\s]', '', match.group()))
for tag in tags:
final_tags.append(tag)
print ';'.join(sorted(final_tags))
|
64faf607b140cb576ccace9da660013802c20d7b | DaveFelce/shopping-cart | /main.py | 1,124 | 3.65625 | 4 | from cart import Cart
from item import Item
from user import User
def main():
item_shorts = Item(name='shorts', price=10, description='Some nice shorts')
item_tshirt = Item(name='tshirt', price=20, description='A nice t-shirt')
item_pants = Item(name='pants', price=30, description='Lovely pants')
# create user
user = User('Eric')
# create a new cart
cart = Cart()
user.add_cart(cart)
# Eric does some shopping
cart.add_item(item_shorts, 4)
cart.add_item(item_tshirt, 2)
cart.add_item(item_pants, 3)
# we want to display his cart
retrieved_cart = user.get_cart_by_id(cart_id=cart.cart_id)
print(retrieved_cart)
pants = retrieved_cart.get_item('pants')
print(pants)
cart2 = Cart()
cart2.add_item(item_shorts, 1)
cart2.add_item(item_tshirt, 2)
cart2.add_item(item_pants, 3)
user.add_cart(cart2)
retrieved_cart2 = user.get_cart_by_id(cart_id=2)
tshirt = retrieved_cart2.get_item('tshirt')
print(tshirt)
tshirt_total = cart2.get_item_total('tshirt')
print(tshirt_total)
if __name__ == '__main__':
main()
|
7c15ac86290c9b2a4aa0164a3e6535fb078b0b76 | abimarticio/learning-python | /exercises/exercise_01.py | 746 | 4.0625 | 4 | #Ask for the following information,
#and display the:
#country
#gender
#mobile number
#major
#birthday
#instagram username
country = input("What is the name of your country? ")
print("{}".format(country))
gender = input("What is your gender? ")
print("{}".format(gender))
mobileNumber = input("What is your mobile number? ")
print("{}".format(mobileNumber))
print(f"You are from {country}")
print("You are from {country}".format(country=country))
print("You are from {location}".format(location=country))
major = input("What is your major? ")
print("{}".format(major))
birthday = input("When is your birthday ")
print("{}".format(birthday))
instagram_username = input("What is your instagram username? ")
print("{}".format(instagram_username)) |
079d1c937ecee89c4b6a9f391fbb940cd29fc563 | Ghostpupper/adventofcode | /day12/day12.py | 1,683 | 3.734375 | 4 | from input_getter import get_input
class Boat:
def __init__(self):
self._dir_pointer = 0
self._dir_list = ['E', 'S', 'W', 'N']
self._facing = self._dir_list[self._dir_pointer]
self._dir_dist = {
'N': 0,
'S': 0,
'E': 0,
'W': 0
}
self.manhattan = self.manhattan_distance()
def move(self, letter, number: int):
"""
:param letter:
:param number:
:return:
"""
if letter == 'F':
self._dir_dist[self._facing] += number
print(f'{self._dir_dist}')
if letter == 'R':
steps = number / 90
self._dir_pointer = int((self._dir_pointer + steps) % 4)
self._facing = self._dir_list[self._dir_pointer]
print(f'Facing {self._facing}')
if letter == 'L':
steps = number / 90
p = int((self._dir_pointer - steps) % 4)
self._dir_pointer = p
self._facing = self._dir_list[int(self._dir_pointer)]
print(f'Facing {self._facing}')
if letter in self._dir_list:
self._dir_dist[letter] += number
print(f'{self._dir_dist}')
def manhattan_distance(self):
vertical = abs(self._dir_dist['N'] - self._dir_dist['S'])
horizontal = abs(self._dir_dist['W'] - self._dir_dist['E'])
self.manhattan = man = vertical + horizontal
return man
if __name__ == '__main__':
in_txt = get_input()
boat = Boat()
for inst in in_txt:
letter = inst[0]
num = int(inst[1:])
boat.move(letter, num)
print(boat.manhattan_distance())
|
038bf7be20d7ee9d1fc51cac0f64d80903956614 | Vcolvr/KenziePython | /Short_Long_Short.py | 158 | 3.53125 | 4 | def solution(a, b):
lengthA = len(a)
lengthB = len(b)
if lengthA > lengthB:
return b + a + b
else:
return a + b + a
|
32f2b29ec590f32ffb09a240ee8f8525fb32ca2e | Little-frog/python | /leecode/最长公共前缀.py | 476 | 3.53125 | 4 | def longestCommonPrefix(s):
'Written by myself'
if not s:
return ""
str0 = min(s)
str1 = max(s)
for i in range(len(str0)):
if str0[i] != str1[i]:
return str0[:i]
return str0
'Answer'
ans = ''
for i in zip(*s):
if len(set(i)) == 1:
ans += i[0]
else:
break
return ans
print(zip(*s))
result = longestCommonPrefix(["alower","awhtrht","alighthrth"])
# print(result)
|
0b912d49bbb2a83d04ce1e59a7f92d8be2b1064b | shinobu0831/python | /src/if.py | 713 | 3.890625 | 4 | #age = int(input('input age:'))
# if age < 18:
# print('no vote1')
# elif age < 20:
# print('no vote2')
# else:
# print('no vote3')
# 三項演算子
#print('A' if age < 10 else 'B')
# 内包表記
#data = [10**n for n in range(1, 11)]
# print(data)
# リスト[]:重複可、順序保持、変更可
listA = ['1', 2, 3, 4, 5, 6, 7, 7]
listA.append(8)
print(type(listA), listA)
# タプル():重複可、順序保持、変更不可
tupleA = ('1', 2, 3, 4, 5, 6, 7, 7)
print(type(tupleA), tupleA)
# セット{}:重複不可、順不同
setA = {'1', 2, 3, 4, 5, 6, 7, 7}
setA.add(8)
print(type(setA), setA)
# 辞書
dictA = {"name": "私", "age": "36"}
dictA['memo'] = 'hoge'
print(type(dictA), dictA)
|
9286688297bdf10c2c62c4c18a51d3c47fa4b8bc | daniel-reich/ubiquitous-fiesta | /WQjynmyMXcR83Dd8K_12.py | 1,209 | 3.78125 | 4 |
def swapPositions(list, pos1, pos2):
list[pos1],list[pos2] = list[pos2],list[pos1]
return list
def number_of_swaps(listOfNumbers):
currentNumber = 0
nextNumber = 0
count = 1
organizedListOfNumbers = []
numberOfSwaps = 0
for i in listOfNumbers:
organizedListOfNumbers.append(i)
organizedListOfNumbers.sort()
while listOfNumbers != organizedListOfNumbers:
for i in listOfNumbers:
currentNumber = i
indexOfCurrentNumber = listOfNumbers.index(i)
if listOfNumbers.index(currentNumber) != len(listOfNumbers)-1:
nextNumber = listOfNumbers[indexOfCurrentNumber+1]
indexOfNextNumber = listOfNumbers.index(nextNumber)
if count%2 == 1:
if currentNumber > nextNumber:
swapPositions(listOfNumbers, indexOfCurrentNumber, indexOfNextNumber)
numberOfSwaps += 1
elif count%2 == 0:
if currentNumber < nextNumber:
swapPositions(listOfNumbers, indexOfCurrentNumber, indexOfNextNumber)
numberOfSwaps += 1
return numberOfSwaps
|
0823df27de4215859751e960f2df4acd7a296b87 | mishrakeshav/Competitive-Programming | /SPOJ/BUGLIFE.py | 848 | 3.53125 | 4 | def dfs(node,c):
visited[node] = 1
color[node] = c
for nbr in graph[node]:
if visited[nbr]==0:
if not dfs(nbr,c^1):
return False
elif color[nbr] == color[node]:
return False
return True
for tt in range(int(input())):
n,m = map(int,input().split())
graph = dict()
for i in range(1,n+1):
graph[i] = []
visited = [0 for i in range(n+1)]
color = [0 for i in range(n+1)]
for _ in range(m):
u,v = map(int,input().split())
graph[u].append(v)
graph[v].append(u)
ans = True
for i in range(1,n+1):
if visited[i] == 0:
if not dfs(i,0):
ans = False
break
if ans:
print('No suspicious bugs found!')
else:
print('Suspicious bugs found!')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.