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
|
---|---|---|---|---|---|---|
b96ae4e7f1acb0878c2f22b576f72761266df319 | rutu342/PythonCodes | /basics6.py | 247 | 4.4375 | 4 | #to check weather an alphabet is capital or small
alpha=input("enter any alphabet")
if(alpha>='a' and alpha<='z'):
print(alpha,"is small")
elif(alpha>='A' and alpha<='Z'):
print(alpha,"is capital")
else:
print("Unknown value")
|
78de0f2d21e5a4479ed2de7ba1a5a21ee3ec3c91 | hoppfull/Learning-Python | /Advanced/design patterns1/ex08 - facade/main.py | 578 | 3.59375 | 4 | """Facade Design Pattern (Made in Python 3.4.3)
http://en.wikipedia.org/wiki/Facade_pattern
Very simple pattern. Already used it many times before. Didn't know it
was a common design pattern.
"""
class Part1:
def foo(self):
print("foo!")
class Part2:
def bar(self):
print("bar!")
class Part3:
def baz(self):
print("baz!")
class Facade:
def __init__(self):
self.p1 = Part1()
self.p2 = Part2()
self.p3 = Part3()
def start(self):
self.p1.foo()
self.p2.bar()
self.p3.baz()
if __name__ == "__main__": # Client code:
facade = Facade()
facade.start() |
c562724e98327da303f4c53d5b36eddb2741c8f4 | Svastikkka/DS-AND-ALGO | /Stack/Balanced Paranthesis 3.py | 1,081 | 3.890625 | 4 | "Implementation of stack using linked list "
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.size=0
def PushLL(self,arr):
NewNode=Node(arr)
NewNode.next=self.head
self.head=NewNode
self.size=self.size+1
def PopLL(self):
self.head=self.head.next
self.size=self.size-1
def BalancedParanthesis(str):
ll=LinkedList()
for i in str:
if i in "{[(":
ll.PushLL(i)
if i is ")":
if ll.size==0 or ll.head.data!="(":
return False
ll.PopLL()
if i is "}":
if ll.size==0 or ll.head.data!="{":
return False
ll.PopLL()
if i is i is "]":
if ll.size==0 or ll.head.data!="[":
return False
ll.PopLL()
if ll.size==0:
return True
return False
ele=input()
if BalancedParanthesis(ele):
print("true")
else:
print("false")
|
04540cbfb6e006155afd014dc36a123da1b265c2 | juanse962/analisis-numerico | /metodos/rule_false.py | 1,391 | 3.65625 | 4 | from sympy import *
import math
x = symbols('x')
function = (math.e**(3*x-12)) + x*cos(3*x)-x**2+4
xa= input("interval start: ")
xb = input("interval end: ")
tolerance = input("number of tolerance: ")
niter = input("number of iterations: ")
xa = float(xa)
xb = float(xb)
tolerance = float(tolerance)
niter = int(niter)
xm = 0
fxa = function.subs(x, xa)
fxb = function.subs(x, xb)
xm = xa -(function.subs(x, xa)*(xb-xa))/(function.subs(x, xb)-function.subs(x, xa))
fxm = function.subs(x,xm)
if fxa == 0:
print("{0} It's a root".format(xa))
elif fxb == 0:
print("{0} It's a root".format(xb))
elif fxa * fxb < 0:
xm = xa -(function.subs(x, xa)*(xb-xa))/(function.subs(x, xb)-function.subs(x, xa))
fxm = function.subs(x,xm)
count = 1
error = tolerance + 1
while (error > tolerance) and (fxm !=0) and (count < niter):
if fxa * fxm < 0:
xb = xm
else:
xa = xm
aux = xm
xm = xa -(function.subs(x, xa)*(xb-xa))/(function.subs(x, xb)-function.subs(x, xa))
fxm = function.subs(x,xm)
error = abs(xm-aux)
count += 1
if fxm == 0:
print("{0} It's a root".format(xm))
elif error < tolerance:
print("{0} approximately and a tolerance = {1}".format(xm,tolerance))
else:
print("Failure of the number of iterations")
else:
print("The interval is inadequate") |
432870120634e1d3c667bca146e26a06ea0a2147 | llh911001/leetcode-solutions | /reverse_words.py | 242 | 4.5 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
"""
def reverseWords(s):
return ' '.join(s.strip().split()[::-1])
|
085a9e058ba2a9a45ce93eea3385fb38b9c8c03f | sk055/Data-Structures-using-python | /Linear Data Structures/Array/02-Insertion.py | 260 | 4.03125 | 4 | from array import *
print("Insertion in array")
array_1 = array('i', [1,2,3,4,5]) #defining array
for k in array_1:
print(k)
print("\nResult\n")
array_1.insert(1,30)
for k in array_1: #Traversing array after insertion
print(k)
|
4b01e3d534b8e759950f81764bed268beed4992a | clydemichelle/automateboringstuffwithpython | /Part1_PythonBasics/Chapter4_Lists/commaCode.py | 219 | 4 | 4 | def delimit(someList):
for item in range(len(someList)-1):
print( someList[item] + ', ' , end = '')
print('and ' + someList[-1] + '.')
spam = ['apples', 'bananas', 'tofu', 'cats']
delimit(spam)
|
9d17cc734520ffe36cb94e3711e8c3192a6bc87c | wrapper228/RIP | /RIP_lab2/RIP_lab2/lab_python_oop/square.py | 454 | 3.65625 | 4 | from lab_python_oop.rectangle import Rectangle
from lab_python_oop.color import Color
class Square(Rectangle):
def __init__(self, name, x, color):
self.name = name
self.x = x
self.color = Color(color)
def area(self):
return self.x * self.x
def name(self):
return self.name
def __repr__(self):
return '{} {} {} {}'.format(self.name, self.x, self.color.c, self.area())
|
7c2d00c9c4b19a1f286a4e982571d3b9c90b69f3 | raghurammullapudi44/Mission-RnD | /PythonCourse/unit8_assignment_01.py | 2,697 | 3.75 | 4 | __author__ = 'Kalyan'
problem = """
We are going to revisit unit4 assignment2 for this problem.
Given an input file of words (mixed case). Group those words into anagram groups and write them
into the destination file so that words in larger anagram groups come before words in smaller anagram sets.
With in an anagram group, order them in case insensitive ascending sorting order.
If 2 anagram groups have same count, then set with smaller starting word comes first.
For e.g. if source contains (ant, Tan, cat, TAC, Act, bat, Tab), the anagram groups are (ant, Tan), (bat, Tab)
and (Act, cat, TAC) and destination should contain Act, cat, TAC, ant, Tan, bat, Tab (one word in each line).
the (ant, Tan) set comes before (bat, Tab) as ant < bat.
At first sight, this looks like a big problem, but you can decompose into smaller problems and crack each one.
This program should be written as a command line script. It takes one argument the input file of words and outputs
<input>-results.txt where <input>.txt is the input file of words.
"""
import sys
import unit4utils
def main():
input = unit4utils.open_input_file("unit4_testinput_02.txt")
load_words(input)
def load_words(input):
all_words=[]
for x in input.readlines():
if x[0]!='#' and x[0]!=' ' and x[0]!='\n':
all_words.append(x.strip())
input.close()
anagram_sort(all_words)
def anagram_sort(all_words):
parent_anagrams=list(set(''.join(sorted(x.lower())) for x in all_words))
values=[range(0) for x in range(len(parent_anagrams))]
anagram_dictionary=dict(zip(parent_anagrams,values))
for x in all_words:
parent_anagram_word=''.join(sorted(x.lower()))
if parent_anagram_word in anagram_dictionary.keys():
anagram_dictionary[parent_anagram_word].append(x)
sort_case_insencitive(anagram_dictionary.values())
def sort_case_insencitive(anagram_groups):
for x in anagram_groups:
x.sort(key=lambda x:x.lower())
arrange_dec_ties_asc(anagram_groups)
def arrange_dec_ties_asc(anagram_groups):
anagram_groups.sort(key=sort_key)
write_to_result(anagram_groups)
def sort_key(item):
# descending by group length, ascending by first word in case of tie
return -len(item),item[0].lower()
def write_to_result(anagram_groups):
result = unit4utils.get_temp_file("result.txt")
result=unit4utils.open_temp_file("result.txt","wb")
for x in anagram_groups:
for y in range(len(x)):
result.writelines(x[y]+'\n')
result.close()
if __name__ == "__main__":
main()
#sys.exit(main()) |
399fe939bbcd2536b335a541b3b128ffdfee92d9 | romulorm/cev-python | /ex.081.extraindoDadosDeLista.py | 483 | 3.78125 | 4 | lista = []
opcao = 'S'
cont = 0
while opcao == 'S':
lista.append(int(input('Digite um valor: ')))
opcao = str(input('Deseja continuar? ')).upper().strip()[0]
cont += 1
lista.sort(reverse=True)
print('Você digitou \033[33m{}\033[m elementos.'.format(cont))
print('Os valores em ordem decrescente são: \033[33m{}\033[m'.format(lista))
if 5 in lista:
print('O número \033[33m5\033[m está na lista.')
else:
print('O número \033[33m5\033[m NÃO está na lista.') |
7c059b74297779b7355bee833b987706147cc414 | WalczRobert/module-4 | /input_validation/validation_with_try.py | 794 | 3.9375 | 4 |
class Testscores():
def input(self):
score1, score2, score3 = input("what are your 3 scores (comma separated): ").split(',')
average(score1, score2, score3)
def average(self, score1, score2, score3):
NUMBER_TESTS = 3
score = float((score1 + score2 + score3) / NUMBER_TESTS)
try:
if self.score1 < 0:
raise ValueError('Invalid score value')
if self.score2 < 0:
raise ValueError('Invalid score value')
if self.score3 < 0:
raise ValueError('Invalid score value')
except:
print('except - Invalid score value')
else:
print (score)
return score
if __name__ == '__main__':
input() |
d0d034c5951602144957579283ea58119790469f | ryanmp/cs325 | /hw3/algo_mst.py | 1,596 | 3.515625 | 4 | import itertools
from tree import *
from helpers import *
import time
#minimum spanning tree
#input: list of cities
#output: tree representation of edges for MST -> traversal -> route
#@profile
def algo_mst(cities):
all_edges = set() #(cityA,cityB,distance)
# setting up our city-set as a set of edges
for idx1 in xrange(len(cities)):
for idx2 in range(idx1+1,len(cities)):
new = (idx1,idx2,distance(cities[idx1],cities[idx2]))
all_edges.add(new)
# vertices
v_not_in_tree = set([i for i in xrange(len(cities))])
# just pick a starting node...
v_in_tree = set([0])
tree=Node('0')
while (len(v_not_in_tree) > 1):
# set of edges connected to the nodes of our tree (but not already in tree)
possible_new_edges = []
for v in v_in_tree:
filter_result = filter(
lambda x: ((x[1] == v or x[0] == v)
and not( x[0] in v_in_tree and x[1] in v_in_tree)) ,
all_edges)
possible_new_edges.append( filter_result )
possible_new_edges = list(itertools.chain(*possible_new_edges)) #flatten 2d list to 1d
# which edge has the minimum weight?
next_edge = min(possible_new_edges, key = lambda t: t[2])
# is arg0 or arg1 the new node?
# let's add this new edge to the tree while we are at it
if (next_edge[0] in v_in_tree):
v = next_edge[1]
tree.add_child2(str(next_edge[0]),str(next_edge[1]))
else:
v = next_edge[0]
tree.add_child2(str(next_edge[1]),str(next_edge[0]))
all_edges.remove(next_edge)
v_in_tree.add(v)
v_not_in_tree.remove(v)
# pre order trav that shit and we are done
return map(int,pre_order_trav(tree))
|
66797d257df4a07829848afeb58cbd5694700211 | frankzappasmustache/IT121_Python | /assignments/Lab_3a_usingStrings/fuckstrings.py | 3,730 | 3.875 | 4 | """
Project Name: IT121_Python
Sub-project: Labs
File Name: fuckstrings.py
Author: Dustin McClure
Lab: Lab 3a - Using Strings
Modified Date: 10/10/2020
A program that formats and prints responses from the
foaas api (Fuck off as a Service); an api that allows
you to very efficiently tell someone or something to
'fuck off'.
"""
# import the Fuck class from the foaas module
from foaas import Fuck
# create a new instance of the class Fuck
fuck = Fuck()
# set variables for the current lab and number of fuck operations
lab_three = 3
fuck_amount = 4
# print a fucking explanation of what this program accomplishes
# using string modulo operators %d (digit), %s (string), and
# %f (floating point) to embed values
print('''Today, for lab %da, we will be exploring precisely %.1f
of the many satisfying ways one can use %s off as a service to
simplify the action of telling someone to %s off. \n
''' % (lab_three, fuck_amount, 'fuck','fuck'))
print("=====================================================================\n")
# assign response value of fuck.asshole action to var asshole
asshole = fuck.asshole(from_='Dustin').text
# create string slices of string stored in asshole and assign
# them to variables that can more easily be formatted
asshole_one = asshole[0:18]
asshole_two = asshole[19:28]
# format our slice variables into a multiline string stored
# in its own variable
total_asshole = '''\
{x}
Sincerely,
{y}\
'''.format(x=asshole_one, y=asshole_two)
# print our newly formatted multiline string and add an
# additional newline
print(total_asshole + '\n')
print("=====================================================================\n")
# assign response value of fuck.off_with action to var fuck_array_shaming
fuck_array_shaming = fuck.off_with(behavior="that strict programming dogma.", from_="Dustin").text
# print the string stored in var fuck_array_shaming and add an
# additional newline
print(fuck_array_shaming + '\n')
print("=====================================================================\n")
# assign response value of fuck.caniuse action to var big_fucking_hammer
# escaping out special characters so they print
big_fucking_hammer = fuck.caniuse(tool="the \'BFH\' (big fucking hammer)", from_="Dustin")
# print string stored in nvar big_fucking_hammer and remove newline
# with end=""; adding a little extra at the end so we know who
# keeps the BFH
print(big_fucking_hammer.text, end="")
print(" (keeper of the BFH)" + '\n')
print("=====================================================================\n")
# assign response value of fuck.particular action to var
# recursion_fuck, and multiply our arg string for thing
# by 5 so we can simulate mild recursion in our print statement
recursion_fuck = fuck.particular(thing="recursion loop" * 5, from_="Dustin").text
# create string slices of string stored in recursion_fuck
# and assign them to variables that can more easily be formatted
fuck_this = recursion_fuck[0:9]
recursion_one = recursion_fuck[9:24]
recursion_two = recursion_fuck[24:38]
recursion_three = recursion_fuck[38:52]
recursion_four = recursion_fuck[52:66]
recursion_five = recursion_fuck[66:80]
in_particular = recursion_fuck[80:94]
my_name = recursion_fuck[95:109]
# store formatted multiline string in fuckery variable
fuckery = '''\
{a}
{b}
{c}
{d}
{e}
{f}
{g}.
{h}\
'''.format(a=fuck_this, b=recursion_one, c=recursion_two,
d=recursion_three, e=recursion_four, f=recursion_five, g=in_particular, h=my_name)
# print multiline string stored in fuckery
print(fuckery)
|
2cdda1eeae90c75c08b3fc09017b3de853192473 | Shivani161992/Leetcode_Practise | /Backtracking/WordSearch.py | 1,541 | 3.578125 | 4 | from typing import List
word = "AAB"
board =[["C","A","A"],["A","A","A"],["B","C","D"]]
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
row=len(board)
col=len(board[0])
index=0
hold=''
for r in range(0, row):
for c in range(0, col):
if board[r][c]==word[index]:
found = self.search(board, word, hold, index, r, c)
if found == True:
return True
return False
def search(self, board, word, hold, index, r, c):
if r >= 0 and r < len(board) and c >= 0 and c < len(board[0]) and index < len(word):
if board[r][c] == word[index]:
hold = hold + board[r][c]
store = board[r][c]
board[r][c] = 0
if word == hold:
return True
right = self.search(board, word, hold, index + 1, r, c + 1)
left = self.search(board, word, hold, index + 1, r, c - 1)
bottom = self.search(board, word, hold, index + 1, r + 1, c)
top = self.search(board, word, hold, index + 1, r - 1, c)
if right == True or left == True or top == True or bottom == True:
return True
else:
board[r][c] = store
return False
else:
return False
else:
return False
obj=Solution()
print(obj.exist(board, word))
|
3633a524bdc19fbfc4e83931838f10c995a1a069 | DamonLiuTHU/LeetCode_Python | /max_points_on_line.py | 2,391 | 3.53125 | 4 | # Definition for a point.
class Point(object):
def __init__(self, a=0, b=0):
self.x = a
self.y = b
class Solution(object):
def same_line(self, A, B, C):
if A[0] == B[0] and A[1] == B[1] or A[0] == C[0] and A[1] == B[1] \
or C[0] == B[0] and C[1] == B[1]:
return True
if A[0] == B[0]:
return A[0] == C[0]
if A[1] == B[1]:
return A[1] == C[1]
a = float(C[1] - A[1]) * (B[0] - A[0])
b = float(B[1] - A[1]) * (C[0] - A[0])
return a == b
def maxPoints(self, points):
"""
:type points: List[Point]
:rtype: int
"""
p_list = [[point.x, point.y] for point in points]
point2count = dict()
for point in p_list:
point2count[str(point)] = point2count.get(str(point), 0) + 1
p_set = point2count.keys()
if len(points) <= 2:
return len(points)
MAX = 2
for i in range(len(points)):
for j in range(i + 1, len(points)):
A = points[i]
B = points[j]
count = point2count.get(str(A)) + point2count.get(str(B))
print('=======================================================')
print('point (%d,%d) and point (%d,%d) :' % (p_list[i][0],
p_list[i][1],
p_list[j][0],
p_list[j][1]))
for k in range(j + 1, len(points)):
if self.same_line(p_list[i],
p_list[j],
p_list[k]):
count += point2count.get()
MAX = max(MAX, count)
print('=======================================================')
return MAX
t_input = [[0, 9], [138, 429], [115, 359], [115, 359], [-30, -102], [230, 709],
[-150, -686], [-135, -613], [-60, -248], [-161, -481], [207, 639],
[23, 79],
[-230, -691], [-115, -341], [92, 289], [60, 336], [-105, -467],
[135, 701],
[-90, -394], [-184, -551], [150, 774]]
s = Solution()
points = [Point(i[0], i[1]) for i in t_input]
print s.maxPoints(points)
|
dee05afe21f1e054151d13dc6bedebbcd20b9735 | lsylk/practice | /skills.py | 13,013 | 4.75 | 5 | """Skills Assessment: Lists
Edit the function bodies until all of the doctests pass when
you run this file.
"""
def print_list(items):
"""Print each item in the input list.
For example::
>>> print_list([1, 2, 6, 3, 9])
1
2
6
3
9
"""
for item in items:
print item
def all_odd(numbers):
"""Return a list of only the odd numbers in the input list.
For example::
>>> all_odd([1, 2, 7, -5])
[1, 7, -5]
>>> all_odd([2, -6, 8])
[]
"""
odd_nums = []
for num in numbers:
if num % 2 != 0:
odd_nums.append(num)
return odd_nums
def all_even(numbers):
"""Return a list of only the even numbers in the input list.
For example::
>>> all_even([2, 6, -1, -2])
[2, 6, -2]
>>> all_even([-1, 3, 5])
[]
"""
even_nums = []
for num in numbers:
if num % 2 == 0:
even_nums.append(num)
return even_nums
def every_other_item(items):
"""Return every other item in `items`, starting at first item.
For example::
>>> every_other_item([1, 2, 3, 4, 5, 6])
[1, 3, 5]
>>> every_other_item(
... ["you", "z", "are", "z", "good", "z", "at", "x", "code"]
... )
['you', 'are', 'good', 'at', 'code']
"""
odd_items = []
for i in range(len(items)):
if i % 2 == 0:
odd_items.append(items[i])
return odd_items
def print_indexes(items):
"""Print index of each item in list, followed by item itself.
Do this without using a "counting variable" --- that is, don't
do something like this::
count = 0
for item in list:
print count
count = count + 1
Output should look like this::
>>> print_indexes(["Toyota", "Jeep", "Volvo"])
0 Toyota
1 Jeep
2 Volvo
"""
for i in range(len(items)):
print "%i %s" % (i, items[i])
def long_words(words):
"""Return words in input list that longer than 4 characters.
For example::
>>> long_words(["hello", "a", "b", "hi", "bacon", "bacon"])
['hello', 'bacon', 'bacon']
(If there are duplicates, show both --- notice "bacon" appears
twice in output)
If no words are longer than 4 characters, return an empty list::
>>> long_words(["all", "are", "tiny"])
[]
"""
# long_words = []
# for word in words:
# if len(word) > 4:
# long_words.append(word)
# return long_words
return [word for word in words if len(word) > 4] # list comprehension
def n_long_words(words, n):
"""Return words in list longer than `n` characters.
For example::
>>> n_long_words(
... ["hello", "hey", "spam", "spam", "bacon", "bacon"],
... 3
... )
['hello', 'spam', 'spam', 'bacon', 'bacon']
>>> n_long_words(["I", "like", "apples", "bananas", "you"], 5)
['apples', 'bananas']
"""
return [word for word in words if len(word) > n]
def smallest_int(numbers):
"""Find the smallest integer in a list of integers and return it.
**DO NOT USE** the built-in function `min()`!
For example::
>>> smallest_int([-5, 2, -5, 7])
-5
>>> smallest_int([3, 7, 2, 8, 4])
2
If the input list is empty, return `None`::
>>> smallest_int([]) is None
True
"""
if numbers != []:
min_num = numbers[0]
for num in numbers:
if num < min_num:
min_num = num
return min_num
elif numbers is None:
return True
def largest_int(numbers):
"""Find the largest integer in a list of integers and return it.
**DO NOT USE** the built-in function `max()`!
For example::
>>> largest_int([-5, 2, -5, 7])
7
>>> largest_int([3, 7, 2, 8, 4])
8
If the input list is empty, return None::
>>> largest_int([]) is None
True
"""
if numbers != []:
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
elif numbers is None:
return True
def halvesies(numbers):
"""Return list of numbers from input list, each divided by two.
For example::
>>> halvesies([2, 6, -2])
[1.0, 3.0, -1.0]
If any of the numbers are odd, make sure you don't round off
the half::
>>> halvesies([1, 5])
[0.5, 2.5]
"""
halvesies = []
for num in numbers:
halvesy = num / 2.0
halvesies.append(halvesy)
return halvesies
def word_lengths(words):
"""Return the length of words in the input list.
For example::
>>> word_lengths(["hello", "hey", "hello", "spam"])
[5, 3, 5, 4]
"""
words_length = []
for word in words:
length = len(word)
words_length.append(length)
return words_length
def sum_numbers(numbers):
"""Return the sum of all of the numbers in the list.
Python has a built-in function, `sum()`, which already does
this --- but for this exercise, you should not use it.
For example::
>>> sum_numbers([1, 2, 3, 10])
16
Any empty list should return the sum of zero::
>>> sum_numbers([])
0
"""
if numbers == []:
return 0
else:
total = 0
for num in numbers:
total += num
return total
def mult_numbers(numbers):
"""Return product (result of multiplication) of numbers in list.
For example::
>>> mult_numbers([1, 2, 3])
6
Obviously, if there is a zero in input, the product is zero::
>>> mult_numbers([10, 20, 0, 50])
0
As explained at http://en.wikipedia.org/wiki/Empty_product,
if the list is empty, the product should be 1::
>>> mult_numbers([])
1
"""
total = 1
for num in numbers:
total *= num
return total
def join_strings(words):
"""Return a string of all input strings joined together.
Python has a built-in method, `list.join()` --- but for
this exercise, **you should not use it**.
For example::
>>> join_strings(["spam", "spam", "bacon", "balloonicorn"])
'spamspambaconballoonicorn'
For an empty list, you should return an empty string::
>>> join_strings([])
''
"""
joined_words = ""
for word in words:
joined_words += word
return joined_words
def average(numbers):
"""Return the average (mean) of the list of numbers given.
For example::
>>> average([2, 4])
3.0
This should handle cases where the result isn't an integer::
>>> average([2, 12, 3])
5.666666666666667
There is no defined answer if the list given is empty;
it's fine if this raises an error when given an empty list.
(Think of the best way to handle an empty input list, though,
a feel free to provide a good solution here.)
"""
sum_numbers = 0
for num in numbers:
sum_numbers += num
average_total = float(sum_numbers) / len(numbers)
return average_total
def join_strings_with_comma(words):
"""Return ['list', 'of', 'words'] like "list, of, words".
For example::
>>> join_strings_with_comma(
... ["Labrador", "Poodle", "French Bulldog"]
... )
'Labrador, Poodle, French Bulldog'
If there's only one thing in the list, it should return just that
thing, of course::
>>> join_strings_with_comma(["Pretzel"])
'Pretzel'
"""
words_string = ""
for word in words:
if word == words[(len(words) - 1)]:
words_string += word
else:
words_string += word + ", "
return words_string
def foods_in_common(foods1, foods2):
"""Find foods in common.
Given 2 lists of foods, return the items that are in common
between the two, sorted alphabetically.
**NOTE**: for this problem, you're welcome to use any of the
Python data structures you've been introduced to (not just
lists). Is there another that would be a good idea?
For example::
>>> foods_in_common(
... ["cheese", "bagel", "cake", "kale"],
... ["hummus", "beets", "bagel", "lentils", "kale"]
... )
['bagel', 'kale']
If there are no foods in common, return an empty list::
>>> foods_in_common(
... ["lamb", "chili", "cheese"],
... ["cake", "ice cream"]
... )
[]
"""
foods1 = set(foods1)
foods2 = set(foods2)
foods = foods1.intersection(foods2)
return [food for food in foods]
def reverse_list(items):
"""Return the input list, reversed.
**Do not use** the python function `reversed()` or the method
`list.reverse()`.
For example::
>>> reverse_list([1, 2, 3])
[3, 2, 1]
>>> reverse_list(["cookies", "love", "I"])
['I', 'love', 'cookies']
You should do this without changing the original list::
>>> orig = ["apple", "berry", "cherry"]
>>> reverse_list(orig)
['cherry', 'berry', 'apple']
>>> orig
['apple', 'berry', 'cherry']
"""
return [items[(- i - 1)] for i in range(len(items))]
def reverse_list_in_place(items):
"""Reverse the input list `in place`.
Reverse the input list given, but do it "in place" --- that is,
do not create a new list and return it, but modify the original
list.
**Do not use** the python function `reversed()` or the method
`list.reverse()`.
For example::
>>> orig = [1, 2, 3]
>>> reverse_list_in_place(orig)
>>> orig
[3, 2, 1]
>>> orig = ["cookies", "love", "I"]
>>> reverse_list_in_place(orig)
>>> orig
['I', 'love', 'cookies']
"""
for i in range(len(items)/2):
items[0], items[-1-i] = items[-1-i], items[0]
def duplicates(items):
"""Return list of words from input list which were duplicates.
Return a list of words which are duplicated in the input list.
The returned list should be in ascending order.
For example::
>>> duplicates(
... ["apple", "banana", "banana", "cherry", "apple"]
... )
['apple', 'banana']
>>> duplicates([1, 2, 2, 4, 4, 4, 7])
[2, 4]
You should do this without changing the original list::
>>> orig = ["apple", "apple", "berry"]
>>> duplicates(orig)
['apple']
>>> orig
['apple', 'apple', 'berry']
"""
word_count = {}
for item in items:
if item not in word_count:
word_count[item] = 1
else:
word_count[item] += 1
duplicates = []
for word in word_count:
if word_count[word] > 1:
duplicates.append(word)
return duplicates
def find_letter_indices(words, letter):
"""Return list of indices where letter appears in each word.
Given a list of words and a letter, return a list of integers
that correspond to the index of the first occurrence of the letter
in that word.
**DO NOT** use the `list.index()` method.
For example::
>>> find_letter_indices(['odd', 'dog', 'who'], 'o')
[0, 1, 2]
("o" is at index 0 in "odd", is at index 1 in "dog", and at
index 2 in "who")
If the letter doesn't occur in one of the words, use `None` for
that word in the output list. For example::
>>> find_letter_indices(['odd', 'dog', 'who', 'jumps'], 'o')
[0, 1, 2, None]
("o" does not appear in "jumps", so the result for that input is
`None`.)
"""
indices = []
for word in words:
if letter in word:
for i in range(len(word)):
if word[i] == letter:
indices.append(i)
else:
indices.append(None)
return indices
def largest_n_items(itemst, n):
"""Return the `n` largest integers in list, in ascending order.
You can assume that `n` will be less than the length of the list.
For example::
>>> largest_n_items([2, 6006, 700, 42, 6, 59], 3)
[59, 700, 6006]
It should work when `n` is 0::
>>> largest_n_items([3, 4, 5], 0)
[]
If there are duplicates in the list, they should be counted
separately::
>>> largest_n_items([3, 3, 3, 2, 1], 2)
[3, 3]
"""
return sorted((sorted(itemst))[-1:-1-n:-1])
#####################################################################
# Test all functions.
if __name__ == "__main__":
import doctest
print
result = doctest.testmod()
if not result.failed:
print "ALL TESTS PASSED!"
print
|
87ec7684d139e9ade08cc37ae54bf0ffe1546ed1 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/mntdom001/mymath.py | 1,386 | 4.15625 | 4 | # mymath.py
# a module that contains the functions get_integer() which prompts the user to
# enter numbers and the function calc_factorial which determines the
# factorial of the two digits entered by the user
# Author: Dominic Manthoko
# 13 April 2014
def get_integer(s):
""" this function will prompt the user to enter a number. The number
will either be the number of items to choose from, n, or the number of
items that are chosen, k"""
# this will happen if we are asking the user for the number of items, n,
# which they can choose
if s == "n":
n = input ("Enter n:\n")
while not n.isdigit ():
n = input ("Enter n:\n")
n = eval (n)
return n
# this will happen if we are asking the user for the number of items, k,
# that are choosen
elif s =="k":
k = input ("Enter k:\n")
while not k.isdigit ():
k = input ("Enter k:\n")
k = eval (k)
return k
def calc_factorial(x):
""" this funtion will determine the factorial of the parameter x and
return the answer of the factorial of x"""
# initialize the factorial to 1
nfactorial = 1
# this loop will determine the factorial of x
for i in range (1, x+1):
nfactorial *= i
return nfactorial
|
6c3b12452a72b7277287b6b55f5318788ac7cb9c | SurajPatil314/Leetcode-problems | /Binary Tree/BST_preorder_iterative.py | 680 | 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 preorderTraversal(self, root: TreeNode) -> List[int]:
ans = []
if not root:
return ans
qw = []
qw.append(root)
while (len(qw) > 0):
zx = qw.pop(0)
ans.append(zx.val)
if zx.left:
qw.insert(0, zx.left)
if zx.right:
if not zx.left:
qw.insert(0, zx.right)
else:
qw.insert(1, zx.right)
return ans
|
06ea8f2e412fc018628f4d1cb75441e1c0ccc85b | ReCir0/UCU_Programming | /Lab5/continuation.py | 2,622 | 3.84375 | 4 | def calculate_expression(expression):
'''
>>> calculate_expression("Скільки буде 8 відняти 3?")
5
>>> calculate_expression("Скільки буде 7 додати 3 помножити на 5?")
50
>>> calculate_expression("Скільки буде 10 поділити на -2 додати 11 мінус -3?")
9
>>> calculate_expression("Скільки буде 3 в кубі?")
'Неправильний вираз!'
'''
try:
numbers = []
actions = []
expression = expression[13:len(expression)]
i = 0
num_1 = ""
while True:
if expression[i] == "?":
return int(num_1)
if expression[i] == " ":
break
num_1 += expression[i]
i += 1
expression = expression[len(num_1) + 1:len(expression)]
num_1 = int(num_1)
numbers.append(num_1)
while True:
i = 0
action = ""
while True:
if expression[i] == " ":
if expression[i + 1] != "н":
break
action += expression[i]
i += 1
actions.append(action)
expression = expression[len(action) + 1:len(expression)]
i = 0
num_2 = ""
while expression[i] != " " and expression[i] != "?":
num_2 += expression[i]
i += 1
numbers.append(int(num_2))
if expression[i] == " ":
expression = expression[len(num_2) + 1:len(expression)]
else:
break
result = numbers[0]
len_actions = len(actions)
for i in range(len_actions):
if actions[i] == "плюс" or actions[i] == "додати":
result = result + numbers[i + 1]
elif actions[i] == "мінус" or actions[i] == "відняти":
result = result - numbers[i + 1]
elif actions[i] == "помножити на":
result = result * numbers[i + 1]
elif actions[i] == "поділити на":
if result % numbers[i + 1] == 0:
result = int(result / numbers[i + 1])
else:
result = result / numbers[i + 1]
else:
return 'Неправильний вираз!'
return result
except:
return 'Неправильний вираз!'
print(calculate_expression('Скільки буде 10 розділити на 2?')) |
7358b9bdbf0bc76efe9304a101aada4e3d9d2d4c | willson310116/ML-Practice | /Neural Network/text_classification_imdb/load_data_pipe.py | 2,824 | 3.984375 | 4 | s = """
These line is just for testing of loading data with different imput forms.
For example, content with empty lines, not like others with sentence stick together which is kind of results after processing.
As a result, these lines I type are seperate with empty lines.
"""
def Remove_space(s):
"""
Modifying multiple lines string into one string with a proper form
"""
result = list(s.strip())
# print(result,"\n")
for i in range(len(result)):
if result[i] == '\n':
result[i] = " "
result = "".join(result)
result = result.replace(".", "").replace(",", "").replace("(", "").replace(")", "").replace(":", "").replace("\n", "").replace("\"", "").split(" ")
result = list(filter(("").__ne__, result))
return result
# print(s)
# s = input("Type some sentence:\n")
s = """
Its one hell of a complicated film. It will be very hard for an average viewer to gather all the information provided by this movie at the first watch. But the more you watch it, more hidden elements will come to light. And when you are able to put these hidden elements together. You will realize that this movie is just a "masterpiece" which takes the legacy of Christopher Nolan Forward
If I talk about acting, Then I have to say that Robert Pattinson has really proved himself as a very good actor in these recent years. And I am sure his acting skills will increase with time. His performance is charming and very smooth. Whenever he is on the camera, he steals the focus John David Washington is also fantastic in this movie. His performance is electrifying, I hope to see more from him in the future. Other characters such as Kenneth Branagh, Elizabeth, Himesh Patel, Dimple Kapadia, Clémence Poésy have also done quite well. And I dont think there is a need to talk about Michael Caine
Talking about Music, its awesome. I dont think you will miss Hans Zimmer's score. Ludwig has done a sufficient job. There is no lack of good score in the movie
Gotta love the editing and post production which has been put into this movie. I think its fair to say this Nolan film has focused more in its post production. The main problem in the movie is the sound mixing. Plot is already complex and some dialogues are very soft due to the high music score. It makes it harder to realize what is going on in the movie. Other Nolan movies had loud BGM too. But Audio and dialogues weren't a problem
My humble request to everyone is to please let the movie sink in your thoughts. Let your mind grasp all the elements of this movie. I am sure more people will find it better. Even those who think they got the plot. I can bet they are wrong.
"""
# print(s)
print("\n")
# print(Remove_space(s))
filename = "load.txt"
with open(filename, encoding="utf-8") as f:
content = f.read()
print(content)
print(type(content))
print(Remove_space(content))
|
fb1f2fc82d4dd8a44de4aa798b58b09beab9b55f | syuanivy/ADBS | /board.py | 2,086 | 4.09375 | 4 | from error import Error
class Board:
"""
Representation of ships and their positions on a map.
"""
def __init__(self, xsize, ysize):
"""
Create a rectangular board with integer coordinates that range from
(0, 0) to (xsize-1, ysize-1).
"""
xsize = int(xsize)
ysize = int(ysize)
if xsize < 0 or ysize < 0:
raise ValueError("Invalid board size: %s", ((xsize, ysize),))
self.xsize = xsize
self.ysize = ysize
self._grid = [[None for y in range(ysize)] for x in range(xsize)]
self.numOfShips = 0
def add_ship(self, ship):
"""
Add a ship to the board. Raises an IndexError if the ship falls out of
bounds.
"""
if ship.x < 0 or ship.x >= self.xsize or ship.y < 0 or ship.y >= self.ysize:
raise IndexError("Ship start position is not on board: %s" % ((ship.x, ship.y),))
for x,y in ship.get_coordinates():
if self.query_coordinate(x, y):
raise Error(Error.ERR_SHIP_COLLIDE)
# Start with highest coordinate to get IndexError if out of bounds
for x, y in reversed(sorted(ship.get_coordinates())):
self._grid[x][y] = ship
self.numOfShips += 1
def query_coordinate(self, x, y):
"""
Returns the ship that exists at the (x, y) coordinate on the board or
None if there is no ship. Raises an IndexError if the coordinates fall
out of bounds or a ValueError if the coordinates are not valid.
"""
x = int(x)
y = int(y)
if x < 0 or x >= self.xsize or y < 0 or y >= self.ysize:
raise IndexError("Position is not on board: %s" % ((x, y),))
return self._grid[x][y]
def has_ship(self, x, y):
return self._grid[x][y] is not None
def sink_ship(self, x, y):
ship = self._grid[x][y]
if ship is not None:
for x, y in reversed(sorted(ship.get_coordinates())):
self._grid[x][y] = None
self.numOfShips -= 1
|
cf1832eab913eb23db959fb17d5ecf75a890d1cb | axelFrias1998/CrashCourseOnPythonExercises | /Fourth week/Lists/Lists and tuples/listsAndTuples.py | 375 | 3.875 | 4 | fullname = ("Grace", "M", "Hopper")
def convert_seconds(seconds):
hours = seconds // 3600
minutes = (seconds - hours * 3600) // 60
remaining_seconds = seconds - hours * 3600 - minutes * 60
return hours, minutes, remaining_seconds
hours, minutes, remaining_seconds = convert_seconds(2000)
print(hours, minutes, remaining_seconds, type(convert_seconds(200)))
|
55cd06180a315b6a57eab6148d6c966afec1cd31 | paul0920/leetcode | /question_leetcode/200_5.py | 1,320 | 3.5 | 4 | import collections
def numIslands(grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
visited = set()
count = 0
for i in range(m):
for j in range(n):
if not is_valid(i, j, visited, grid):
continue
visited.add((i, j))
bfs(i, j, visited, grid)
count += 1
return count
def is_valid(y, x, visited, grid):
if (y, x) in visited:
return False
if y < 0 or y >= len(grid) or x < 0 or x >= len(grid[0]):
return False
if grid[y][x] == "0":
return False
return True
def bfs(y, x, visited, grid):
DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
queue = collections.deque()
queue.append((y, x))
while queue:
curr_y, curr_x = queue.popleft()
for dy, dx in DIRECTIONS:
next_y, next_x = curr_y + dy, curr_x + dx
if not is_valid(next_y, next_x, visited, grid):
continue
visited.add((next_y, next_x))
queue.append((next_y, next_x))
grid = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
]
print numIslands(grid)
|
9621fc0a4ce47d47a143085c99581a10d2f43a23 | staypuffinpc/IPT760-F19 | /Day6/BS2.py | 1,889 | 4.03125 | 4 | htmlDoc = """<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
### Beautiful Soup ###
## import the Library
from bs4 import BeautifulSoup
## creating an an instance of the Beautiful Soup class
soup = BeautifulSoup(htmlDoc, "html.parser")
### Navigating the Tree ###
## Going down
# using tag names
tag = soup.p.b
# print(tag)
# .contents and .children
bodyTag = soup.body
# print(bodyTag.contents)
# for child in bodyTag.children:
# print(child)
# # .descendants
# print(len(list(soup.children)))
# print(len(list(soup.descendants)))
# .string, .strings, and .strippped_strings
titleTag = soup.title
# print(titleTag.string)
#
# headTag = soup.head
# print(headTag)
# print(headTag.string)
#
# for string in soup.stripped_strings:
# print(repr(string))
## Going up
# .parent
# print(titleTag.parent)
# # .parents
aTag = soup.a
# for parent in aTag.parents:
# print(parent.name)
## Going sideways
# .next_sibling and .previous_sibling
# pTag = soup.p
# print(pTag)
# print(pTag.next_sibling.next_sibling.previous_sibling)
#
# # .next_siblings and .previous_siblings
# for sibling in aTag.next_siblings:
# print(repr(sibling))
## Going back and forth
# .next_element and .previous_element
print(aTag.next_element)
print(aTag.previous_element)
# .next_elements and .previous_elements
for element in aTag.next_elements:
print(repr(element))
|
2ad00cbdfec5879cc5a37637677b7c4af2569b85 | fore0919/wecode | /test.py | 154 | 3.765625 | 4 | numbers = []
def even():
for num in range(1,51):
if num % 2 == 0:
numbers.append(num)
print(numbers)
return numbers
even() |
1ea3c1c6ca426059b6edb8e1c419c60a71c9694c | ChicksMix/programing | /unit 5/DiamondHicks.py | 561 | 4.03125 | 4 | b=int(input("Enter the number of symbols to be used in the base: "))
b2= b-2
for n in range(1,b+1,2): # counting by two to add the next line
space=1
while space <=int((b-n)/2):
print " ",
space+=1
for x in range (1,n+1):
if x < n:
print str("*"),
else:
print str("*")
for s in range(b2,0,-2):
space2=b2
while space2 >=int((b2+s)/2):
print " ",
space2-=1
for p in range(1,s+1):
if p < s:
print str("*"),
else:
print str("*")
|
878946aa603a7765250277475bc3c013451dbb5b | septyanra/labpy03 | /Latihan2.py | 245 | 4 | 4 | print("Program Menampilkan Bilangan Terbesar dari Bilangan n")
n = 1
max = 0
while n !=0:
if n > max:
max = n
n = int(input("Masukkan bilangan : "))
if n == 0:
break
print("Nilai terbesar adalah : ", max)
|
4ba6433cbda78be78d414ba66c42529616a49eec | db2398/nwe | /10.py | 72 | 3.546875 | 4 | num=int(input())
c=0
while(num>0):
num=num//10
c=c+1
print("%d"%c)
|
9e6e69b3d95805c44a3e69332a61db37489064b9 | xy2333/Leetcode | /leetcode/PrintFromTopToBottomAsZ.py | 784 | 3.53125 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x,left = None,right = None):
self.val = x
self.left = left
self.right = right
class Solution:
def __init__(self):
self.stack = []
self.res = [[]]
def Print(self, pRoot):
# write code here
if pRoot is not None:
self.stack.append(pRoot)
now = 1
last = 0
while len(self.stack) != 0:
temp = self.stack.pop(0)
now -= 1
self.res[-1].append(temp.val)
if temp.left is not None:
self.stack.append(temp.left)
last += 1
if temp.right is not None:
self.stack.append(temp.right)
last += 1
if now == 0:
now = last
last = 0
self.res.append([])
res = self.res[:-1]
for i in range(len(res)):
if i%2 == 1:
res[i] = res[i][::-1]
return res |
87711c6b969a6ce41564dcb43d4ee333eed9be2f | udoyen/andela-homestead | /andela-homestd/monkey.py | 2,252 | 3.859375 | 4 | import random
import string
# produces random string of type ascii
# s = string.ascii_lowercase
#
#
# def generate():
# """Generates random letters"""
# # word creation
# w1 = ''.join(random.sample(s, 8))
# w2 = ''.join(random.sample(s, 2))
# w3 = ''.join(random.sample(s, 2))
# w4 = ''.join(random.sample(s, 1))
# w5 = ''.join(random.sample(s, 6))
#
# # join the randomly created words
# fw = ''.join(w1 + ' ' + w2 + ' ' + w3 + ' ' + w4 + ' ' + w5)
#
# # print(fw)
#
# return fw
#
#
# def score():
# """scorer function"""
# goal = "methink it is a weasel"
# mon = generate()
# if mon == goal:
# return '100%'
# else:
# return 'almost there'
#
#
# def callfunc():
# count = 1000
# while count < 1000:
# score()
# return print(score())
# print(random.randint(0, 9))
# print(random.randrange(1, 26))
# print(''.join(random.sample(s, 8)))
# print(''.join(random.sample(s, 2)))
# print(''.join(random.sample(s, 2)))
# print(''.join(random.sample(s, 4)))
# print(''.join(random.sample(s, 1)))
# print(''.join(random.sample(s, 6)))
# print(''.join(random.choice(s) for _ in range(3)))
# callfunc()
def generateone(strlen):
alphabet = "abcdefghijklmnopqrstuvwxyz "
res = ""
for i in range(strlen):
res += alphabet[random.randrange(27)]
return res
# print(generateone(20))
def score(goal, teststring):
numsame = 0
for i in range(len(goal)):
if goal[i] == teststring[i]:
# add a score when ever a character in a
# goal matches one in teststring
numsame += 1
return (numsame / len(goal)) * 100 # multiplication by 100 gives a better representation of the score
def main():
goalstring = "methinks it is like a weasel"
newstring = generateone(28)
best = 0
# both strings are being compared
newscore = score(goalstring, newstring)
count = 0
while newscore < 100:
count += 1
if newscore > best:
if count % 1000000 == 0:
print(newscore, newstring)
best = newscore
newstring = generateone(28)
newscore = score(goalstring, newstring)
# print(newstring)
main()
|
a91cc3752a549a7b720a5107fd598b03974aeb28 | AIHackerTest/xiewuqi_Py101-004 | /Chap0/project/ex29.py | 827 | 4.1875 | 4 | # -*- coding:UTF-8 -*-
people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomend!")
if people < cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is dry!")
if people > dogs:
print("The world is dry!")
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")
if people == dogs:
print("People are dogs.")
# 附加练习
if True and False:
print("True")
else:
print("False")
if False or False:
print(" True ")
else:
print("False")
if 3 == 3 and not ("testing" == "testing" or "Pyhong" == "Fun"):
print("True")
elif 3 == 3 and not ("testing" != "testing" or "Pyhong" != "Fun"):
print("False")
|
a0cac161796f36ae80e67be8f84eea9aba0b66bc | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4490/codes/1590_1016.py | 299 | 3.5 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
a = float(input())
b = float(input())
c = float(input())
s = (a+b+c)/2
print(round((s*(s-a)*(s-b)*(s-c))**(1/2),5)) |
00f78fef27d1eb7bce191acfeb7528893d7f910c | Marios1989/Functions | /Functions.py | 2,318 | 4.03125 | 4 | # Functions
def spam():
""""Prints 'Eggs!' """
print("Eggs! ")
spam()
# Call and Response
def square(n):
"""Returns the square of a number."""
squared = n ** 2
print()
"%d squared is %d." % (n, squared)
return squared
# Call the square function on line 10! Make sure to
# include the number 10 between the parentheses.
my_number_squared = square(10)
# Parameters and Arguments
def power(base,exponent): # Add your parameters here!
result = base ** exponent
print("%d to the power of %d is %d." % (base, exponent, result))
power(37, 4) # Add your arguments here!
# Functions Calling Functions
def one_good_turn(n):
return n + 1
def deserves_another(n):
return one_good_turn(n) + 2
# Few more functions
def cube(number):
return number * number * number
def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False
# Generic Imports
import math
print(math.sqrt(25))
# Function Imports
# Import *just* the sqrt function from math on
from math import sqrt
# Universal Imports
from math import *
import math # Imports the math module
everything = dir(math) # Sets everything to a list of things from math
print(everything) # Prints 'em all!
# On Beyond Strings
def biggest_number(*args):
print()
max(args)
return max(args)
def smallest_number(*args):
print
min(args)
return min(args)
def distance_from_zero(arg):
print
abs(arg)
return abs(arg)
biggest_number(-10, -5, 5, 10)
smallest_number(-10, -5, 5, 10)
distance_from_zero(-10)
# max
# Set maximum to the max value of any set of numbers
maximum = max(4,5,6.0)
print(maximum)
# min
# Set minimum to the min value of any set of numbers
minimum = min(9,7,4)
print(minimum)
# abs()
absolute = abs(-42)
print(absolute)
# type ()
# Print out the types of an integer, a float,
# and a string on separate lines below.
print(type(89))
print(type(8.9))
print(type('spam'))
# Review Functions
def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"
# Review Modules
import math
print(math.sqrt(13689))
# Review Built-In Functions
def distance_from_zero(num):
if type(num) == int or type(num) == float:
return abs(num)
else:
return "Nope" |
bbc2a07431ea5ff03f9e9e64686beb584805c5df | Viratsoam/Python-DataStructure | /Recursion/pmi.py | 171 | 4.09375 | 4 | def pmi(n):
if n == 0 or n == 1:
return n
return (n*(n+1))//2
n = int(input("Enter the number to find the sum of first natural numbers!!"))
print(pmi(n))
|
ed372c0c143601216eeab41ad9e9bff4b41c4297 | penicillin0/atcoder | /vairtual/20210920/c.py | 342 | 3.671875 | 4 | def Base_10_to_n(X, n):
if (int(X/n)):
return Base_10_to_n(int(X/n), n)+str(X % n)
return str(X % n)
ans = []
n = int(input())
for i in range(3 ** n):
str_i = Base_10_to_n(i, 3).zfill(n)
password = str_i.replace('0', 'a').replace('1', 'b').replace('2', 'c')
ans.append(password)
print(*sorted(ans), sep='\n')
|
d5588c22a46697f72fc6fee0ba63389a371d6c48 | 26sneharoy/programming-lab | /word.py | 80 | 3.734375 | 4 | w=input("enter you word :")
print(w[-1])
length=len(w)
print(w[1:length-1])
|
4fdc19e9f53d4dbe37a8b65d9c58c04fd0dac900 | GabrielRomanoo/Python | /Aula 7/ex2 com import.py | 1,145 | 3.953125 | 4 | # Crie um programa para calcular as 4
# operações básicas (usando funções).
# As opções são 1-somar, 2-subtrair,
# 3-multiplar, 4-dividir, 5-sair
import funcoes # Tem que estar no mesmo diretório
x = 10
while(x != 5):
x = int(input("1-somar, 2-subtrair, 3-multiplar, 4-dividir, 5-sair, Opção: "))
if(x != 5):
print("Informe dois valores: ")
a = int(input())
b = int(input())
if(x == 1):
print("Resultado: ", funcoes.soma(a= a,b = b))
# a e b são parametros reais, usando uma chamada nominal
if(x == 2):
print("Resultado: ", funcoes.subtrair(a,b))
# a e b são parametros reais, usando chamada usando parametro posiconal
if(x == 3):
print("Resulado: ", funcoes.multiplicar(a,b)) #usa funcoes.multiplicar para indicar que é no arquivo funcoes
# a e b são parametros reais, usando chamada usando parametro posiconal
if(x == 4):
print("Resulado: ", funcoes.dividir(a, b))
# a e b são parametros reais, usando chamada usando parametro posiconal |
725053bee9a114b005159b0d35077368fde1ddc8 | CircleZ3791117/CodingPractice | /source_code/329_LongestIncreasingPathInAMatrix.py | 937 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = circlezhou
'''
Description:
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
'''
class Solution:
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix or len(matrix) < 1 or len(maxtrix[0]) < 1:
return 0
road_map = {} # record the loggest path from each node
H = len(matrix)
w = len(matrix[0])
|
29dcd5194fd346bc4f0c8f9bbee66226a24d3f67 | Megan0145/TK-exercises-1-1 | /Graphs/Graphs-I.py | 984 | 4.34375 | 4 | #1 Using the graph shown in the picture above, write python code to represent the graph in an adjacency list.
class Graph:
def __init__(self):
self.vertices = {
"A": {"B":1},
"B": {"C": 3, "E": 1, "D": 2},
"C": {"E": 4},
"D": {"E": 2},
"E": {"F": 3},
"F": {},
"G": {"D": 1}
}
}
#2 Using the same graph you used for the first exercise, write python code to represent the graph in an adjacency matrix.
class Graph:
def __init__(self):
self.edges = [[0, 1, 0, 0, 0, 0, 0],
[0, 0, 3, 2, 1, 0, 0],
[0, 0, 0, 0, 4, 0, 0],
[0, 0, 0, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 3, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0]] |
7f27c1aa112fc0453c220c1efb4ed9e8ebedbdfb | mutedalien/PY_algo_interactive | /less_8/hw_8_more/lesson_8_task_3.py | 1,040 | 4.0625 | 4 | # Написать программу, которая обходит не взвешенный ориентированный граф без петель, в котором все вершины связаны,
# по алгоритму поиска в глубину (Depth-First Search).
# Задача пройти по всем вершинам вглубь один раз.
def graph(n): # Функция генерации графа
graph = {}
for i in range(n):
element = []
for j in range(n):
if i != j:
element.append(j)
graph[i] = element
return graph
n = int(input('Введите число вершин системы: '))
graph = graph(n)
print(graph)
visited = set()
def dfs(visited, graph, node): # Функция прохождения по вершинам графа
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
dfs(visited, graph, 0)
|
12973bad0f24ead0842cd512e8d169309a9e73cb | ANUSHA6696/Python_Demo | /sets.py | 1,209 | 4.15625 | 4 | #collection does not allow duplicates
l1=[1,2,2,2,3,3,4,2,5]
s=set(l1)
print(s)
s1=set("hello")
print(s1)
#empty set
s3=set() #else it is either tuple or dict
# to add
s3.add(1)
#delete same as list or dict
#union combining two sets without duplication
even= {0,2,4,6,8}
odd = {1,3,5,7,9}
prime={2,3,5,7}
u=odd.union(even)
print(u)
#intersection takes common elements in both sets
i=odd.intersection(prime)
print(i)
#to check elements that are not in one set
SetA={1,2,3,4,5}
SetB={5,6,7,8,9}
diff=SetA.difference(SetB) #gives elements from set b not in set a
print(diff)
#gives all elements not in both sets
diff2= SetB.symmetric_difference(SetA)
SetA.update(SetB) #adds elements in setb not in seta without duplication to set a
#same applies for all other types
#subset if all elements of set1 in set2
set1={1,2,3,4,5,6}
set2={1,2,3}
print(set1.issubset(set2)) #checks if all elements of set1 is in set2 gives false but vice versa is true
print(set2.issuperset(set1)) #gives false as set2 does not contain all elemts of set1 but vice versa is true
#disjoint if both sets have null intersection
set3={4,5,6}
print(set2.isdisjoint(set3))
#copy is same as list
#frozenset is an immutable set
|
eff280e314cb3ab90182af1a70badb34f333a1f5 | SickScarecrow8/CYPAmauryFD | /libro/problemas_resueltos/problema2_1.py | 172 | 3.71875 | 4 | N = int ( input ( "Ingrese el numero de sonidos emitidos por el grillo: "))
if N > 0:
T = (N / 4) + 40
print(f"La temperatura es {T}.")
print("Fin del programa.")
|
fa6e1efae11dc98d981eab6ca59095eb84ed7533 | YMChen95/CMPUT174-Introduction-to-the-Foundations-of-Computation-I | /lab10/lab10-1.py | 307 | 4.03125 | 4 | def reverseDisplay(number):
if number!=0:
number1=number%10
number=number//10
print(number1,end='')
return reverseDisplay(number)
def main():
number = int(input("Enter a number: "))
reverseDisplay(number)
print(reverseDisplay(number))
main() |
82059c7d0a23dbe2991509c454105b17e8d3ab9d | MaximusMalabaev/Test | /generator.py | 252 | 3.78125 | 4 | #example 1
def simple_generator(val):
while val > 0:
val -= 1
yield 1
gen_iter = simple_generator(5)
print(next(gen_iter))
print(next(gen_iter))
print(next(gen_iter))
print(next(gen_iter))
print(next(gen_iter))
print(next(gen_iter))
|
7b3dc9b5ab9b48b720246b5a1fce99744023140b | Ahmad-Magdy-Osman/JCoCo | /tests/classtest2.py | 808 | 3.84375 | 4 | import disassembler
import sys
class Dog:
# to run this test, step over code with debugger into this __init__
# method and print the operand stack (option "a") to examine contents.
# It should attempt to call the __str__ method below when the operand
# stack is printed. Then the result will be that a Dog reference
# will be printed instead.
def __init__(self,name,bark):
self.name = name
self.bark = bark
def getName(self):
return self.name
def setName(self,name):
self.name = name
def speak(self):
print(self.bark)
def __str__(self):
return "Dog(" + self.name + "," + self.bark + ")"
def main():
d = Dog("Mesa","woof")
print(d.getName())
d.speak()
d.setName("Sequoia")
if len(sys.argv) == 1:
main()
else:
disassembler.disassemble(Dog)
disassembler.disassemble(main)
|
ed1d88c95fe3cd887c084a121f241eaf98ff1334 | JPMonglis/BTS | /stringConverter.py | 21,040 | 3.59375 | 4 | #!/usr/bin/python
# coding: utf-8
import sys
import os
import re
import base64
import binascii
import urllib
# \
# Author: Paul Laîné
# Data: Sat Sep, 2016
# Version: 1.0
# /
def file_base64_to_text():
try:
path = raw_input("\nPlease enter the path of your file: ")
try:
data = open(path, 'r')
content = data.read()
print "[+] Start decoding the base 64 content ..."
try:
plain = base64.b64decode(content)
except TypeError:
return "Your bases 64 content don't work..."
print "[+] Start decoding the base 64 content ... OK"
data.close()
except IOError:
return "File not found ..."
save = raw_input("Do you want to save the plain text (Y/N): ")
if save == "y" or save == "Y":
path_save = raw_input("Where you want to save the plain text: ")
try:
print "[+] Trying to generate the file ..."
data = open(path_save, 'a')
print "[+] Trying to generate the file ... OK"
print "[+] Start writing the plain text on the file ..."
data.write(plain)
print "[+] Start writing the plain text on the file ... OK"
data.close()
except IOError:
return "Ooops something goes wrong with your file, retry ..."
raw_input("\nHit any key to continue ...")
return plain
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def base64_to_text():
try:
while True:
print "\nInput in base 64:"
cypher = raw_input("Cypher> ")
if re.match('^[a-zA-z0-9]+(=)?(==)?$', cypher):
try:
print "Plain> "+base64.b64decode(cypher)+"\n"
except TypeError:
print "Your base 64 input don't work"
else:
print "Input in base 64 please, bjAwYg== "
if raw_input("\nAnother time (Y/N): ") in ("N", 'n'):
break
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def file_binary_to_text():
try:
path = raw_input("\nPlease enter the path of you file: ")
try:
data = open(path, 'r')
content = data.read()
content = int(content, 2)
print "[+] Start decoding the binary content ..."
try:
plain = binascii.unhexlify('%x' % content)
except TypeError:
return "Your binary content don't work"
print "[+] Start decoding the binary content ... OK"
data.close()
except IOError:
return "File not found ..."
save = raw_input("Do you want to save the plain text (Y/N): ")
if save == "y" or save == "Y":
path_save = raw_input("Where you want to save the plain text: ")
try:
print "[+] Trying to generate the file ..."
data = open(path_save, 'a')
print "[+] Trying to generate the file ... OK"
print "[+] Start writing the plain text on the file ..."
data.write(plain)
print "[+] Start writing the plain text on the file ... OK"
data.close()
except IOError:
return "Ooops something goes wrong with your file, retry ..."
raw_input("\nHit any key to continue ...")
return plain
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def binary_to_text():
try:
while True:
print "\nInput binary: "
cypher = raw_input("Cypher> ")
if re.match('^[0-1]+$', cypher):
cypher = int(cypher, 2)
try:
print "Plain> "+(binascii.unhexlify('%x' % int(cypher)))
except TypeError:
print "Your binary input don't work..."
else:
print "Input a binary please, only 1 and 0"
if raw_input("\nAnother time (Y/N): ") in ('N', 'n'):
break
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def file_hexadecimal_to_text():
try:
path = raw_input("\nPlease enter the path of you file: ")
try:
data = open(path, 'r')
content = data.read()
print "[+] Start decoding the hexadecimal content ..."
try:
plain = base64.b16decode(content)
except TypeError:
return "Your hexadecimal content don't work..."
print "[+] Start decoding the hexadecimal content ... OK"
data.close()
except IOError:
return "File not found ... "
save = raw_input("Do you want to save the plain text (Y/N): ")
if save == "y" or save == "Y":
path_save = raw_input("Where you want to save the plain text: ")
try:
print "[+] Trying to generate the file ..."
data = open(path_save, 'a')
print "[+] Trying to generate the file ... OK"
print "[+] Start writing the plain text on the file ..."
data.write(plain)
print "[+] Start writing the plain text on the file ... OK"
data.close()
except IOError:
return "Ooops something goes wrong with your file, retry ..."
raw_input("\nHit any key to continue ...")
return plain
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def hexadecimal_to_text():
try:
while True:
print "\nInput hexadecimal: "
cypher = raw_input("Cypher> ")
if re.match('^[0-9a-fA-F]+', cypher):
try:
print "Plain> "+(base64.b16decode(cypher))
except TypeError:
print "Your hexadecimal input don't work..."
else:
print "Input a hexadecimal please"
if raw_input("\nAnother time (Y/N): ") in ('N', 'n'):
break
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def file_url_to_text():
try:
path = raw_input("\nPlease enter the path of you file: ")
try:
data = open(path, 'r')
content = data.read()
print "[+] Start encoding the URL..."
try:
plain = urllib.unquote(content)
except TypeError:
return "Your URL content don't work..."
print "[+] Start encoding the URL ... OK"
data.close()
except IOError:
return "File not found ... "
save = raw_input("Do you want to save the plain text (Y/N): ")
if save == "y" or save == "Y":
path_save = raw_input("Where you want to save the cypher text: ")
try:
print "[+] Trying to generate the file ..."
data = open(path_save, 'a')
print "[+] Trying to generate the file ... OK"
print "[+] Start writing the cypher text on the file ..."
data.write(plain)
print "[+] Start writing the cypher text on the file ... OK"
data.close()
except IOError:
return "Ooops something goes wrong with your file, retry ..."
raw_input("\nHit any key to continue ...")
return plain
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def url_to_text():
try:
while True:
print "\nInput URL: "
cypher = raw_input("Cypher> ")
try:
print "Plain> " + urllib.unquote(cypher)
except TypeError:
print "Your URL don't work..."
if raw_input("\nAnother time (Y/N): ") in ('N', 'n'):
break
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def file_text_to_base64():
try:
path = raw_input("\nPlease enter the path of you file: ")
try:
data = open(path, 'r')
content = data.read()
print "[+] Start encode in base 64 the content ..."
try:
cypher = base64.b64encode(content)
except TypeError:
return "Your text input don't work..."
print "[+] Start encode in base 64 the content ... OK"
data.close()
except IOError:
return "File not found ..."
save = raw_input("Do you want to save the cypher (Y/N): ")
if save == "y" or save == "Y":
path_save = raw_input("Where you want to save the cypher: ")
try:
print "[+] Trying to generate the file ..."
data = open(path_save, 'a')
print "[+] Trying to generate the file ... OK"
print "[+] Start writing the cypher on the file ..."
data.write(cypher)
print "[+] Start writing the cypher on the file ... OK"
data.close()
except IOError:
return "Ooops something goes wrong with your file, retry ..."
raw_input("\nHit any key to continue ...")
return cypher
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def text_to_base64():
try:
while True:
print "\nInput some text: "
plain = raw_input("Plain> ")
if re.match('^(.)+$', plain):
try:
print "Cypher> "+(base64.b64encode(plain))
except TypeError:
print "Your text don't work 0_0"
else:
print "You don't input text!"
if raw_input("\nAnother time (Y/N): ") in ('N', 'n'):
break
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def file_text_to_binary():
try:
path = raw_input("\nPlease enter the path of you file: ")
try:
data = open(path, 'r')
content = data.read()
print "[+] Start encode in binary the content ..."
try:
cypher = bin(int(binascii.hexlify(content), 16)).split('b')
cypher = cypher[0] + cypher[1]
except TypeError:
return "Your text input don't work retry ..."
print "[+] Start encode in binary the content ... OK"
data.close()
except IOError:
return "File not found ..."
save = raw_input("Do you want to save the cypher (Y/N): ")
if save == "y" or save == "Y":
path_save = raw_input("Where you want to save you cypher: ")
try:
print "[+] Trying to generate the file ..."
data = open(path_save, 'a')
print "[+] Trying to generate the file ... OK"
print "[+] Start writing the cypher on the file ..."
data.write(cypher)
print "[+] Start writing the cypher on the file ... OK"
data.close()
except IOError:
return "Ooops something goes wrong with your file, retry ..."
raw_input("\nHit any key to continue ...")
return cypher
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def text_to_binary():
try:
while True:
print "\nInput some binary: "
plain = raw_input("Plain> ")
if re.match('^(.)+$', plain):
try:
cypher = bin(int(binascii.hexlify(plain), 16)).split('b')
print "Cypher> "+(cypher[0] + cypher[1])
except TypeError:
print "Your text don't work 0_0"
else:
print "You don't input text!"
if raw_input("\nAnother time (Y/N): ") in ('N', 'n'):
break
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def file_text_to_hexadecimal():
try:
path = raw_input("\nPlease enter the path of you file: ")
try:
data = open(path, 'r')
content = data.read()
print "[+] Start encode in hexadecimal the content ..."
try:
cypher = base64.b16encode(content)
except TypeError:
return "Your text input don't work ..."
print "[+] Start encode in hexadecimal the content ... OK"
data.close()
except IOError:
return "File not found ..."
save = raw_input("Do you want to save the cypher (Y/N): ")
if save == "y" or save == "Y":
path_save = raw_input("Where you want to save the cypher: ")
try:
print "[+] Trying to generate the file ..."
data = open(path_save, 'a')
print "[+] Trying to generate the file ... OK"
print "[+] Start writing the cypher on the file ..."
data.write(cypher)
print "[+] Start writing the cypher on the file ... OK"
data.close()
except IOError:
return "Ooops something goes wrong with your file, retry ..."
raw_input("\nHit any key to continue ...")
return cypher
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def text_to_hexadecimal():
try:
while True:
print "\nInput some hexadecimal: "
plain = raw_input("Plain> ")
if re.match('^(.)+$', plain):
try:
print "Cypher> "+(base64.b16encode(plain))
except TypeError:
print "Your text don't work 0_0"
else:
print "You don't input text!"
if raw_input("\nAnother time (Y/N): ") in ('N', 'n'):
break
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def file_text_to_url():
try:
path = raw_input("\nPlease enter the path of you file: ")
try:
data = open(path, 'r')
content = data.read()
print "[+] Start decoding the URL..."
try:
plain = urllib.quote_plus(content)
except TypeError:
return "Your URL content don't work..."
print "[+] Start decoding the URL ... OK"
data.close()
except IOError:
return "File not found ... "
save = raw_input("Do you want to save the plain text (Y/N): ")
if save == "y" or save == "Y":
path_save = raw_input("Where you want to save the plain text: ")
try:
print "[+] Trying to generate the file ..."
data = open(path_save, 'a')
print "[+] Trying to generate the file ... OK"
print "[+] Start writing the plain text on the file ..."
data.write(plain)
print "[+] Start writing the plain text on the file ... OK"
data.close()
except IOError:
return "Ooops something goes wrong with your file, retry ..."
raw_input("\nHit any key to continue ...")
return plain
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def text_to_url():
try:
while True:
print "\nInput URL: "
cypher = raw_input("Cypher> ")
if re.match("^(https?://|www\.)[a-z-]+\.[a-z0-9-]+[a-z.]{0,4}/?[a-z0-9A-Z*_\-'();:@&=+$,/?#.]+$", cypher):
try:
print "Plain> "+urllib.quote_plus(cypher)
except TypeError:
print "Your URL don't work..."
else:
print "Input a good URL please"
if raw_input("\nAnother time (Y/N): ") in ('N', 'n'):
break
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def report(info):
return "+" + "-" * 20 + " REPORT " + "-" * 20+"\n"+info+"\n+" + "-" * 52 + "\n"
def menu(info_version):
style_on = '\x1b[7m'
style_off = '\x1b[27m'
notifications = ''
if info_version == "active_version":
set_version = 1
elif info_version == "file_version":
set_version = 2
try:
while True:
os.system('clear')
print notifications
print "\t\t " + style_on + " M A I N - M E N U " + style_off
print "\n 01. Base 64 to text\t\t 05. Text to base 64"
print " 02. Binary to text\t\t 06. Text to binary"
print " 03. Hexa to text\t\t 07. Text to hexadecimal"
print " 04. URL to text\t\t 08. Text to URL"
print "\n\t\t\t66. EXIT\n"
rep = raw_input('strC0nv3rt/menu> ')
if rep == 1 or rep == "1" and set_version == 2:
plain = file_base64_to_text()
notifications = report(plain)
elif rep == 1 or rep == "1" and set_version == 1:
base64_to_text()
elif rep == 2 or rep == "2" and set_version == 2:
plain = file_binary_to_text()
notifications = report(plain)
elif rep == 2 or rep == "2" and set_version == 1:
binary_to_text()
elif rep == 3 or rep == "3" and set_version == 2:
plain = file_hexadecimal_to_text()
notifications = report(plain)
elif rep == 3 or rep == "3" and set_version == 1:
hexadecimal_to_text()
elif rep == 4 or rep == "4" and set_version == 2:
plain = file_url_to_text()
notifications = report(plain)
elif rep == 4 or rep == "4" and set_version == 1:
url_to_text()
elif rep == 5 or rep == "5" and set_version == 2:
cypher = file_text_to_base64()
notifications = report(cypher)
elif rep == 5 or rep == "5" and set_version == 1:
text_to_base64()
elif rep == 6 or rep == "6" and set_version == 2:
cypher = file_text_to_binary()
notifications = report(cypher)
elif rep == 6 or rep == "6" and set_version == 1:
text_to_binary()
elif rep == 7 or rep == "7" and set_version == 2:
cypher = file_text_to_hexadecimal()
notifications = report(cypher)
elif rep == 7 or rep == "7" and set_version == 1:
text_to_hexadecimal()
elif rep == 8 or rep == "8" and set_version == 2:
cypher = file_text_to_url()
notifications = report(cypher)
elif rep == 8 or rep == "8" and set_version == 1:
text_to_url()
elif rep == 66 or rep == "66":
os.system('clear')
break
else:
os.system('clear')
print "Input a good value ...\n"
except KeyboardInterrupt:
print "\nHave a nice day 1337."
sys.exit()
def version():
style_on = '\x1b[7m'
style_off = '\x1b[27m'
try:
while True:
os.system('clear')
banner()
print "\t\t " + style_on + " M A I N - M E N U " + style_off + "\n"
print " 01. Active version\t 02.File version"
print "\n\t\t 66. EXIT"
print "\n The active version is a instant conversion mode."
print "\n In the file version you input a file and output\n a converted file"
rep = raw_input("\nstrC0v3rt> ")
if rep == 1 or rep == "1":
menu('active_version')
elif rep == 2 or rep == "2":
menu('file_version')
elif rep == 66 or rep == "66":
print "\nHave a nice day 1337.\n"
sys.exit()
except KeyboardInterrupt:
print "n\nHave a nice day 1337.\n"
sys.exit()
def banner():
r = '\x1b[31m'
b = '\x1b[34m'
y = '\x1b[33m'
d = '\x1b[97m'
print '\n' + b + ' [---] The String Converter [---]'
print ' [---] Created by: ' + r + 'Paul Laîné' + b + ' (' + y + 'palaine' + b + ') [---]'
print ' Version: ' + r + '1.2' + b
print ' Codename: ' + y + '\'strC0nv3rt\' ' + b
print ' [---] On GitHub: ' + y + 'https://www.github.com/palaine' + b + ' [---]' + d + '\n'
if __name__ == '__main__':
sys.exit(version())
|
e857d6b485e6ed8c1b16105571dcba45bdc5e52e | vuhonganh/selfStudy | /online_courses/udacity/design_comp_prog/lesson_6/anagrams.py | 6,271 | 4.3125 | 4 | # This homework deals with anagrams. An anagram is a rearrangement
# of the letters in a word to form one or more new words.
#
# Your job is to write a function anagrams(), which takes as input
# a phrase and an optional argument, shortest, which is an integer
# that specifies the shortest acceptable word. Your function should
# return a set of all the possible combinations of anagrams.
#
# Your function should not return every permutation of a multi word
# anagram: only the permutation where the words are in alphabetical
# order. For example, for the input string 'ANAGRAMS' the set that
# your function returns should include 'AN ARM SAG', but should NOT
# include 'ARM SAG AN', or 'SAG AN ARM', etc...
def anagrams_ver2(phrase, shortest=2):
"""better version: shorter and more efficient"""
return find_anagrams_ver2(phrase.replace(' ', ''), '', shortest)
def find_anagrams_ver2(letters, previous_word, shortest):
"""Using letters, form anagrams using words > previous_word and not shorter than shortest"""
result = set()
for w in find_words_ver2(letters):
if len(w) >= shortest and w >= previous_word:
remainder = removed(letters, w)
if remainder:
for rest in find_anagrams_ver2(remainder, w, shortest):
result.add(w + ' ' + rest)
else:
result.add(w)
return result
def find_words_ver2(letters):
return extend_prefix_ver2('', letters, set())
def extend_prefix_ver2(pre, letters, results):
if pre in WORDS:
results.add(pre)
if pre in PREFIXES:
for L in letters:
extend_prefix_ver2(pre + L, letters.replace(L, '', 1), results)
return results
def anagrams(phrase, shortest=2):
"""Return a set of phrases with words from WORDS that form anagram
of phrase. Spaces can be anywhere in phrase or anagram. All words
have length >= shortest. Phrases in answer must have words in
lexicographic order (not all permutations)."""
# first need to remove space in phrase for easy processing later:
phrase_no_space = phrase.replace(' ', '')
# case where are several words form an anagram
result_in_tuple = set()
find_anagrams(phrase_no_space, shortest, result_in_tuple)
result = set()
for elem in result_in_tuple:
s = ' '.join(w for w in elem)
result.add(s)
# case where a whole word form an anagram
whole_words = find_words(phrase_no_space, len(phrase_no_space))
for s in whole_words:
if s != phrase_no_space:
result.add(s)
return result
def find_anagrams(letters, shortest, results):
"""return a set of anagrams with all words longer than shortest"""
if len(letters) < shortest:
return
part_1 = find_words(letters, shortest) # part_1 is the possible first words in results anagrams
for word in part_1:
subtracted_letters = removed(letters, word)
the_rest = find_words(subtracted_letters, len(subtracted_letters)) # find exact the rest which forms a word
for word2 in the_rest:
cur_anagram = (word, word2) if word < word2 else (word2, word)
results.add(cur_anagram)
subset = set()
find_anagrams(subtracted_letters, shortest, subset)
for _, elem in enumerate(subset):
another_anagram = ((word, elem[0], elem[1]) if word < elem[0] else
(elem[0], word, elem[1]) if word < elem[1] else
(elem[0], elem[1], word))
results.add(another_anagram)
return
# ------------
# Helpful functions
#
# You may find the following functions useful. These functions
# are identical to those we defined in lecture.
def removed(letters, remove):
"""Return a str of letters, but with each letter in remove removed once."""
for L in remove:
letters = letters.replace(L, '', 1)
return letters
def find_words(letters, shortest):
"""return a set of words in WORDS that is composed from a sub set of these letters
min length of word is shortest"""
if len(letters) < shortest:
return None
return sorted(extend_prefix('', letters, shortest, set()))
def extend_prefix(pre, letters, shortest, results):
"""Helper function of find_words()"""
if pre in WORDS and len(pre) >= shortest:
results.add(pre)
if pre in PREFIXES:
for L in letters:
extend_prefix(pre + L, letters.replace(L, '', 1), shortest, results)
return results
def prefixes(word):
"""A list of the initial sequences of a word, not including the complete word."""
return [word[:i] for i in range(len(word))]
def readwordlist(filename):
"""Return a pair of sets: all the words in a file, and all the prefixes. (Uppercased.)"""
wordset = set(open(filename).read().upper().split())
prefixset = set(p for word in wordset for p in prefixes(word))
return wordset, prefixset
WORDS, PREFIXES = readwordlist('words4k.txt')
# ------------
# Testing
#
# Run the function test() to see if your function behaves as expected.
def test():
print 'File: anagrams.py'
assert 'DOCTOR WHO' in anagrams('TORCHWOOD')
assert 'BOOK SEC TRY' in anagrams('OCTOBER SKY')
assert 'SEE THEY' in anagrams('THE EYES')
assert 'LIVES' in anagrams('ELVIS')
assert anagrams('PYTHONIC') == {'NTH PIC YO', 'NTH OY PIC', 'ON PIC THY', 'NO PIC THY', 'COY IN PHT', 'ICY NO PHT',
'ICY ON PHT', 'ICY NTH OP', 'COP IN THY', 'HYP ON TIC', 'CON PI THY', 'HYP NO TIC',
'COY NTH PI', 'CON HYP IT', 'COT HYP IN', 'CON HYP TI'}
assert 'DOCTOR WHO' in anagrams_ver2('TORCHWOOD')
assert 'BOOK SEC TRY' in anagrams_ver2('OCTOBER SKY')
assert 'SEE THEY' in anagrams_ver2('THE EYES')
assert 'LIVES' in anagrams_ver2('ELVIS')
assert anagrams_ver2('PYTHONIC') == {'NTH PIC YO', 'NTH OY PIC', 'ON PIC THY', 'NO PIC THY', 'COY IN PHT', 'ICY NO PHT',
'ICY ON PHT', 'ICY NTH OP', 'COP IN THY', 'HYP ON TIC', 'CON PI THY', 'HYP NO TIC',
'COY NTH PI', 'CON HYP IT', 'COT HYP IN', 'CON HYP TI'}
return 'tests pass'
print test()
|
5cd4853e0f813579cdb6716464a761a9026fbfdc | laxbista/Python-Practice | /String_Excercises/q12.py | 307 | 4.09375 | 4 | # Exercise Question 12: Find the last position of a substring “Emma” in a given string
# Where in the string is the last occurrence of the substring “Emma”?:
str1 = "Emma is a data scientist who knows Python. Emma works at google."
search= "Emma"
occur = str1.rfind(search)
print(occur)
|
2cc67428472e4826b84fe1f9109c208fa56f91ea | rajasekaran36/GE8151-Problem-Solving-and-Python-Programming | /Lab/Ex 10 Word Count Command Line/E10-Code.py | 149 | 3.78125 | 4 | import sys
args = sys.argv
count = 0
for command in args:
print (command)
count+=1
print ("Total number of arguments:",count)
input("Thanks") |
a0583be35e2818c18b564bf75959acfd016c69fd | truongc2/data-describe | /data_describe/misc/preprocessing.py | 2,037 | 3.609375 | 4 | import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.impute import SimpleImputer
def preprocess(data, target, impute="simple", encode="label"):
"""Simple preprocessing pipeline for ML.
Args:
data: A Pandas dataframe
target: Name of the target feature
impute: Method to use for imputing numeric variables. Only 'simple' is implemented.
encode: Method to use for encoding categorical variables. Only 'label' is implemented.
Raises:
NotImplementedError: Imputation or encoding method not implemented.
ValueError: No columns left to preprocess.
Returns:
(X, y) tuple of numpy arrays
"""
y = data[target]
data = data.drop(target, axis=1)
data = data.dropna(axis=1, how="all")
# Process numeric features
num = data.select_dtypes(["number"])
if num.shape[1] > 0:
if impute == "simple":
imp = SimpleImputer(missing_values=np.nan, strategy="mean")
x_num = imp.fit_transform(num)
else:
raise NotImplementedError("Unknown imputation method: {}".format(impute))
# Ordinal encode everything else
# TODO: Address date and text columns
cat = data[[c for c in data.columns if c not in num.columns]]
if cat.shape[1] > 0:
cat = cat.astype(str)
cat = cat.fillna("")
if encode == "label":
x_cat = cat.apply(LabelEncoder().fit_transform)
else:
raise NotImplementedError("Unknown encoding method: {}".format(encode))
if num.shape[1] > 0 and cat.shape[1] > 0:
X = pd.DataFrame(
np.concatenate([x_num, x_cat], axis=1),
columns=list(num.columns.values) + list(cat.columns),
)
elif num.shape[1] > 0:
X = pd.DataFrame(x_num, columns=num.columns)
elif cat.shape[1] > 0:
X = pd.DataFrame(x_cat, columns=x_cat.columns)
else:
raise ValueError("No numeric or categorical columns were found.")
return X, y
|
5681e1325467397160eaef6875f13251c4bc0cdc | BuglessCoder/algorithm-1 | /Lintcode/climbing-stairs.py | 407 | 3.65625 | 4 | class Solution:
"""
@param n: An integer
@return: An integer
"""
def Solution(self):
pass
def climbStairs(self, n):
# write your code here
fibo = []
fibo.append(1)
fibo.append(1)
fibo.append(2)
for i in range(3, 1000):
fibo.append(fibo[i-1] + fibo[i-2])
return fibo[n]
d = Solution()
print d.climbStairs(5)
|
ae242434c64028efaa254acf8555b79a0d2cc0e1 | strawsyz/straw | /ProgrammingQuestions/牛客/青蛙跳台阶.py | 326 | 3.796875 | 4 | # 青蛙一次跳1或2格台阶,跳完所有台阶有多少种跳法
# 记忆化搜索
def f(n):
memo = [-1] * (n + 1)
def dp(n):
if n == 1 or n == 0:
return 1
if memo[n] == -1:
memo[n] = (dp(n - 1) + dp(n - 2))
return memo[n]
return dp(n)
res = f(5)
print(res) |
255309a0246c3035d254aee6f09cf14020f9e331 | Helbros72/targilim | /targilim_page_25_8_9.py | 410 | 3.90625 | 4 | # a - list numbers
a = []
print (' For stop insert digits ,enter 0 or negative digit')
while True :
x = int(input( ' Enter the number :'))
if x == 0 or x < 0:
print (' Goodbye')
break
else :
number = int(x)
a.append(number)
#else :
#break
min_number = min(a)
max_number = max(a)
print ('Smalless :',(min_number ))
print ('Bigger :' , max_number)
|
5d50530b01da6a17fb9c699aaa3037da24ad5aac | stephen-weber/Project_Euler | /Python/Problem0105_SpecialSubsetSums_testing.py/Problem_105_SpecialSubsetSums_testing.py | 3,328 | 3.65625 | 4 | """
Special subset sums: testing
Problem 105
Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
S(B) S(C); that is, sums of subsets cannot be equal.
If B contains more elements than C then S(B) S(C).
For example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because 65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139, 158} satisfies both rules for all possible subset pair combinations and S(A) = 1286.
Using sets.txt (right click and "Save Link/Target As..."), a 4K text file with one-hundred sets containing seven to twelve elements (the two examples given above are the first two sets in the file), identify all the special sum sets, A1, A2, ..., Ak, and find the value of S(A1) + S(A2) + ... + S(Ak).
NOTE: This problem is related to problems 103 and 106.
"""
#year=[20,31,38,39,40,42,45]
sets=[]
pppp=set()
def make_set(lineSet):
global sets
global pppp
num=len(lineSet)
n=range(1,num+1)
import itertools
pppp=set()
sets=[]
for k in range(1,len(n)+1):
for i in itertools.combinations(n,k):
sets.append(i)
for ii in range(len(sets)-1):
i=sets[ii]
for jj in range(ii+1,len(sets)):
j=sets[jj]
g=[i,j]
g.sort()
h=set(i)
t=set(j)
if h.intersection(t)==set([]):
pppp.add(tuple(g))
pppp=list(pppp)
def check2( n):
global pppp
for a,b in pppp:
a1=[]
b1=[]
for e in a:
a1.append(n[e-1])
for e in b:
b1.append(n[e-1])
#print a1,sum(a1),"=?=",sum(b1),b1
if len(a)==len(b):
if sum(a1)==sum(b1):
print a1,sum(a1),sum(b1),b1,"+++"
return False
if len(a)>len(b):
if sum(a1)<=sum(b1):
print a1,sum(a1),sum(b1),b1,"////"
return False
if len(a)<len(b):
if sum(a1)>=sum(b1):
print a1,sum(a1),sum(b1),b1,"PPP"
return False
return True
def Start():
global sets
global pppp
global pollution
total=0
sets=[]
count=0
golf= open("/Users/sweber/Desktop/Problem105_SpecialSubsetSums_testing/sets.txt")
line =golf.readlines()
lineSet=[]
for i in line:
d=i.split(",")
lin=[int(str(e)) for e in d]
lineSet.append(lin)
for ape in lineSet:
count+=1
print count," : ",ape
make_set(ape)
cow=check2(ape)
#print cow
if cow:
total=total+sum(ape)
print count," : YES total=",total
else:
print count, " : NO THIS SECOND TEST FAILED"
sets=[]
pppp=set()
print total
Start()
|
59a9b626e1127bc3c35ef212ef6b306023702103 | kotouharuto/algorthm-study | /basic-algorithem_1/1-1/median3.py | 439 | 3.984375 | 4 | # 3つの整数値を読み込んで中央値を求めて表示
def med3(a, b, c):
if a >= b:
if b >= c:
return b
elif a <= c:
return a
else:
return c
elif a > c:
return a
elif b > c:
return c
else:
return b
print('3つの整数の中央値を求めます。')
a = int(input('整数aの値:'))
b = int(input('整数bの値:'))
c = int(input('整数cの値:'))
print(f'中央値は{med3(a, b, c)}です。') |
85911d3d2945e3114d5af04298c8c94c4dc5e51b | eu2004/codecademy_capstone | /capstone_starter/predict_income_knr.py | 3,540 | 3.65625 | 4 | # Predicts income based on education, drugs and sex, using K-Nearest Neighbors Regression model.
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from matplotlib import pyplot as plt
from time import time
def generate_column_mapping(column_values):
unique_column_values = list(set(column_values))
column_mapping = {}
index = 0
for val in unique_column_values:
column_mapping[val] = index
index += 1
return column_mapping
def get_data_set(data_frame):
#Removing the NaNs
x_columns = ["education","drugs","sex"]
data_frame[x_columns] = data_frame[x_columns].replace(np.nan, '', regex=True)
data_frame["income"] = data_frame["income"].replace(np.nan, -1, regex=True)
#Augment Data
data_frame["education_code"] = data_frame.education.map(generate_column_mapping(data_frame["education"]))
data_frame["drugs_code"] = data_frame.drugs.map(generate_column_mapping(data_frame['drugs']))
data_frame["sex_code"] = data_frame.sex.map(generate_column_mapping(data_frame['sex']))
X = data_frame[['education_code','drugs_code','sex_code']]
y = data_frame[["income"]]
return X,y
def get_test_data_set(data_frame):
X, y = get_data_set(data_frame)
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8, test_size = 0.2)
return X_train, X_test, y_train, y_test
def test_performance(data_frame, iteration_count):
X_train, X_test, y_train, y_test = get_test_data_set(data_frame)
train_score = []
test_score = []
k_steps = []
start = time();
for k in range(1, iteration_count):
regressor = KNeighborsRegressor(k, weights="distance")
regressor.fit(X_train, y_train)
train_score.append(regressor.score(X_train, y_train))
test_score.append(regressor.score(X_test, y_test))
k_steps.append(k)
print("execution time (sec) for test_performance:", time() - start)
plt.plot(k_steps, train_score, label="Training score")
plt.plot(k_steps, test_score, label="Test score")
plt.xlabel('k values')
plt.ylabel('Accuracy score')
plt.legend(loc=8)
plt.show()
def predict_income(data_frame, X_input):
X, y = get_data_set(data_frame)
start = time();
regressor = KNeighborsRegressor(5, weights="distance")
regressor.fit(X, y)
prediction = regressor.predict(X_input)
print("execution time (sec) for predict_income:", time() - start)
return prediction, X_input
#Tests
df = pd.read_csv("profiles.csv")
print("What income has a person with 'graduated from law school' as education level, takes drugs often and is a woman:", predict_income(df, [[1,2,1]]))
test_performance(df, 100)
#Results:
# ('execution time (sec) for predict_income:', 0.7219998836517334)
# ("What income has a person with 'graduated from law school' as education level, takes drugs often and is a woman:", (array([[7999.4]]), [[1, 2, 1]]))
# ('execution time (sec) for test_performance:', 370.6950001716614)
#Visualize data
# x_train, x_test, y_train, y_test = get_test_data_set(df)
# regressor = KNeighborsRegressor(17, weights="distance")
# regressor.fit(x_train, y_train)
# y_predict = regressor.predict(x_test)
# plt.scatter(y_test, y_predict, alpha=0.4)
# plt.xlabel("Incomes")
# plt.ylabel("Predicted incomes")
# plt.title("Actual Income vs Predicted Income")
# plt.show()
#
|
0f39a75c924be000651b3f1a6a2e8d68c9fa172d | richpsharp/ep | /problem12.py | 2,166 | 3.828125 | 4 | """
The sequence of triangle numbers is generated by adding the natural numbers. So
the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten
terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred
divisors?
"""
import collections
def prime_decomposition(n):
"""Return list of prime factors of n."""
max_test = int(n**0.5)
prime_list = collections.defaultdict(int)
for factor in [2, 3]:
while n % factor == 0:
prime_list[factor] += 1
n = n // factor
factor = 5 # do 6k+/-1
while factor < max_test:
if n == 1:
break
while n % factor == 0:
prime_list[factor] += 1
n = n // factor
while n % (factor+2) == 0:
prime_list[factor+2] += 1
n = n // (factor+2)
factor += 6
if n != 1:
prime_list[n] += 1
return prime_list
def n_factors(n):
if n == 1:
return 1
if n in n_factors.cache:
return n_factors.cache[n]
prime_count = iter(prime_decomposition(n).values())
count = 1+next(prime_count)
for x in prime_count:
count *= 1+x
n_factors.cache[n] = count
return count
if __name__ == '__main__':
n_factors.cache = {}
n = 3
last_prime_decomp = prime_decomposition(n)
while True:
tri_n = n*(n+1)/2
cur_prime_decom = prime_decomposition(n+1)
total_prime_decom = last_prime_decomp.copy()
for val, count in cur_prime_decom.items():
total_prime_decom[val] += count
total_prime_decom[2] -= 1
n_factors = 1
for count in total_prime_decom.values():
n_factors *= (count+1)
last_prime_decomp = cur_prime_decom
if n_factors > 500:
print('%d %d %s' % (tri_n, n_factors, total_prime_decom))
break
n += 1
|
d0ac50c3f3107ae2e5dbd2acb058ebd9f48f4a01 | SwAtz07/HOMOMORPHIC-ENCRYPTION | /Paillier.py | 4,114 | 3.6875 | 4 | import random
import ModularArithmetic
import RabinMiller
class PrivateKey:
"""
PrivateKey object contains λ and μ
in accordance to the Paillier Cryptosystem
args:
p: a prime number
q: another prime number
(p and q are of equal length)
n: product of p and q
attributes:
λ: lowest common multiple of p-1 and q-1
∵ p and q are of equal length we can use the simplification,
μ: modular multiplicative inverse of λ and n
"""
def __init__(self, p, q, n):
self.λ = ModularArithmetic.lcm( p-1, q-1)
self.μ = ModularArithmetic.multiplicative_inverse( self.λ, n)
def __repr__(self):
return ("---\nPrivate Key :\nλ:\t"+str(self.λ) +"\nμ:\t"+str(self.μ) +"\n---")
class PublicKey:
"""
Public Key object contains n and g
in accordance to the Paillier Cryptosystem
args:
n: product of two equal lenght prime numbers
attributes:
n: product of two primes
g: a random number such that,
multiplicative order of g in n^2 is a multiple of n
∵ p and q are of equal length we can use a simplification of g = n+1
"""
def __init__(self, n):
self.n = n
self.nsq = n * n
self.g = n+1
def __repr__(self):
return ("---\nPublic Key :\nn:\t"+ str(self.n) +"\n---")
def generate_keys(bitlen=128):
"""
generate_keys( bitlen)
args:
bitlen: length of primes to be generated (default: 128)
returns Public Private key pair as a tuple
(PublicKey, PrivateKey)
"""
p = RabinMiller.generate_prime(bitlen)
q = RabinMiller.generate_prime(bitlen)
n = p * q
return (PublicKey(n), PrivateKey(p, q, n))
def Encrypt(public_key, plaintext):
"""
Encrypt( public_key, plaintext)
args:
public_key: Paillier Publickey object
plaintext: number to be encrypted
returns:
ciphertext: encryption of plaintext
such that ciphertext = (g ^ plaintext) * (r ^ n) (mod n ^ 2)
where, r is a random number in n such that r and n are coprime
"""
r = random.randint( 1, public_key.n-1)
while not ModularArithmetic.xgcd( r, public_key.n)[0] == 1:
r = random.randint( 1, public_key.n)
a = pow(public_key.g, plaintext, public_key.nsq)
b = pow(r, public_key.n, public_key.nsq)
ciphertext = (a * b) % public_key.nsq
return ciphertext
def Decrypt(public_key, private_key, ciphertext):
"""
Decrypt( publick_key, private_key, ciphertext)
args:
public_key: Paillier PublicKey object
private_key: Paillier PrivateKey object
ciphertext: Encrypted Integer which was ecnrypted using the public_key
returns:
plaintext: decryption of ciphertext
such that plaintext = L(ciphertext ^ λ) * μ (mod n ^ 2)
where, L(x) = (x - 1) / n
"""
x = pow(ciphertext, private_key.λ, public_key.nsq)
L = lambda x: (x - 1) // public_key.n
plaintext = (L(x) * private_key.μ) % public_key.n
return plaintext
def homomorphic_add(public_key, a, b):
"""
adds encrypted integer a to encrypted integer b
args:
public_key
encryption of integer a
encryption of integer b
returns:
encryption of sum of a and b
"""
return (a * b) % public_key.nsq
def homomorphic_add_constant(public_key, a, k):
"""
adds a plaintext k to encrypted integer a
args:
public_key
encryption of integer a
plaintext k
returns:
encryption of sum of a and k
"""
return a * pow( public_key.g, k, public_key.nsq) % public_key.nsq
def homomorphic_mult_constant(public_key, a, k):
"""
multiplies a plaintext k to encrypted integer a
args:
public_key
encryption of integer a
plaintext k
returns:
encryption of product of a and k
"""
return pow(a, k, public_key.nsq)
|
6de54992bf50db5fd2ed368145ed529891489ac4 | MarkGhebrial/Vigenere-Cipher | /src/cipher.py | 1,145 | 3.890625 | 4 | from alphabet import alphabet, tebahpla
class VigenereCypher:
def __init__ (self, key: str):
self.key = key.lower()
def encryptChar (self, char: str, position: str):
try:
# Get the value of the character, then add the value of the character at key[position] and turn it back into a character
return tebahpla[(alphabet[char.lower()] + alphabet[self.key[position % len(self.key)]]) % len(alphabet)]
except KeyError:
# If the character is not aphanumeric, then don't change it
return char
def encryptString (self, data: str) -> str:
'''Encrypt each character in data, then retun that value
'''
temp = ""
for i in range(len(data)):
temp += self.encryptChar(char=data[i], position=i)
return temp
def decryptChar (self, char: str, position: str) -> str:
try:
return tebahpla[(alphabet[char.lower()] - alphabet[self.key[position % len(self.key)]]) % len(alphabet)]
except KeyError:
return char
def decryptString (self, data: str) -> str:
temp = ""
for i in range(len(data)):
temp += self.decryptChar(char=data[i], position=i)
return temp |
28cc85d0c7238df54395fd865c0b0f72e35672f0 | duhan9836/Algorithm-learning | /GateCircuitsClass.py | 2,818 | 3.796875 | 4 | class LogicGate:
def __init__(self,n):
self.label=n
self.output=None
def getLabel(self):
return self.label
def getOutput(self):
self.output=self.performGateLogic()
return self.output
#at this point, we'll not implement performGateLogic function, because we don't know how each gate will perform its
#own logic operation. Those details will be included by each individual gate that is added to the hierarchy.
class BinaryGate(LogicGate):
def __init__(self,n):
LogicGate.__init__(self,n)
self.pinA=None
self.pinB=None
def getpinA(self):
if self.pinA==None:
return int(input("Enter pinA input for gate"+self.getLabel()+"------>"))
else:
return self.pinA.getFrom().getOutput()
def getpinB(self):
if self.pinB==None:
return int(input("Enter pinB input for gate" + self.getLabel() + "------>"))
else:
return self.pinB.getFrom().getOutput()
def setNextPin(self,source):
if self.pinA==None:
self.pinA=source
elif self.pinB==None:
self.pinB=source
else:
print("Cannot connect: NO EMPTY PINS on this gate.")
class AndGate(BinaryGate)
def __init__(self,n):
BinaryGate.__init__(self,n)
def performGateLogic(self):
a=self.getpinA()
b=self.getpinB()
if a==1 and b==1:
return 1
else:
return 0
class OrGate(BinaryGate)
def __init__(self,n):
BinaryGate.__init__(self,n)
def performGateLogic(self):
a=self.getpinA()
b=self.getpinB()
if a==1 or b==1:
return 1
else:
return 0
class UnaryGate(LogicGate):
def __init__(self,n):
LogicGate.__init__(self,n)
self.pin=None
def getpin(self):
if self.pin==None
return int(input("Enter pin input for gate" + self.getLabel() + "------>"))
else:
return self.pin.getFrom().getOutput()
def setNextPin(self,source):
if self.pin==None:
self.pin=source
else:
print("Cannot connect: NO EMPTY PINS on this gate")
class NotGate(UnaryGate)
def __init__(self,n):
BinaryGate.__init__(self,n)
def performGateLogic(self):
a=self.getpin()
if a==1:
return 0
elif a==0:
return 1
class Connector
def __init__(self,fgate,tgate):
self.fromgate=fgate
self.togate=tgate
tgate.setNextPin(self)
def getFrom(self):
return self.fromgate
def getTo(self):
return self.togate
|
7ecdf60b480adcfac7b8fef15de047471a479cbc | rosierui/hrank | /py/hackerrank/easy/print.py | 397 | 3.671875 | 4 | '''
https://www.hackerrank.com/challenges/python-print/problem
10/01/17 hackos 615
if __name__ == '__main__':
n = int(raw_input())
i = 0
while n > 0:
print str(i),
i += 1
n -= 1
'''
from __future__ import print_function
if __name__ == '__main__':
n = int(raw_input())
i = 1
while n > 0:
print(str(i), end='')
i += 1
n -= 1 |
cecbeeb95edfa05010cb7018b7ad2adb66b360e1 | KnightKnight27/MiscellaneousCode | /Python/depth_first_search.py | 1,423 | 4.15625 | 4 | """
Simple implementation of depth-first search.
"""
import unittest
class Node(object):
def __init__(self, value, neighbours=[]):
self.value = value
self.neighbours = neighbours
def __repr__(self):
return str(self.value)
def __str__(self):
return self.__repr__()
def neighbours_of(node):
"""
Return a list of all neighbours of a given
node, i.e. all nodes which are connected to it by
edges
"""
return node.neighbours
def depth_first_search(start_node):
"""
"""
visited = set([start_node])
print start_node
visit_nodes(start_node, visited)
def visit_nodes(start_node, visited):
for node in neighbours_of(start_node):
if node not in visited:
print node
visited.add(node)
visit_nodes(node, visited)
class TestDepthFirstSearch(unittest.TestCase):
def test_reaches_all_nodes_in_connected_graph(self):
node_1 = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
node_5 = Node(5)
node_6 = Node(6)
node_7 = Node(7)
node_1.neighbours = [node_2, node_3]
node_2.neighbours = [node_3, node_1, node_4]
node_3.neighbours = [node_5]
node_4.neighbours = [node_6]
node_5.neighbours = [node_7]
depth_first_search(node_1)
if __name__ == "__main__":
unittest.main()
|
776900f17bb0ef1d712f6ee9496c2c72adda1ecc | saminnewroad/Python_basics | /untitled2.py | 420 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 15:12:30 2020
@author: 18502
"""
def count(list,name):
count_name=0
for num in list:
if num==name:
count_name=count_name+1
return count_name
a=['samin', 'reena', 'john', 'samin', 'ram', 'reena', 'samin', 'samin', 'reena', 'john', 'samin', 'ram', 'reena', 'samin']
b=set(a)
for num in b:
print(num +str(count(a,num))) |
785f002df0bdc170f7990d42d7d91853f88b3d64 | jaomorro/StanfordCourseraAlgorithms | /Part2/2-sum with hash.py | 1,893 | 3.515625 | 4 | """
Your task is to compute the number of target values tt in the interval [-10000,10000] (inclusive)
such that there are distinct numbers x,yx,y in the input file that satisfy x+y=tx+y=t.
"""
import requests
import json
def load_data(file_name):
"""
load data to be used into a file
:param file_name: file to load the data to
:return: no returned data
"""
url = "https://d18ky98rnyall9.cloudfront.net/_6ec67df2804ff4b58ab21c12edcb21f8_algo1-programming_prob-2sum.txt?Expires=1587772800&Signature=KBufMS4gc7o4tCtPD1ndyUNsfeFuEBOtc1H1T7e63rw9E3XfZZAkMhPefegM7SVcUdhy~z~Yfj56cGXjd2fupteT8AYzsNFn87i5QDM9nqo2PdfwhzAc6AT1R6mXeSOk3S9Ip14ePN~FDsarkPP3-A0L2jCCf-948yybTVuPpX8_&Key-Pair-Id=APKAJLTNE6QMUY6HBC5A"
r = requests.get(url)
data = r.text
with open(file_name,"w") as f:
f.write(data.strip("\n"))
def retrieve_data(file_name):
"""
load data from file into list
:param file_name: name of the file where the data is stored
:return: list of numbers
"""
with open(file_name) as f:
data = f.readlines()
data_list = [int(x.strip("\n")) for x in data]
return data_list
def target_nums(data,target_range):
"""
:param data: list of numbers
:param target_range: min and max of target range
:return: number of target values in range that numbers summed to
"""
min_range,max_range = target_range[0],target_range[1]
target_nums = {}
d = {}
data.sort()
i,j = 0,len(data)-1
while i < j:
num1 = data[i]
num2 = data[j]
if num1 == num2:
i += 1
elif num1 + num2 >= min_range and num1 + num2 <= max_range:
target_nums.setdefault(num1+num2,0)
i += 1
elif num1 + num2 < min_range:
i += 1
elif num1 + num2 > max_range:
j -= 1
return len(target_nums)
def main():
file_name = "Data/HashData.txt"
data = retrieve_data(file_name)
result = target_nums(data,[-10000,10000])
print(f"result = {result}")
if __name__ == "__main__":
main()
|
6d80a3b0537819af425306ac9730d73300ef0b07 | helmutwecke/QmPy | /qmpy/_interpolation.py | 3,596 | 3.796875 | 4 | """Uses routines from scipy.interpolate to interpolate given data sets"""
from scipy.interpolate import interp1d, CubicSpline, KroghInterpolator
from numpy import linspace
def _interpolate(xx, yy, xopt, kind='linear'):
"""
Interpolates two given sets of data points by either linear, natural
cubic spline or polynomial interpolation and returns an array of x-, and
y-values according to the specified intervall.
Args:
xx (1darray): x-coordinates sorted in increasing order.
yy (1darray): Corresponding y-coordinates.
xopt (touple): Options for the generated x-coordinates. Has to have
the form (xmin, xmax, npoints).
kind (str): The kind of interpolation to use. Accepted options are
'linear', 'cspline' or 'polynomial'. Defaults to 'linear'.
Returns:
xint (array): The x-coordinates corresponding the computed
y-values.
yint (array): The interpolated y-coordinates (they are equal to the
potential values)
"""
legal_choices = ['linear', 'cspline', 'polynomial']
if kind not in legal_choices:
msg = """OptionWARNING: Invalid option {} for interpolation, using
default. Valid options are {}"""
print(msg.format(kind, legal_choices))
kind = 'linear'
if kind == 'linear':
intfunc = _linear(xx, yy)
elif kind == 'cspline':
intfunc = _cspline(xx, yy)
else:
intfunc = _poly(xx, yy)
xint = _genx(xopt)
yint = _geny(xint, intfunc)
return xint, yint
def _linear(xx, yy):
"""
Uses linear interpolation to find a function matching a dataset.
Args:
xx (1darray): X-coordinates sorted in increasing order.
yy (1darray): Corresponding y-coordinates.
Returns:
intfunc (function object): The interpolated function.
"""
intfunc = interp1d(xx, yy, fill_value="extrapolate")
return intfunc
def _cspline(xx, yy):
"""
Uses natural cubic spline interpolation to find a function matching
a dataset.
Args:
xx (1darray): X-coordinates sorted in increasing order.
yy (1darray): Corresponding y-coordinates.
Returns:
intfunc (PPoly): The interpolated function.
"""
intfunc = CubicSpline(xx, yy, bc_type='natural')
return intfunc
def _poly(xx, yy):
"""
Uses polynomial interpolation to find a function matching
a dataset.
Args:
xx (1darray): X-coordinates sorted in increasing order.
yy (1darray): Corresponding y-coordinates.
Returns:
intfunc (PPoly): The interpolated function.
"""
intfunc = KroghInterpolator(xx, yy)
return intfunc
def _genx(xopt):
"""
Generates an array of x-values matching the given minimum and maximum
value.
Args:
xopt (touple): Touple of form (xmin, xmax, npoints) where xmax is
always excluded.
Returns:
xx (array): Array ranging from xmin to xmax of shape (npoints,)
"""
xmin, xmax, points = xopt
xx = linspace(xmin, xmax, points)
return xx
def _geny(xx, func):
"""
Generates an array containing y-values corresponding to given x-coordinates
by using a function y = f(x).
Args:
xx (1darray): Array containing the x-values for which matching
y-values shall be computed.
func (callable object): The function used to generate the data.
Returns:
yy (1darray): Array containing y-values matching the supplied
x-coordinates.
"""
yy = func(xx)
return yy
|
63edbc2e92fa108c1c398d4138abc31737a1fc6f | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/grgtay001/question1.py | 323 | 4.34375 | 4 | #Tayla George
#Program to determine if a year is a leap year or not
# 7 March 2014
year = eval(input("Enter a year:\n"))
def leap(year):
if (year%400)==0 or (year%4)==0 and (year%100!=0):
print(year,"is a leap year.")
elif (year//4) + (year%100)>0:
print(year,"is not a leap year.")
leap(year) |
5ad19f59c8133f8667ed27adb8685f1c16d5cd7a | venkateshmoganti/Python-Programes | /Task3.py | 217 | 4.1875 | 4 | # Add the numbers given in the list which are greater than 0
given_list = [1, 2, -3, 4, -5, 6]
total = 0
for element in given_list:
if element > 0:
total += element
else:
continue
print(total)
|
9df357df6b3529424470032b4d214948968ad269 | sanmesh21/Employee-Management-Salary-Receipt-Generator-System | /DSF.py | 1,891 | 3.953125 | 4 | import pandas
data = pandas.read_csv("Employee Data.csv")
#print(data)
#print(data.shape)
while True:
op = int(input("press 1 to find data of hr_locations :\n press 2 to find data of gender :\npress 3 to find data of age :\npress 4 to find data of status :\n press 5 to find data of experience :"))
if op ==1:
n = input("Enter the Hired Location : ")
d = data[data.hr_location == n]
print(d)
elif op == 2:
n = input("Enter the gender : ")
d = data[data.gender == n]
print(d)
elif op == 3:
op = int(input("press1 if you want to find particular age record: \nor\n press 2 if you want to find age in range :"))
if op == 1:
n = int(input("Enter the age :"))
d = data[data.age == n ]
print(d)
elif op == 2:
print("Enter the Age limits: ")
n1 = int(input("Enter the start limit of age :"))
n2 = int(input("Enter the end limit of age :"))
d = data[(data.age >= n1) & (data.age <=n2) ]
print(d)
elif op == 4:
n = input("Enter the status : ")
d = data[data.status == n]
print(d)
elif op == 5:
op = int(input("press1 if you want to find particular experience record: \nor\n press 2 if you want to find experience in range :"))
if op == 1:
n = int(input("Enter the experience :"))
d = data[data.experience == n]
print(d)
elif op == 2:
print("Enter the experience limits: ")
n1 = int(input("Enter the start limit of experience :"))
n2 = int(input("Enter the end limit of experience :"))
d = data[(data.age >= n1) & (data.age <=n2) ]
print(d)
else:
print("Invalid Choice")
break
import employee |
9f45e7cf3f633dc785e22ef63223fc2d3e5e7844 | blueExcess/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 422 | 3.984375 | 4 | #!/usr/bin/python3
from sys import argv
if __name__ == '__main__':
count = 0
if len(argv) == 1:
print("0 arguments.")
exit()
narg = len(argv) - 1
if len(argv) == 2:
print('{} argument:'.format(narg))
else:
print('{} arguments:'.format(narg))
for x in argv:
count += 1
if count == 1:
continue
print('{}: {}'.format(count - 1, x))
|
4c79719002ca8c69f788a1ac9b58ca7ff6c4246f | pratap-rajan/SOLID_blogposts | /wrong.py | 530 | 3.71875 | 4 |
def percentage_of_word(search, file):
search = search.lower()
content = open(file, "r").read()
words = content.split()
number_of_words = len(words)
occurrences = 0
for word in words:
if word.lower() == search:
occurrences += 1
return occurrences/number_of_words
def count_word_occurrences(word, localfile):
content = return open(file, "r").read()
counter = 0
for e in content.split():
if word.lower() == e.lower():
counter += 1
return counter
|
070a95a373716f37f39bd894b17e9930cf4e58f4 | parthi555/pythonProject01 | /train ticket project/forin.py | 587 | 3.734375 | 4 | #language = ['python','mysql','java','javascript','html','css']
#for language in language:
# print(language)
#language = 'python'
#for char in language:
# print(char)
bikes = ['cbr','bmw','ktm','royalenfield']
for bike in bikes:
if bike == 'bmw':
print(bike.upper())
else:
print(bike.title())
chicken_rice = 100
requested_toppings = ['onion','tomatosaurse']
for requested_topping in requested_toppings:
if requested_topping == 'omlet':
chicken_rice += 200
else:
chicken_rice += 150
print(f'chicken rice: {chicken_rice}')
|
41ba2faa467393e2abe204e2f30e3d33a614a35f | guilevieiram/100_days | /snake_game/snake.py | 1,709 | 3.734375 | 4 | import turtle as t
import time
SNAKE_COLOR = 'white'
SEGMENT_SHAPE = 'square'
SEGMENT_SIZE = 20
STEP_SIZE = SEGMENT_SIZE
STARTING_POS = (0, 0)
STARTING_SNAKE_SIZE = 3
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 600
MAX_X = (SCREEN_WIDTH-SEGMENT_SIZE)//2
MAX_Y = (SCREEN_HEIGHT-SEGMENT_SIZE)//2
COLISION_DISTANCE = SEGMENT_SIZE - 1
class Segment(t.Turtle):
def __init__(self) -> None:
super().__init__()
self.shape(SEGMENT_SHAPE)
self.penup()
self.speed(0)
self.color(SNAKE_COLOR)
def hide(self) -> None:
self.hideturtle()
class Snake():
def __init__(self) -> None:
self.snake = []
for _ in range(STARTING_SNAKE_SIZE): self.add_segment()
self.head: Segment = self.snake[0]
def add_segment(self) -> None:
segment = Segment()
if not self.snake:
segment.goto(STARTING_POS)
else:
snakes_last_segment_position = self.snake[-1].position()
segment.goto(snakes_last_segment_position - (SEGMENT_SIZE, 0))
self.snake.append(segment)
def move(self, step: int = STEP_SIZE) -> None:
lenght = len(self.snake)
for seg_num in range(1, lenght)[::-1]:
self.snake[seg_num].goto(self.snake[seg_num - 1].position())
self.head.forward(step)
def turn(self, direction: float) -> None:
if not (self.head.heading() - direction) % 180 == 0:
self.head.setheading(direction)
def colision_with_wall(self) -> bool:
x, y = self.head.position()
return not (abs(x) < MAX_X and abs(y) < MAX_Y)
def colision_with_itself(self) -> bool:
return True in [self.head.distance(segment) < COLISION_DISTANCE for segment in self.snake[1:]]
def delete_snake(self) -> None:
for segment in self.snake:
segment.hide()
def reset(self) -> None:
self.delete_snake()
self.__init__() |
aab0de72e2cee314d56bd7ed249f0f42af082e48 | maniofisint/backups | /learn/DS_codes/projects/multy variable polynomial/code8.py | 3,833 | 3.515625 | 4 | class polynomial:
class Node:
def __init__(self,exp=None, variable=None, coefficient=None, char=None, next=None, updown=None, is_thread=False):
self.exp = exp
self.variable = variable
self.coefficient = coefficient
self.next = next
self.updown = updown
self.is_thread = is_thread
def __init__(self, string):
self.header = self._creat_list(string, None)
def convert(self, string , updown):
lis = self.separate(string)
thread = self.Node(is_thread = True)
for i in range(len(lis)):
if self.is_number(lis[i][0]):
lis[i] = self.Node(coefficient=float(lis[i][0], variable=lis[i][1], exp=lis[i][2]))
else:
lis[i] = self.Node(coefficient=self.convert(lis[i][0]), variable=lis[i][1], exp=lis[i][2])
for i in range(1, len(string)-1):
if string[i] == '(':
newString = str()
newString += '('
Pcount = 1
while Pcount > 0:
i += 1
if string[i] == '(':
Pcount += 1
elif string[i] == ')':
Pcount -= 1
newString += string[i]
newNode = self.Node (None, None, None)
newList = self._creat_list(newString, newNode)
newNode.updown = newList
self.insert_last(head, newNode)
else:
newNode = self.Node(string[i], None, None)
self.insert_last(head, newNode)
return head
def insert_last(self, head, q):
p = head
while not p.next.is_threat:
p = p.next
hold = p.next
p.next = q
q.next = hold
def print_list(self):
print('(', end='')
p = self.header.next
while p is not self.header :
if p.char is not None: #on a character
print(p.char, end='')
p = p.next
else:
if p.updown is not None: #should go down
p = p.updown
else:
if p.is_threat: #should go up
print(')', end='')
p = p.next.updown.next if p.next is not self.header else p.next
else: #p is a header
print('(', end='')
p = p.next
print(')')
def separate(self, string):
def separate_by_plus(string: str):
lis = []
hold = str()
paren_counter = 0
for i in string:
if i == '(': paren_counter += 1
elif i == ')': paren_counter -= 1
elif i == '+':
if paren_counter == 0:
lis.append(hold)
hold = str()
continue
hold += i
lis.append(hold)
return lis
lis = separate_by_plus(string)
hold = str()
for i in range(len(lis)):
ind = len(lis[i]) - 1
while ind >= 0 and lis[i][ind] != ')':
hold = lis[i][ind] + hold
ind -= 1
lis[i] = [lis[i][:ind+1], hold]
hold = str()
var = lis[-1][1][0]
for i in range(len(lis)):
if len(lis[i][1]) == 0:
lis[i] = [lis[i][0][1:-1], var, 0]
elif len(lis[i][1]) == 1:
lis[i] = [lis[i][0][1:-1], var, 1]
else:
lis[i] = [lis[i][0][1:-1], var, int(lis[i][1][2:])]
return lis
|
7f2dcc86275c893fd8cfcc264fe6555722f7987e | eirikurt/sdsort | /test/cases/nested_class.out.py | 710 | 4.03125 | 4 | # create a Color class
class Color:
# constructor method
def __init__(self):
# object attributes
self.name = 'Green'
self.lg = self.Lightgreen()
def __repr__(self):
self.show()
def show(self):
print("Name:", self.name)
# create Lightgreen class
class Lightgreen:
def __init__(self):
self.name = 'Light Green'
self.code = '024avc'
def display(self):
print("Name:", self.name)
print("Code:", self.code)
# create Color class object
outer = Color()
# method calling
outer.show()
# create a Lightgreen
# inner class object
g = outer.lg
# inner class method calling
g.display()
|
60a4652b84f77c9dbe7d04aaa170827b5a58a003 | jhu97/coding-test | /implementation_2.py | 419 | 3.6875 | 4 | import sys
input = sys.stdin.readline
N = int(input())
count = 0
for hour in range(N + 1):
if '3' in str(hour):
count += 60 * 60
else:
for minute in range(60):
if '3' in str(minute):
count += 60
else:
for sec in range(60):
if '3' in str(sec):
count += 1
print(count)
|
500851d3e67eac50eb6451daaf8d871ab68c9c83 | GarethFunk/stateofthechart | /improc/flowchart/line.py | 493 | 3.5 | 4 |
from .small_classes import Connector
class Line:
""" This class is used to represent lines connecting lines"""
startCon = -1
endCon = -1
kinkPoints = []
text = ""
def __init__(self, startNode, startFace, endNode, endFace, startPos = -1, endPos = -1, kinkPoints = [], text = ""):
self.startCon = Connector(startNode, startFace, startPos)
self.endCon = Connector(endNode, endFace, endPos)
self.kinkPoints = kinkPoints
self.text = text
|
e2eeb74cc5252403218f5131e41a85dd43443660 | Pengineer/Python34-Syntax | /simple/Demo26_magic.py | 1,292 | 4 | 4 | # 魔法方法
'''
魔法方法总是被双下划线包围,例如__init__。
魔法方法是面向对象的Python的一切,如果你不知道魔法方法,说明你还没能意识到面向对象的Python的强大。
魔法方法的“魔力”体现在它们总能够子啊适当的时候被自动调用。
'''
# __init__(self[,...])
# 对象实例化时被自动调用
# __new__(cls[,...])
# __init__方法并不是对象实例化时被调用的第一个方法,而是__new__(cls[,...])方法
# 第一个参数数class,后面如果有参数则原封不动的传给__init__方法。
# 这个方法执行后会返回一个类的实例化对象,我们一般不会去重写这个方法。
# 仅当我们修改一个不可变类型时会重写该方法。
#
# 如下,因为str类型是不可变类型,为了强制统一str的格式,我们可以覆写str的__new__(),在创建str对象之前将其进行相应的修改,然后在创建对象。
class CapStr(str):
def __new__(cls, string):
string = string.upper()
return str.__new__(cls, string)
c = CapStr('Hello Python')
print(c)
# __del__(self)
# Python的析构器,当对象要被销毁的时候,这个方法被自动的调用。
# 当一个对象的引用计数为0时,将执行该方法。
|
22c5e33cfe1fea526121f42e024c7e117c76bea4 | ding-cat/Python | /some_learning_code/dictionary.py | 778 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from collections import defaultdict
sentence = "Peter Piper picked a peck of pickled peppers A peck of pickled peppers Peter Piper picked If Peter Piper picked a peck of pickled peppers Wheres the peck of pickled peppers Peter Piper picked"
word_dict = {}
for word in sentence.split():
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1
print(word_dict)
word_dict = defaultdict(int)
for word in sentence.split():
word_dict[word] +=1
print (word_dict)
for key, value in word_dict.items():
print (key, value)
from collections import Counter
words = sentence.split()
word_count = Counter(words)
print (word_count['Peter'])
print (word_dict) |
ccc5e29afa0f9bf4aa4f391a3365ba9c6b6c5499 | xdmiodz/hackerrank | /non_divisible_subset/solution.py | 792 | 3.515625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the nonDivisibleSubset function below.
def nonDivisibleSubset(k, S):
sets = Counter(item % k for item in S)
total_len = int(sets[0] > 0)
midpoint = k // 2 + 1 if k % 2 == 0 else (k + 1) // 2
for p1 in range(1, midpoint):
p2 = k - p1
if p2 != p1:
total_len += max(sets[p1], sets[p2])
else:
total_len += 1
return total_len
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nk = input().split()
n = int(nk[0])
k = int(nk[1])
S = list(map(int, input().rstrip().split()))
result = nonDivisibleSubset(k, S)
fptr.write(str(result) + '\n')
fptr.close()
|
75abdf64941f0b76c1ad2926e45ec6d6aad9d747 | DennicaN/Python-HWs | /HW1_1.py | 363 | 3.859375 | 4 | a = 3
b = "word"
print('Переменная "a" - ', a, 'Переменная "b" слово - ', b)
c = int(input('Укажите челочисленную переменную "c" '))
d = str(input('Укажите строковую переменную "d" '))
print('Ваша переменная с - ', c)
print('Ваша переменная d - ', d)
|
b14e421e79f8e3371b2b99973e3a4641ce7eebb9 | Tz21/python_basic | /start.py | 597 | 4.125 | 4 | #6/11 class1
#數字
print(21)
#字串
print("python字串")
#布林值
print(True)
#變數
input = 3
print(input)
#運算符號
data = 3 + 5
print(data)
data = 5 / 2
print(data)
data = 5 // 2 #整數除法
print(data)
data = 6 * 2
print(data)
data = 6**2 #二次方
print(data)
print('Hello'+'World')
#提示文字
n1 = input("Enter a Number:")
n2 = input("Enter another Number:")
result = n1 + n2
print(result)
n1 = input("Enter a number:")
n2 = input("Enter another number:")
result2 = int(n1) + int(n2)
print(result2)
#homework:讓使用者輸入5個數字,1.算總和 2.哪個數字最大
|
592e13bd33d9a6b3715b1ebb61fe7a2a378f86aa | prithviwarrior/Python_Workspace | /Practice/Swap_case.py | 114 | 3.890625 | 4 | s = "AlPhabET__123"
s2 = ""
for i in s:
if(i.isupper):
s2.join(i.lower)
else:
s2.join(i.upper)
print(s2) |
7e1908b1bdf0e86670547807fc50c1027448da31 | LuLu-89/code_practice | /Disemvowel_Trolls/solution.py | 191 | 3.921875 | 4 | def disemvowel(string):
vowel = ('a', 'e', 'i', 'o', 'u', 'A', 'I', 'E', 'O', 'U')
for x in string:
if x in vowel:
string = string.replace(x, "")
return string |
de1ba6341e45162a26f55b806e5ce6607fa59788 | twyunting/Algorithms-LeetCode | /Easy/String/0459. Repeated Substring Pattern.py | 264 | 3.828125 | 4 | def repeatedSubstringPattern(s):
"""
:type s: str
:rtype: bool
"""
return s in (s + s)[1:-1]
print(repeatedSubstringPattern("abcabc"))
# It's quite evident that if the new string contains the input string, the input string is a repeated pattern string.
|
4cd2512760895cd28a3dc43e9ee8a26d308eba79 | tony-zhu/psapi | /psapi/utils/ipaddress.py | 2,725 | 3.515625 | 4 | """
Helper methods for validating IP addresses,
Code borrowed from:
http://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python
"""
import re
hostname_re = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$')
def is_valid_ipv4(ip):
"""Validates IPv4 addresses.
"""
return ipv4_re.match(ip) is not None
def is_valid_ipv6(ip):
"""Validates IPv6 addresses.
"""
pattern = re.compile(r"""
^
\s* # Leading whitespace
(?!.*::.*::) # Only a single whildcard allowed
(?:(?!:)|:(?=:)) # Colon iff it would be part of a wildcard
(?: # Repeat 6 times:
[0-9a-f]{0,4} # A group of at most four hexadecimal digits
(?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard
){6} #
(?: # Either
[0-9a-f]{0,4} # Another group
(?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard
[0-9a-f]{0,4} # Last group
(?: (?<=::) # Colon iff preceeded by exacly one colon
| (?<!:) #
| (?<=:) (?<!::) : #
) # OR
| # A v4 address with NO leading zeros
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
(?: \.
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
){3}
)
\s* # Trailing whitespace
$
""", re.VERBOSE | re.IGNORECASE | re.DOTALL)
return pattern.match(ip) is not None
def is_valid_hostname(address):
"""
Checks if the address is a valid hostname according to RFC1034#section-3.1
"""
if len(address) > 255:
return False
if address[-1:] == ".":
address = address[:-1]
return all(hostname_re.match(x) for x in address.split("."))
def get_address_type(address):
"""Returns ipv4, ipv6, dns, url, or hostname"""
if address is None:
return None
elif is_valid_ipv4(address):
return 'ipv4'
elif is_valid_ipv6(address):
return 'ipv6'
elif address.find("/") >= 0:
return 'url'
elif is_valid_hostname(address):
# TODO Need better check for toplevel domain names
address_len = len(address)
if address[address_len-3] == '.' or address[address_len-4] == '.':
return None #'dns' not really used often
else:
return 'hostname'
else:
return None
|
7460b20590eca8a953618f198007ffdb0f57ce22 | SchrodingersGat/reverse-geocachr | /scripts/latlon_distance.py | 672 | 4.125 | 4 | from math import *
def distance(p1, p2):
lat1,lon1 = p1
lat2,lon2 = p2
lat1 = lat1 * pi / 180
lat2 = lat2 * pi / 180
lon1 = lon1 * pi / 180
lon2 = lon2 * pi / 180
R = 6371.0
dLat = (lat2 - lat1)
dLon = (lon2 - lon1)
a1 = pow(sin(dLat/2),2)
a2 = pow(sin(dLon/2),2)
a3 = cos(lat1) * cos(lat2)
a = a1 + a2*a3
c = 2 * atan2(sqrt(a),sqrt(1-a))
d = R * c
return d
#stedman house
LAT1 =-41.540351
LON1 = 146.411132
#walters house
LAT2 = -43.033823
LON2 = 147.270602
P1 = (LAT1,LON1)
P2 = (LAT2,LON2)
print "Expected Distance:"
print "179.97Km"
print ""
print "Distance:"
print distance(P2,P1)
|
8d397ec33c015d5950b629c2be90afec6d40803b | A01374862/Mison_05 | /MisionCinco.py | 5,787 | 3.96875 | 4 | # Mariana Mejía Béjar
# Misión 5. El ciclo for y while (menu)
import turtle
from PIL import Image, ImageDraw
from random import randint
# Define el menú que le muestra al usuario las opciones a elegir de aquelo que puede realizar el programa
def menu():
print("Misión 5. Seleccione qué quiere hacer.")
print("1. Dibujar cuadros y círculos")
print("2. Dibujar parábolas en forma de estrella")
print("3. Dibujar espiral")
print("4. Dibujar red")
print("5. Contar divisibles entre 17")
print("6. Imprimir pirámides de números")
print("0. Salir")
opcion = int(input("Qué desea hacer?: "))
return opcion
# Define la función que dibuja los cuadrados y los círculos
def dibujarCuadrosCirculos(imagen):
a = 600
for figura in range(0, 301, 10): #(0, 10, 20, 30, 40... 300(
puntoa = (figura,figura)
puntob = (figura+a, figura+a)
imagen.line(puntoa + (figura+a,figura) + puntob + (figura, figura+a) + (figura,figura), "black")
imagen.ellipse(puntoa+puntob, "white", "black")
a = a-20 #Cada vez que corre el for, le resta 20 al 600 (580...)
# Define la función que dibuja la estrella
def dibujarEstrella(imagen):
for y in range(0, 301, 10): #(0, 10, 20...300)
a = (300, y)
b = (300+y, 300)
# generar color aleatorio
rojo = randint(0,255)
verde = randint(0,255)
azul = randint(0,255)
imagen.line(a+b, (rojo, verde, azul))
for x in range(0, 301, 10): #(0, 10, 20...300)
c = (x, 300)
d = (300, 300+x)
# generar color aleatorio
rojo = randint(0,255)
verde = randint(0,255)
azul = randint(0,255)
imagen.line(c+d, (rojo, verde, azul))
for y in range(0, 301, 10): #(0, 10, 20...300)
e = (300, y)
f = (300-y, 300)
# generar color aleatorio
rojo = randint(0,255)
verde = randint(0,255)
azul = randint(0,255)
imagen.line(e+f, (rojo, verde, azul))
for x in range(300, 601, 10): #(300, 310, 320...600)
g = (x, 300)
h = (300, 900-x)
# generar color aleatorio
rojo = randint(0,255)
verde = randint(0,255)
azul = randint(0,255)
imagen.line(g+h, (rojo, verde, azul))
# Define la función que por medio de la tortuga dibujará un espiral
def dibujarEspiral():
turtle.color("black")
for t in range (5, 601, 10): #(5, 15, 25... 600)
turtle.forward (t)
turtle.left (90)
turtle.forward (t+5)
turtle.left (90)
turtle.forward (t+5)
turtle.left (90)
turtle.forward (t+10)
turtle.left (90)
turtle.speed(7)
# Define la función que va a dibujar la red
def dibujarRed(imagen):
for linearojo in range(0,601,20): #(0, 20, 30, 40... 600)
la=(0,600-linearojo)
lb=(linearojo,600)
lc=(600,linearojo)
ld=(600-linearojo,0)
imagen.line(la+lb,"red")
imagen.line(lc+ld,"red")
for lineaazul in range(0,601,20): #(0, 20, 30, 40... 600)
le=(0,lineaazul)
lf=(lineaazul,0)
lg=(lineaazul,600)
lh=(600,lineaazul )
imagen.line(le+lf, "blue")
imagen.line(lg+lh, "blue")
# Define la función que dice cuántos números son divisibles entre 17
def dividirNumeros():
cantidad = 0
for numero in range (1000,10000,1): #Empieza desde el 1000 porque se piden números de 4 dígitos. Se pone hasta el 10000 para que se incluya el 9999 (1000, 1001, 1002, 1003, 1004... 9999).
if numero%17 == 0:
'''print (numero, "es divisible entre 17")'''
#El contador va sumando 1 al número previo cada vez que encuentra un número divisible netre 17
cantidad = cantidad+1
print (cantidad, "números de 4 dígitos se pueden dividir entre 17.") #El contador nos dice cuantos número detectó que se pueden dividir exactamente entre 17
# Define la función que se encarga de realizar las pirámides de números
def calcularPiramide():
a = 0
for x in range (1, 10, 1): #Rango de 9. (1, 2, 3... 9)
a = (a * 10) + x
b = (a * 8) + x
print (a,"* 8 +", x, "=", b)
print (" ")
c = 0
d = 0
for x in range (1, 10, 1): #Rango de 9. (1, 2, 3... 9)
c = (c * 10) + 1
d = (d * 10) + 1
e = c * d
print (c, "*", d,"=", e)
# Define la función principal
def main():
opcion = menu()
while opcion !=0 :
if opcion == 1:
img = Image.new("RGB", (600, 600), "white")
imagen = ImageDraw.Draw(img)
dibujarCuadrosCirculos(imagen)
img.show()
elif opcion == 2:
img = Image.new("RGB", (600, 600), "white")
imagen = ImageDraw.Draw(img)
dibujarEstrella(imagen)
img.show()
elif opcion == 3:
dibujarEspiral()
elif opcion == 4:
img = Image.new("RGB", (600, 600), "white")
imagen = ImageDraw.Draw(img)
dibujarRed(imagen)
img.show()
elif opcion == 5:
print(" ")
cantidad = dividirNumeros()
print(" ")
elif opcion == 6:
print(" ")
calcularPiramide()
print(" ")
else:
print(" ")
print("ERROR: Favor de insertar un número del 0 al 6")
print(" ")
opcion = menu()
main()
|
a6cdd9c65fef8eff9116998d4c3ebfff1f2fc1e5 | MihaelaGaman/InterviewProblemsSolved | /algorithms_python/longestPalindromicSubstring.py | 1,588 | 4.25 | 4 | """
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
def longestPalindrome(s):
max_len = 1
start = 0; low = 0; high = 0
n = len(s)
# Consider each character as center point of even len palindromes
for i in xrange(1, n):
# Find the longest even len palindrome with center points i-1 and i.
low = i - 1
high = i
while low >= 0 and high < n and s[low] == s[high]:
if high - low + 1 > max_len:
start = low
max_len = high - low + 1
low -= 1
high += 1
# Find the longest odd len palindrome with center point i
low = i - 1
high = i + 1
while low >= 0 and high < n and s[low] == s[high]:
if high - low + 1 > max_len:
start = low
max_len = high - low + 1
low -= 1
high += 1
return s[start:start + max_len]
# Test 1
s = "babad"
print "Test 1: ", s, " longest palindrome = ", longestPalindrome(s)
# Test 2
s = "cbbd"
print "Test 2: ", s, " longest palindrome = ", longestPalindrome(s)
# Test 3
s = "bbbb"
print "Test 3: ", s, " longest palindrome = ", longestPalindrome(s)
# Test 4
s = "a"
print "Test 4: ", s, " longest palindrome = ", longestPalindrome(s)
# Test 5
s = "aacdefcaa"
print "Test 5: ", s, " longest palindrome = ", longestPalindrome(s)
|
6190436ff727f1bfb91b686616c1937e6a4047d6 | jcarball/python-programs | /funcion año bisiesto.py | 477 | 3.75 | 4 | def isYearLeap(year):
#
if (year % 4 == 0) and (year%100 !=0 or year%400 == 0):
result = True
print(result)
else:
result = False
print(result)
return result
# coloca tu código aquí
#
testData = [1900, 2000, 2016, 1987]
testResults = [False, True, True, False]
for i in range(len(testData)):
year = testData[i]
print(year,"->",end="")
result = isYearLeap(year)
if result == testResults[i]:
print("OK")
else:
print("Error") |
c887e704041221d22aaa322f6dff400242e1bcf4 | dzarrr/Project-Euler | /problem7.py | 521 | 3.75 | 4 | ## Dzar Bela Hanifa
## Project Euler no 7
## Written in Python 3.7
def generate_prime_sieve(n):
sieve = []
for i in range (0, n + 1):
sieve.append(True)
prime_sieve = []
for i in range (2, n + 1) :
if sieve[i] :
prime_sieve.append(i)
for j in range (i + i, n + 1, i) :
sieve[j] = False
return prime_sieve
max_number = int(input("Bilangan maksimum : "))
n = int(input("Bilangan prima ke berapa yang anda cari ? : "))
prime_list = generate_prime_sieve(max_number)
print (prime_list[n-1])
|
48302d9c32afb7c8e2b33b54eac885ba115ee8a3 | rystills/OpSys-Project2 | /MemoryStore.py | 12,841 | 3.6875 | 4 | from Process import Process
from enum import Enum
from Event import Event, EventType
import bisect
import Simulator
"""
State is a simple enum containing each of the potential process states
"""
class MemoryAlgorithm(Enum):
nextFit = 1
firstFit = 2
bestFit = 3
"""
The MemoryStore class represents an array of memory slots with a set number of frames
"""
class MemoryStore():
"""
MemoryStore contructor: creates a new memory store with the desired number of frames
@param numFrames: the fixed number of frames that can be stored here
@param framesPerLine: optional arg specifying how many frames of memory to output per-line (has no effect on internal repr)
"""
def __init__(self, numFrames=256, framesPerLine=32):
self.numFrames = numFrames
self.framesPerLine = framesPerLine
self.memory = '.'*numFrames
#store a list of processes currently in the memory store (sorted in order of smallest to greatest memLocation)
self.processes = []
self.lastPlacedLoc = 0
self.t_memmove = 1
#dict of pid:[(pageNum,frameNum)]
self.pageTable = {}
"""
get the amount of free memory currently available in the store
"""
def getFreeMemory(self):
return self.memory.count('.')
"""
get a list containing the location and size of each free block of memory
"""
def getFreeMemoryLocations(self):
memLocs = []
inMemBlock = False
memStartPos = -1
#iterate over the memory store to find the beginning of each block of memory
for i in range(len(self.memory)):
if (self.memory[i] == '.'):
if (not inMemBlock):
inMemBlock = True
memStartPos = i
else:
if (inMemBlock):
inMemBlock = False
memLocs.append([memStartPos,(i-memStartPos)])
#if we were still reading free memory when we reached the end of the store, add the remaining memory to the list of locations
if (inMemBlock):
memLocs.append([memStartPos,(i+1-memStartPos)])
return memLocs
"""
return a string representing this store's memory, split into lines as specified by framesPerLine
"""
def __str__(self):
border = '='*self.framesPerLine
return border + '\n' + '\n'.join([self.memory[i:i+self.framesPerLine] for i in range(0, self.numFrames, self.framesPerLine)]) + '\n' + border
"""
print the current state of the page table
"""
def displayPageTable(self):
print("PAGE TABLE [page,frame]:")
#print out the page table ordered by pid
keys = list(self.pageTable.keys())
keys.sort()
for key in keys:
print("{0}: ".format(key),end='')
#print out all entries corresponding to this key, with a newline after every 10th entry
vals = self.pageTable[key]
for i in range(len(vals)):
print((' ' if i%10 != 0 else '') + str(vals[i]).replace('(','[').replace(')',']').replace(' ',''),end=('\n' if (i+1)%10 == 0 else ''))
#print a newline before moving on to the next value unless we just finished a row
if (len(vals) % 10 != 0):
print()
"""
check whether or not a defragmentation will free up enough space to place the desired process
@param memNeeded: the amount of memory we need to have after defragmenting
"""
def defragmentWillWork(self, memNeeded):
return memNeeded <= self.getFreeMemory()
"""
defragment our memory, moving processes up to fill all free gaps, and increasing simTime accordingly
"""
def defragment(self):
#keep track of how far we move time forward so we can push back events accordingly
prevSimTime = Simulator.simTime
affectedProcesses = []
self.lastPlacedLoc = 0
for proc in self.processes:
earliestFree = self.memory.find('.')
if (earliestFree < proc.memLocation):
#there is free space in our memory before this location's starting value; move it up and increment time accordingly
removedMem = self.memory[:proc.memLocation] + self.memory[proc.memLocation+proc.memSize:]
reinsertedMem = removedMem[:earliestFree] + proc.pid * proc.memSize + removedMem[earliestFree:]
self.memory = reinsertedMem
#add t_memmove for each frame of memory in the process
Simulator.simTime += self.t_memmove * proc.memSize
affectedProcesses.append(proc)
proc.memLocation = earliestFree
timeDiff = Simulator.simTime - prevSimTime
#update all events to compensate for elapsed time during defragmentation
for ev in Simulator.events.queue:
ev.time += timeDiff
print("time {0}ms: Defragmentation complete (moved {1} frames: {2})".format(Simulator.simTime,timeDiff,
str([p.pid for p in affectedProcesses]).strip('[').strip(']').replace("'","")))
print(self)
"""
insert the specified process into our processes list sorted by memLocation
"""
def insertProcess(self,process):
bisect.insort(self.processes,process)
"""
remove the specified process from the memory store
"""
def removeProcess(self,process):
if (process.pid in self.pageTable):
self.pageTable.pop(process.pid)
#iterate over memory, removing all references to the process
for i in range(len(self.memory)):
if (self.memory[i] == process.pid):
self.memory = self.memory[:i] + '.' + self.memory[i+1:]
else:
#remove the process from memory
self.memory = self.memory[:process.memLocation] + '.'*process.memSize + self.memory[process.memLocation+process.memSize:]
#remove the process from our processes list
self.processes.remove(process)
"""
add the desired process at the specified location in memory
@param process: the process to add into memory
@param loc: the location in memory at which to add the process
@returns true
"""
def addProcessAtLocation(self,proc,loc):
proc.memLocation = loc
self.memory = self.memory[:loc] + proc.pid*proc.memSize + self.memory[loc+proc.memSize:]
proc.memEnterTime = Simulator.simTime
self.insertProcess(proc)
self.lastPlacedLoc = loc + proc.memSize
return True
"""
check if we are on the first pass of attempting to add a process. if so, defrag if it will generate enough space
@param firstRun: whether this is the first time we have attempted to add the process during this event (true) or not (false)
@param func: the add function to call again after defragmenting
@param proc: the process we wish to add
@returns a call to the specified function after defragmenting if this is the first run and defragmenting will help; otherwise false
"""
def checkFirstRun(self,firstRun, func, proc):
if (firstRun):
if (self.defragmentWillWork(proc.memSize)):
print("time {0}ms: Cannot place process {1} -- starting defragmentation".format(Simulator.simTime,proc.pid))
self.defragment()
return func(proc,False)
#we already defragmented and still didn't find a location, so nothing we can do
return False
"""
add a process to memory utilizing our page table
@param process: the process to add to memory
@returns whether the process was added successfully (true) or not (false)
"""
def addProcessPageTable(self, process):
#first make sure there is enough space in memory
if (not self.defragmentWillWork(process.memSize)):
return False
#begin building up a list of pid memory locations, to be added to our pageTable at the end
newPages = []
pagesAdded = 0
for i in range(len(self.memory)):
if (self.memory[i] == '.'):
#this memory slot is free; add the process here
self.memory = self.memory[:i] + process.pid + self.memory[i+1:]
newPages.append((pagesAdded,i))
pagesAdded += 1
#stop once we've allocated enough pages
if (pagesAdded == process.memSize):
break
#apply the new pageList to the pageTable and return success
self.pageTable[process.pid] = newPages
self.processes.append(process)
return True
"""
add a process to the store using the next-fit algorithm
@param process: the process to be added
@param firstRun: whether we are running the process for the first time (true) or immediately after a defragmentation (false)
"""
def addProcessNext(self,process, firstRun = True):
#iterate from lastPlacedLoc to the end of memory, looking for a large enough slot
pos = self.lastPlacedLoc
while (pos+process.memSize <= len(self.memory)):
if (self.memory[pos] == '.'):
#this is a valid space and our process will fit; now check that all required slots are free
slotsFree = True
for i in range(process.memSize):
if (self.memory[pos+i] != '.'):
slotsFree = False
break
if (slotsFree):
return self.addProcessAtLocation(process,pos)
pos += 1
#we didn't find a valid memory location after lastPlacedLoc, so now let's search again from the beginning up to lastPlacedLoc
pos = 0
while (pos < self.lastPlacedLoc and pos+process.memSize <= len(self.memory)):
if (self.memory[pos] == '.'):
#this is a valid space and our process will fit; now check that all required slots are free
slotsFree = True
for i in range(process.memSize):
if (self.memory[pos+i] != '.'):
slotsFree = False
break
if (slotsFree):
return self.addProcessAtLocation(process,pos)
pos += 1
#we didn't find a location at which to place the process, so defragment and try again
return self.checkFirstRun(firstRun,self.addProcessNext,process)
"""
add a process to the store using the first-fit algorithm
@param process: the process to be added
@param firstRun: whether we are running the process for the first time (true) or immediately after a defragmentation (false)
"""
def addProcessFirst(self,process, firstRun = True):
freeLocs = self.getFreeMemoryLocations()
#check all free memory locations for the first location big enough to contain the new process
for loc in freeLocs:
if (loc[1] >= process.memSize):
#we found a location for the process! add it to the processes list
return self.addProcessAtLocation(process,loc[0])
#we didn't find a location at which to place the process, so defragment and try again
return self.checkFirstRun(firstRun,self.addProcessFirst,process)
"""
add a process to the store using the best-fit algorithm
@param process: the process to be added
@param firstRun: whether we are running the process for the first time (true) or immediately after a defragmentation (false)
"""
def addProcessBest(self,process, firstRun = True):
freeLocs = self.getFreeMemoryLocations()
#check all free memory locations for the smallest location big enough to contain the new process
smallestValidLocSize = None
smallestValidLoc = None
for loc in freeLocs:
if (loc[1] >= process.memSize):
if (smallestValidLocSize == None or loc[1] < smallestValidLocSize):
smallestValidLocSize = loc[1]
smallestValidLoc = loc[0]
if (smallestValidLoc != None):
#we found a location for the process! add it to the processes list
return self.addProcessAtLocation(process,smallestValidLoc)
#we didn't find a location at which to place the process, so defragment and try again
return self.checkFirstRun(firstRun,self.addProcessBest,process) |
cc05a8a28941b1c4b31ede3631a770479c32e822 | Lucas-Severo/python-exercicios | /mundo01/ex005.py | 380 | 4.15625 | 4 | '''
Faça um programa que leia um número Inteiro e
mostre na tela o seu sucessor e seu antecessor.
'''
num = int(input('Digite um número: '))
ant = num - 1
suc = num + 1
print('Analisando o valor {}, seu antecessor é {} e o seu sucessor é {}'.format(num, ant, suc))
# print('Analisando o valor {}, seu antecessor é {} e o seu sucessor é {}'.format(num, (num-1), (num+1)))
|
a021cca1d12985ef1dee9a61657950af4dc9780f | SobrancelhaDoDragao/Exercicio-De-Programacao | /Exercicios-Python/Basico/Exercicios/exercicio22.py | 643 | 4.25 | 4 | #Crie um programa que leia o nome completo de uma pessoa e mostre:
# O nome com todas as letras maiúsculas
# O nome com todas minúsculas.
# Quantas letras ao todo(sem considerar espaços)
# Quantas letras tem o primeiro nome.
nome_completo = input("Digite seu nome completo: ").strip()
print("Seu nome com todas as letras maiúsculas:{}".format(nome_completo.upper()))
print("Seu nome com todas as letras minúscilas:{}".format(nome_completo.lower()))
print("Total de letras que seu nome possui:{}".format(len(nome_completo) - nome_completo.count(' ')))
print("Total de letras do seu primeiro nome é: {}".format(nome_completo.find(" ")))
|
a7fbe27b49dbdea37643257150886bcacffb1548 | snehahegde1999/sneha | /program-string.py | 102 | 3.953125 | 4 | a=[1,2,3,4,5,6]
print (a)
#adding one string with another string
a=[1,2,3]
b=a+[4,5,6]
a=[1,2,3]*2
|
85201b899787af938c628561a5f814a02fbdeb90 | Lebhoryi/Leetcode123 | /73. 矩阵置零.py | 1,218 | 3.5 | 4 | # coding=utf-8
'''
@ Summary:
@ Update:
@ file: 73. 矩阵置零.py
@ version: 1.0.0
@ Author: [email protected]
@ Date: 2/24/20 9:03 PM
'''
def setZeroes(matrix: [[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# 获取每一行,假如有0 就整行置为0
row = [[0] * len(i) if 0 in i else i for i in matrix]
# 获取每一列,假如有0 就整列置为0
col = [[0] * len(j) if 0 in j else list(j) for j in zip(*matrix)]
# 将列排序转换为行排序
# zip(*col) 不能直接通过zip(*col)[1]取值,且返回的是元组
# 下面做了两步转换,先将zip()返回的各个元组转换为列表,在将整个转换为list
# 上面一行效果等同:
col2row = list(map(list, zip(*col)))
# col2row = [list(i) for i in zip(*col)]
for i in range(len(matrix)):
# 替换matrix各行
# matrix[i] = col2row[i]
# # 如果一整行为0, 则替换为0
# if row[i] == [0] * len(matrix[0]):
# matrix[i] = row[i]
matrix[i] = col2row[i] if row[i] != [0] * len(matrix[0]) else row[i]
matrix = [
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
setZeroes(matrix)
print(matrix) |
205d3aeee7b72035960929c3a7f1120e2b897385 | gamejobmob/python | /스무고개놀이.py | 586 | 3.671875 | 4 | import random
secretNum = random.randint(1, 100)
print("1부터 100까지의 숫자가 있어요")
for i in range(20):
print("에상하는 숫자를 입력해")
guess = int(input("숫자"))
if guess < secretNum:
print("예상한 숫자가 너무 작아요")
elif guess > secretNum :
print("예상한 숫자가 너무 커요")
else :
break
if guess == secretNum:
print("승리! 정답입니다")
print("%d번만에 맞추었어요"%i)
else :
print("패배하였습니다. 정답은 %d입니다"%secretNum)
|
c70520225cbe1bfd71b84d890bc0dd4a76c1bf25 | ibrahim272941/python_projects | /Armstrong_number.py | 632 | 3.984375 | 4 | num = (input('pls enter a number\t:'))
digit = str(num)
summ = 0
if num.isdigit():
for i in digit :
num_1 = int(i) ** len(digit)
summ +=num_1
num = int(num)
if num == summ :
print(f'{num} is Amrstrong number !!!!')
else:
print(f'{num} is not Armstrong number')
elif num.isalpha():
print(' It is an invalid entry. Dont use non-numeric, float, or negative values!')
elif float(num) < 0:
print(' It is an invalid entry. Dont use non-numeric, float, or negative values!')
else:
print('It is an invalid entry. Dont use non-numeric, float, or negative values!')
|
daa20da55a1c16106bbad4dcae559d6971d48af9 | megcrow/code_academy_practice | /grade_calculator.py | 1,628 | 4.28125 | 4 | #!/usr/bin/python
# A calculator for grades, student scores are stored in dictionaries
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
# Gets float average of argument
def average(numbers):
total = sum(numbers)
total = float(total)
return total/len(numbers)
# Returns weighted average of student grade.
# Homework = 10%, Quizzes = 30%, Tests = 60%
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student['tests'])
return 0.1*homework + 0.3*quizzes + 0.6*tests
# Returns letter grade
def get_letter_grade(score):
if score >= 90.:
return "A"
elif score < 90. and score >= 80.:
return "B"
elif score < 80 and score >= 70.:
return "C"
elif score < 70 and score >= 60:
return "D"
else:
return "F"
# Calculates class average and returns result
def get_class_average(class_list):
results = []
for student in class_list:
results.append(get_average(student))
return average(results)
# Prints the letter grade of Lloyd's weighted average number grade
print get_letter_grade(get_average(lloyd))
# Gets class average and prints to the console
students = [alice, lloyd, tyler]
print get_class_average(students)
|
a933bce34b2b8d4f6026679898bb7b9d2f7ef6c1 | thoma55s/KattisSolutions | /CD.py | 333 | 3.578125 | 4 |
index = 0
while True:
firstInput = raw_input()
if(firstInput == "0 0"):
break
numOfCds = firstInput.split(" ")
jack = int(numOfCds[0])
jill = int(numOfCds[1])
jacks = []
s = set(int(raw_input()) for _ in range(jack))
incommon = 0
for _ in range(jill):
if(int(raw_input()) in s):
incommon += 1
print(incommon) |
782a8dd59cf07883a7e233f9a6711847a283730b | pavi-ninjaac/HackerRank | /Python_challege/counter.py | 1,497 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 31 16:54:35 2020
@author: ninjaac
"""
###################Collections
import collections
################################################################################
#defaultdict
from collections import defaultdict
#it will assign the default value automatically if the key is not defined yet
#it will take a function as default factor and return that if the unknow value is accessed
def default_factor():
return "Not present in the dict!!"
d = defaultdict(default_factor)
d['a'] = 1
d['b'] = 2
print(d) #defaultdict(<function default_factor at 0x07696CD8>, {'a': 1, 'b': 2})
#which is not present
print(d['C']) #Not present in the dict!!
################################################################################
#defaultdict
# creating default with list
d=defaultdict(list)
n,m = map(int,input().split())
for i in range(n+m):
d[input()].append(i)
print(d)
################################################################################
#defaultdict
from collections import defaultdict
d = defaultdict(list)
list1=[]
n, m = map(int,input().split())
for i in range(0,n):
d[input()].append(i+1)
for i in range(0,m):
list1=list1+[input()]
for i in list1:
if i in d:
print(" ".join( map(str,d[i]) ))
else:
print -1
################################################################################
#defaultdict
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.