blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
be01f32ed478acf37072f7a5c4da10fe668dad64 | MidDevOps/DevOps_Online_Summer_Program_2020 | /m7/task7.1/count_vowels_unittest.py | 1,001 | 3.84375 | 4 | import count_vowels
import unittest
class FizzBuzzTest(unittest.TestCase):
def test_fizz(self):
string = "aeiou"
only_unique_letters = set(string)
result = count_vowels.get_vowels(string)
self.assertEqual(result[0], 5)
for vowel in only_unique_letters:
self.assertEqual(result[1].get(vowel, None), 1)
def test_buzz(self):
string = "aaeeiioouu"
only_unique_letters = set(string)
result = count_vowels.get_vowels(string)
self.assertEqual(result[0], 10)
for vowel in only_unique_letters:
self.assertEqual(result[1].get(vowel, None), 2)
def test_fizzbuzz(self):
string = "aaaeeeiiiooouuu"
only_unique_letters = set(string)
result = count_vowels.get_vowels(string)
self.assertEqual(result[0], 15)
for vowel in only_unique_letters:
self.assertEqual(result[1].get(vowel, None), 3)
if __name__ == '__main__':
unittest.main() |
0c4982d9184fd467e581a23cfdf8779a89543608 | nayomipoligami/repeat | /5.bölümödevler/deneme.py | 277 | 3.71875 | 4 | print("""
****************
mükemmel sayı
****************
""")
sayı = int(input("Lütfen bir sayı giriniz: "))
liste = list()
for i in range(1, sayı):
if sayı % i == 0:
liste.append(i)
if sum(liste) == sayı:
print("Mükemmel sayı")
|
153dc6c60d2afc0a73f41c5db62a954e94c34035 | samuelfranca7l/PythonExercises | /exercicios/PythonExercicios_Desafio086.py | 291 | 3.875 | 4 | matrix = [[], [], []]
for i in range(0, len(matrix)):
for n in range(0, 3):
matrix[i].append(int(input(f'Digite um valor para [{i},{n}]: ')))
print('=-' * 30)
for i in range(0, len(matrix)):
for n in range(0, 3):
print(f'[ {matrix[i][n]:^5} ]', end='')
print('')
|
5e2bff807d76575253fe5c31ab381f89577dbbaa | leosty/sort_python | /sort_test.py | 2,436 | 3.90625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Time: 2018/10/15 15:27
#
# # 1. 插入排序
# def insert_sort(ilist):
# for i in range(0, len(ilist)):
# for j in range(i):
# if ilist[i] < ilist[j]:
# ilist.insert(j, ilist.pop(i))
# return ilist
#
# ilist = insert_sort([2, 3, 4, 7, 9, 8, 5, 6, 10])
# print '插入:', ilist
#
# # 2. 希尔排序
# def shell_sort(slist):
# gap = len(slist)
# while gap > 1:
# gap = gap // 2
# for i in range(gap, len(slist)):
# for j in range(i % gap, i, gap):
# if slist[i] < slist[j]:
# slist[i], slist[j] = slist[j], slist[i]
# return slist
#
# slist = shell_sort([2, 3, 4, 7, 9, 8, 5, 6, 10])
# print '希尔:', slist
#
# # 3. 冒泡排序
# def bubble_sort(blist):
# count = len(blist)
# for i in range(0, count):
# for j in range(i + 1, count):
# if blist[i] > blist[j]:
# blist[i], blist[j] = blist[j], blist[i]
# return blist
# blist = bubble_sort([2, 3, 4, 7, 9, 8, 5, 6, 10])
# print '冒泡:', blist
#
#
# # 4. 快速排序 将要排列的数据分成两组,一部分的所有数据都要比林一部分的数据要小
# # 然后再按此方法对这两部分数据分别进行快速排序,整个排序可以进行递归进行。
# 时间复杂度: O(nlog2n) 空间复杂度O(nlog2n) 稳定性:不稳定
#
# def quick_sort(qlist):
# if qlist == []:
# return []
# else:
# qfirst = qlist[0]
# qless = quick_sort([l for l in qlist[1:] if l < qfirst])
# qmore = quick_sort([m for m in qlist[1:] if m >= qfirst])
# return qless + [qfirst] + qmore
# qlist = quick_sort([2, 3, 4, 7, 9, 8, 5, 6, 10])
# print '快排:', qlist
# 5. 选择排序 选择第一个值,然后从待排序的队列中找出最小的值,
# 将它与第一个交换,然后第二趟找后面待排队列中的最小值,交换位置,以此类推。
# 时间复杂度: O(n^2) 空间复杂度O(1) 稳定性:不稳定
def select_sort(slist):
for i in range(len(slist)):
x = i
for j in range(i + 1, len(slist)):
if slist[j] < slist[x]:
x = j
slist[i], slist[x] = slist[x], slist[i]
return slist
slist = select_sort([2, 3, 4, 7, 9, 8, 5, 6, 10])
print '选择:', slist
|
538ecce26a2b78b8a9294e9f29674ecb4e906b59 | illagrenan/block-timer | /block_timer/timer.py | 2,256 | 3.890625 | 4 | # -*- encoding: utf-8 -*-
# ! python3
import sys
import time
from contextlib import ContextDecorator
from typing import Optional
__all__ = ["Timer"]
class Timer(ContextDecorator):
"""
Timer class that can be used both as a context manager and function/method decorator.
Usage:
>>> import math
>>> import time
>>>
>>> with Timer():
... for i in range(42):
... print("{}! = {:.5}...".format(i**2, str(math.factorial(i**2))))
>>>
>>> @Timer(title="Second")
... def some_func():
... time.sleep(1)
>>>
>>> with Timer(title="Some title") as t:
... for i in range(42):
... print("{}! = {:.5}...".format(i**2, str(math.factorial(i**2))))
>>>
>>> print(t.elapsed)
"""
def __init__(self, title: str = "", print_title: Optional[bool] = True, print_file=sys.stderr):
"""
Instantiate new Timer.
:param title: Title (prefix) that will be printed
:param print_title: Should print elapsed time?
:param print_file: File that will be passed to print function, see: https://docs.python.org/3/library/functions.html#print
"""
self._title = title
self._print_title = print_title
self._print_file = print_file
self._elapsed = 0
def __float__(self) -> float:
return float(self.elapsed)
def __str__(self) -> str:
"""
“informal” or nicely printable string representation of an object
"""
return "Elapsed {}".format(self.__repr__())
def __repr__(self) -> str:
"""
“official” string representation of an object.
"""
return str(float(self))
def __enter__(self) -> 'Timer':
self.start = time.perf_counter()
return self
def __exit__(self, *args):
self._elapsed = time.perf_counter() - self.start
if self._print_title:
title = "[{}] ".format(self._title) if self._title else ""
formatted_title = '{title}Total time {total_seconds:.5f} seconds.'.format(title=title, total_seconds=self._elapsed)
print(formatted_title, file=self._print_file)
@property
def elapsed(self) -> float:
return self._elapsed
|
26653cab8f92eb296cac98b55ec3c3567e9bbcbb | Luisa158/LaboratorioContAcumRemote | /primosB.py | 245 | 3.75 | 4 |
a= int(input("Por favor, ingrese un número "))
i = 1
cont=0
while i<=a:
if a % i == 0:
print("divisor:", i)
cont=cont+1
i=i+1
if cont> 2:
print("El número no es primo")
else:
print("El número es primo")
|
116101cf222972a1f08f4246e8d2f789e26c46cf | sophmintaii/tic-tac-toe | /btree.py | 1,897 | 3.609375 | 4 | """
Contains Linked Binary Tree implementation.
"""
class LinkedBinaryTree:
"""
Linked Binary Tree representation.
"""
def __init__(self, root):
"""
Creates a new LinkedBinaryTree onject.
"""
self.key = root
self.left_child = None
self.right_child = None
def insert_left(self, new_node):
"""
Inserts left child tree to the self.
"""
if self.left_child is None:
self.left_child = LinkedBinaryTree(new_node)
else:
temp = LinkedBinaryTree(new_node)
temp.left_child = self.left_child
self.left_child = temp
def insert_right(self, new_node):
"""
Inserts right child tree to the self.
"""
if self.right_child is None:
self.right_child = LinkedBinaryTree(new_node)
else:
temp = LinkedBinaryTree(new_node)
temp.right_child = self.right_child
self.right_child = temp
def leaves_list(self):
"""
Returns leaves of the tree.
"""
def check_if_leaf(tree, leaves):
"""Recursive helping function."""
if tree.left_child is None and tree.right_child is None:
leaves.append(tree.key)
if tree.left_child is not None:
check_if_leaf(tree.left_child, leaves)
if tree.right_child is not None:
check_if_leaf(tree.right_child, leaves)
leaves = []
check_if_leaf(self, leaves)
return leaves
def get_right_child(self):
"""
Returns right child of the tree.
"""
return self.right_child
def get_left_child(self):
"""
Returns left child of the tree.
"""
return self.left_child
|
07d46e4bd33ed1d68bbe38cfbac883f5c44d78c7 | priyansh210/Airline_Reservation_and_Management_System-python | /user/payment.py | 1,127 | 3.734375 | 4 |
import menu.usermenu as usermenu
import sql
mycursor=sql.mycursor
mydb=sql.mydb
def make_booking(udft):
l=len(udft)
for i in range(l):
mycursor.execute("INSERT INTO BOOKING VALUES"+str(tuple(udft.loc[i,:])))
mydb.commit()
print("YOUR FLIGHT HAS BEEN BOOKED !")
input("> ")
username = udft.at[0,'username']
return usermenu.user_menu(username)
def payment(total_amount,udft):
print("--WELCOME TO THE PAYMENT PORTAL--")
cc_no=int(input("ENTER CREDIT CARD NUMBER : "))
if len(str(cc_no)) != 16:
print("enter correct credit card no. ")
payment(total_amount,udft)
udft.loc[:,["creditcard"]]=str(cc_no)
cvv=int(input("ENTER CREDIT CARD CVV (4 max): "))
if len(str(cvv)) > 4:
print("enter correct cvv")
payment(total_amount,udft)
input("ENTER CREDIT CARD EXPIRY (MM-YYYY): ")
print(total_amount,"+",(18/100)*total_amount, "(tax) : Rs is to be deducted ")
random=input("PRESS ENTER TO AGREE >")
if random=='':
make_booking(udft)
else:
payment(total_amount,udft)
|
75f4b60f10d387655676ca32a6d0076b0b0df082 | 0xJayShen/arithmetic | /有序列表合并.py | 1,296 | 3.75 | 4 | # -*- coding: utf8 -*-
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# def mergeTwoLists(l1, l2):
# l = head = ListNode(0)
# while l1 and l2:
# if l1.val <= l2.val:
# l.next, l1 = l1, l1.next
# else:
# l.next, l2 = l2, l2.next
# l = l.next
# l.next = l1 or l2
# return head.next
def hb(list1,list2):
result = []
while list1 and list2:
if list1[0] < list2[0]:
result.append(list1[0])
del list1[0]
else:
result.append(list2[0])
del list2[0]
if list1:
result.extend(list1)
if list2:
result.extend(list2)
print(result)
return result
list2 = [3,4,7,9,20]
list1 = [1,2,5,8,13,11]
hb(list1, list2)
test1 = [1,2,5,7,9]
test2=[2,4,6,8,10,11,34,55]
def mergetest(test1,test2):
result =[]
len1=len(test1)
len2=len(test2)
i=0
j=0
while i<len1 and j<len2:
if test1[i]<=test2[j]:
result.append(test1[i])
i+=1
else:
result.append(test2[j])
j+=1
if i<len1:
for z in range(i+1,len1):
result.append(test1[z])
elif j<len2:
for z in range(j+1,len2):
result.append(test2[z])
return result
print mergetest(test1,test2) |
5ff07adc2ffa1c0612854183174b9a5bcefbde58 | cesarbhering/30-days-of-code-HackerRank | /20-Sorting.py | 268 | 3.59375 | 4 | numSwaps = 0
while a != sorted(a):
for i in range(n-1):
if a[i] > a[i+1]:
a[i], a[i+1] = a[i+1], a[i]
numSwaps += 1
print(f'Array is sorted in {numSwaps} swaps.')
print(f'First Element: {(a)[0]}')
print(f'Last Element: {(a)[-1]}')
|
a1dccee3850a0edb931b2ea592f89be302d6bd0c | steffenerickson/humanitiesTutorial | /17_nltk3_textobject1.py | 892 | 4.03125 | 4 | # NLTK comes with a Text object that has many useful methods
# that facilitate many common tasks
import nltk
# Same prep as before
textfile = open("holmes.txt","r",encoding="utf8")
holmesstring = textfile.read()
textfile.close()
startpoint = holmesstring.find('*** START OF THIS PROJECT GUTENBERG EBOOK')
endpoint = holmesstring.find('*** END OF THIS PROJECT GUTENBERG EBOOK')
holmesstring = holmesstring[startpoint:endpoint]
# To create an NLTK Text object, we need to break the string
# into a list of words:
words = nltk.word_tokenize(holmesstring)
# now we just give the nltk.Text() function this list:
holmestext = nltk.Text(words)
# We can see this creates a text object
print(holmestext)
# Now we can create concordances:
holmestext.concordance("Holmes")
# You can also specify how many words and instances are
# displayed:
# holmestext.concordance("Holmes",width=79,lines=25) |
594092f9d32f046abe6a09a7773d3c49dedae817 | Miszion/Connect4 | /InputController.py | 1,651 | 3.875 | 4 | class InputController:
@staticmethod
def getValidColumn(board, player, turnNumber):
col = int(input("Turn " + str(turnNumber) +": " + player.name + " (" + player.color + "), choose your move: "))
while ((col > board.columns) or (col <= 0)):
print("Invalid move, outside board, try again: ")
col = (int(input("Turn " + str(turnNumber) +": " + player.name + " (" + player.color + "), choose your move: ")))
while (board.grid[0][col-1] != None):
print("Invalid move, column " + str(col) + " is full, try again: ")
col = (int(input("Turn " + str(turnNumber) +": " + player.name + " (" + player.color + "), choose your move: ")))
while ((col > board.columns) or (col <= 0)):
print("Invalid move, outside board, try again: ")
col = (int(input("Turn " + str(turnNumber) +": " + player.name + " (" + player.color + "), choose your move: ")))
print()
return col - 1
@staticmethod
def getPlayAgain():
playAgain = input(" Play again? (y/n): ")
if playAgain == "y":
return True
else:
print("Goodbye!")
return False
@staticmethod
def getGameFilled():
playAgain = input("Tie Game! Play again? (y/n): ")
if playAgain == "y":
return True
else:
print("Goodbye!")
return False
@staticmethod
def promptBoardSize():
boardSpacing = int(input("Please choose the board spacing: "))
if (boardSpacing == -1):
boardSpacing = 0
return boardSpacing
|
52a3768352a4379ce691d785475d5d2b3b9764ee | zrzka/blackmamba | /blackmamba/lib/rope/refactor/occurrences.py | 12,841 | 4.15625 | 4 | """Find occurrences of a name in a project.
This module consists of a `Finder` that finds all occurrences of a name
in a project. The `Finder.find_occurrences()` method is a generator that
yields `Occurrence` instances for each occurrence of the name. To create
a `Finder` object, use the `create_finder()` function:
finder = occurrences.create_finder(project, 'foo', pyname)
for occurrence in finder.find_occurrences():
pass
It's possible to filter the occurrences. They can be specified when
calling the `create_finder()` function.
* `only_calls`: If True, return only those instances where the name is
a function that's being called.
* `imports`: If False, don't return instances that are in import
statements.
* `unsure`: If a prediate function, return instances where we don't
know what the name references. It also filters based on the
predicate function.
* `docs`: If True, it will search for occurrences in regions normally
ignored. E.g., strings and comments.
* `in_hierarchy`: If True, it will find occurrences if the name is in
the class's hierarchy.
* `instance`: Used only when you want implicit interfaces to be
considered.
* `keywords`: If False, don't return instances that are the names of keyword
arguments
"""
import re
from rope.base import codeanalyze
from rope.base import evaluate
from rope.base import exceptions
from rope.base import pynames
from rope.base import pyobjects
from rope.base import utils
from rope.base import worder
class Finder(object):
"""For finding occurrences of a name
The constructor takes a `filters` argument. It should be a list
of functions that take a single argument. For each possible
occurrence, these functions are called in order with the an
instance of `Occurrence`:
* If it returns `None` other filters are tried.
* If it returns `True`, the occurrence will be a match.
* If it returns `False`, the occurrence will be skipped.
* If all of the filters return `None`, it is skipped also.
"""
def __init__(self, project, name, filters=[lambda o: True], docs=False):
self.project = project
self.name = name
self.docs = docs
self.filters = filters
self._textual_finder = _TextualFinder(name, docs=docs)
def find_occurrences(self, resource=None, pymodule=None):
"""Generate `Occurrence` instances"""
tools = _OccurrenceToolsCreator(self.project, resource=resource,
pymodule=pymodule, docs=self.docs)
for offset in self._textual_finder.find_offsets(tools.source_code):
occurrence = Occurrence(tools, offset)
for filter in self.filters:
result = filter(occurrence)
if result is None:
continue
if result:
yield occurrence
break
def create_finder(project, name, pyname, only_calls=False, imports=True,
unsure=None, docs=False, instance=None, in_hierarchy=False,
keywords=True):
"""A factory for `Finder`
Based on the arguments it creates a list of filters. `instance`
argument is needed only when you want implicit interfaces to be
considered.
"""
pynames_ = set([pyname])
filters = []
if only_calls:
filters.append(CallsFilter())
if not imports:
filters.append(NoImportsFilter())
if not keywords:
filters.append(NoKeywordsFilter())
if isinstance(instance, pynames.ParameterName):
for pyobject in instance.get_objects():
try:
pynames_.add(pyobject[name])
except exceptions.AttributeNotFoundError:
pass
for pyname in pynames_:
filters.append(PyNameFilter(pyname))
if in_hierarchy:
filters.append(InHierarchyFilter(pyname))
if unsure:
filters.append(UnsureFilter(unsure))
return Finder(project, name, filters=filters, docs=docs)
class Occurrence(object):
def __init__(self, tools, offset):
self.tools = tools
self.offset = offset
self.resource = tools.resource
@utils.saveit
def get_word_range(self):
return self.tools.word_finder.get_word_range(self.offset)
@utils.saveit
def get_primary_range(self):
return self.tools.word_finder.get_primary_range(self.offset)
@utils.saveit
def get_pyname(self):
try:
return self.tools.name_finder.get_pyname_at(self.offset)
except exceptions.BadIdentifierError:
pass
@utils.saveit
def get_primary_and_pyname(self):
try:
return self.tools.name_finder.get_primary_and_pyname_at(
self.offset)
except exceptions.BadIdentifierError:
pass
@utils.saveit
def is_in_import_statement(self):
return (self.tools.word_finder.is_from_statement(self.offset) or
self.tools.word_finder.is_import_statement(self.offset))
def is_called(self):
return self.tools.word_finder.is_a_function_being_called(self.offset)
def is_defined(self):
return self.tools.word_finder.is_a_class_or_function_name_in_header(
self.offset)
def is_a_fixed_primary(self):
return self.tools.word_finder.is_a_class_or_function_name_in_header(
self.offset) or \
self.tools.word_finder.is_a_name_after_from_import(self.offset)
def is_written(self):
return self.tools.word_finder.is_assigned_here(self.offset)
def is_unsure(self):
return unsure_pyname(self.get_pyname())
def is_function_keyword_parameter(self):
return self.tools.word_finder.is_function_keyword_parameter(
self.offset)
@property
@utils.saveit
def lineno(self):
offset = self.get_word_range()[0]
return self.tools.pymodule.lines.get_line_number(offset)
def same_pyname(expected, pyname):
"""Check whether `expected` and `pyname` are the same"""
if expected is None or pyname is None:
return False
if expected == pyname:
return True
if type(expected) not in (pynames.ImportedModule, pynames.ImportedName) \
and type(pyname) not in \
(pynames.ImportedModule, pynames.ImportedName):
return False
return expected.get_definition_location() == \
pyname.get_definition_location() and \
expected.get_object() == pyname.get_object()
def unsure_pyname(pyname, unbound=True):
"""Return `True` if we don't know what this name references"""
if pyname is None:
return True
if unbound and not isinstance(pyname, pynames.UnboundName):
return False
if pyname.get_object() == pyobjects.get_unknown():
return True
class PyNameFilter(object):
"""For finding occurrences of a name."""
def __init__(self, pyname):
self.pyname = pyname
def __call__(self, occurrence):
if same_pyname(self.pyname, occurrence.get_pyname()):
return True
class InHierarchyFilter(object):
"""Finds the occurrence if the name is in the class's hierarchy."""
def __init__(self, pyname, implementations_only=False):
self.pyname = pyname
self.impl_only = implementations_only
self.pyclass = self._get_containing_class(pyname)
if self.pyclass is not None:
self.name = pyname.get_object().get_name()
self.roots = self._get_root_classes(self.pyclass, self.name)
else:
self.roots = None
def __call__(self, occurrence):
if self.roots is None:
return
pyclass = self._get_containing_class(occurrence.get_pyname())
if pyclass is not None:
roots = self._get_root_classes(pyclass, self.name)
if self.roots.intersection(roots):
return True
def _get_containing_class(self, pyname):
if isinstance(pyname, pynames.DefinedName):
scope = pyname.get_object().get_scope()
parent = scope.parent
if parent is not None and parent.get_kind() == 'Class':
return parent.pyobject
def _get_root_classes(self, pyclass, name):
if self.impl_only and pyclass == self.pyclass:
return set([pyclass])
result = set()
for superclass in pyclass.get_superclasses():
if name in superclass:
result.update(self._get_root_classes(superclass, name))
if not result:
return set([pyclass])
return result
class UnsureFilter(object):
"""Occurrences where we don't knoow what the name references."""
def __init__(self, unsure):
self.unsure = unsure
def __call__(self, occurrence):
if occurrence.is_unsure() and self.unsure(occurrence):
return True
class NoImportsFilter(object):
"""Don't include import statements as occurrences."""
def __call__(self, occurrence):
if occurrence.is_in_import_statement():
return False
class CallsFilter(object):
"""Filter out non-call occurrences."""
def __call__(self, occurrence):
if not occurrence.is_called():
return False
class NoKeywordsFilter(object):
"""Filter out keyword parameters."""
def __call__(self, occurrence):
if occurrence.is_function_keyword_parameter():
return False
class _TextualFinder(object):
def __init__(self, name, docs=False):
self.name = name
self.docs = docs
self.comment_pattern = _TextualFinder.any('comment', [r'#[^\n]*'])
self.string_pattern = _TextualFinder.any(
'string', [codeanalyze.get_string_pattern()])
self.pattern = self._get_occurrence_pattern(self.name)
def find_offsets(self, source):
if not self._fast_file_query(source):
return
if self.docs:
searcher = self._normal_search
else:
searcher = self._re_search
for matched in searcher(source):
yield matched
def _re_search(self, source):
for match in self.pattern.finditer(source):
for key, value in match.groupdict().items():
if value and key == 'occurrence':
yield match.start(key)
def _normal_search(self, source):
current = 0
while True:
try:
found = source.index(self.name, current)
current = found + len(self.name)
if (found == 0 or
not self._is_id_char(source[found - 1])) and \
(current == len(source) or
not self._is_id_char(source[current])):
yield found
except ValueError:
break
def _is_id_char(self, c):
return c.isalnum() or c == '_'
def _fast_file_query(self, source):
try:
source.index(self.name)
return True
except ValueError:
return False
def _get_source(self, resource, pymodule):
if resource is not None:
return resource.read()
else:
return pymodule.source_code
def _get_occurrence_pattern(self, name):
occurrence_pattern = _TextualFinder.any('occurrence',
['\\b' + name + '\\b'])
pattern = re.compile(occurrence_pattern + '|' + self.comment_pattern +
'|' + self.string_pattern)
return pattern
@staticmethod
def any(name, list_):
return '(?P<%s>' % name + '|'.join(list_) + ')'
class _OccurrenceToolsCreator(object):
def __init__(self, project, resource=None, pymodule=None, docs=False):
self.project = project
self.__resource = resource
self.__pymodule = pymodule
self.docs = docs
@property
@utils.saveit
def name_finder(self):
return evaluate.ScopeNameFinder(self.pymodule)
@property
@utils.saveit
def source_code(self):
if self.__resource is not None:
return self.resource.read()
else:
return self.pymodule.source_code
@property
@utils.saveit
def word_finder(self):
return worder.Worder(self.source_code, self.docs)
@property
@utils.saveit
def resource(self):
if self.__resource is not None:
return self.__resource
if self.__pymodule is not None:
return self.__pymodule.resource
@property
@utils.saveit
def pymodule(self):
if self.__pymodule is not None:
return self.__pymodule
return self.project.get_pymodule(self.resource)
|
6921b246a0d2babdb6b25b433fb2f1d2d8a9bf90 | mattpmartin/DataStructuresSeries | /Insertion Sort/Final.py | 582 | 4.0625 | 4 | import random
# creating array of random ints
numbers = [int(random.random() * 20) for _ in range(100)]
# printing array so we know what were looking at
print(numbers)
# insertion sort
def insertionSort(numbers):
for index in range(1, len(numbers)):
currentValue = numbers[index]
position = index
while position > 0 and numbers[position - 1] > currentValue:
numbers[position] = numbers[position - 1]
position -= 1
numbers[position] = currentValue
# test and print out the result
insertionSort(numbers)
print(numbers) |
f01cb78c48ff83fe3fa5af56f9e658f6c0dbeac0 | BioAlex1978/automateboringstuffpythonpractice | /guessTheNumber.py | 1,913 | 4.34375 | 4 | # A short program to guess the number, from "Automate the Boring Stuff With Python, 2nd Edition"
import random
# The following commented block of code is what I came up with before look at the book,
# based entirely in the book's example output, and without knowing the full features.
# This version allows infinite guesses. The book's implementation was to allow 6 guesses.
# Also, I wasn't paying close attention; the book's game is between 1 and 20, mine is between 1 and 100
# My code could probably be cleaner, but as a first attempt while still unfamiliar with Python,
# it does function. :)
#
#number = random.randint(1, 100)
#correct = False
#guesscount = 1
#
#print('I am thinking of a number between 1 and 100.')
#
#while not correct:
# print('Take a guess.')
# guess = int(input())
# if guess == number:
# print('Good job! You guessed my number in ' + str(guesscount) + ' guesses!')
# correct = True
# elif guess < number:
# print('Your guess is too low.')
# guesscount += 1
# else:
# print('Your guess is too high.')
# guesscount += 1
# Below is the book's version as shown on page 50. I've already imported random up at the top of the file
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
# Give feedback based on whether or not the player managed to guess the correct number
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber) + '.')
|
102f2a7ec7b8f0dc47c8f5c2b1751f11f9c062f9 | shi-kejian/nyu | /csuy-1122/homework/1/test.py | 5,303 | 3.5 | 4 | import time
import random
from selection import selectionSort
from quicksort import quickSort
from insertion import insertionSort
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.ticker as mticks
import numpy as np
import sys
sys.setrecursionlimit(1000000)
def generate_list(length, filename, sorted='random'):
f = open(filename, 'a')
if sorted == 'random':
for _ in range(length):
f.write(str(random.randint(-1000000, 1000000)) + ',')
f.write('\n')
elif sorted == 'ascending':
for x in range(length):
f.write(str(x * 2) + ',')
elif sorted == 'descending':
for x in range(length):
f.write(str(-(x * 2)) + ',')
f.close()
def generate_numbers():
lengths = [10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000, 250000, 500000, 1000000, 2500000, 5000000, 10000000]
for length in lengths:
print(length)
start = time.time()
# generate_list(length, 'numbers/random/' + str(length) + '.txt', sorted='random')
# generate_list(length, 'numbers/ascending/' + str(length) + '.txt', sorted='ascending')
generate_list(length, 'numbers/descending/' + str(length) + '.txt', sorted='descending')
end = time.time()
total = end - start
print(total)
print()
def test(num_list, method):
to_use = {
'selection': selectionSort,
'quick': quickSort,
'insertion': insertionSort
}
start = time.time()
to_use[method](num_list)
end = time.time()
total = end - start
return total
# f = open(method + '-times.txt', 'a')
# f.write(str(len(num_list)) + ',' + str(total) + '\n')
# f.close()
def test_average(length, count, sorted='random'):
f = open('numbers/' + sorted + '/' + str(length) + '.txt', 'r')
numbers = f.readline().split(',')
numbers.pop()
for x in range(len(numbers)):
numbers[x] = int(numbers[x])
selection_total = 0
quick_total = 0
insertion_total = 0
for _ in range(count):
selection_total += test(numbers, 'selection')
selection_average = selection_total / count
print('selection')
print('length: %s, count: %s, average: %s \n' % (length, count, selection_average))
for _ in range(count):
quick_total += test(numbers, 'quick')
quick_average = quick_total / count
print('quick')
print('length: %s, count: %s, average: %s \n' % (length, count, quick_average))
for _ in range(count):
insertion_total += test(numbers, 'insertion')
insertion_average = insertion_total / count
print('insertion')
print('length: %s, count: %s, average: %s \n' % (length, count, insertion_average))
f.close()
w = open('results/' + sorted + '/' + str(length) + '.txt', 'w')
w.write(str(selection_average) + '\n')
w.write(str(quick_total) + '\n')
w.write(str(insertion_total) + '\n')
w.close()
def test_all():
lengths = [10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000]
for length in lengths:
test_average(length, 1, sorted='random')
for length in lengths:
test_average(length, 1, sorted='ascending')
for length in lengths:
test_average(length, 1, sorted='descending')
def graph(sorted="random"):
lengths = [10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000]
selection = []
quick = []
insertion = []
for length in lengths:
f = open('results/' + sorted + '/' + str(length) + '.txt', 'r')
line = f.readline().strip()
selection.append(line)
line = f.readline().strip()
quick.append(line)
line = f.readline().strip()
insertion.append(line)
f.close()
print(len(lengths))
print(len(selection))
selection = np.array(selection)
quick = np.array(quick)
insertion = np.array(insertion)
lengths = np.array(lengths)
fix, ax = plt.subplots()
ax.xaxis.set_major_locator(mticks.MultipleLocator(1000))
ax.yaxis.set_major_locator(mticks.MultipleLocator(0.5))
selection_plot = plt.plot(lengths, selection, '-ro', label='selection sort')
quick_plot = plt.plot(lengths, quick, '-bo', label='quick sort')
insertion_plot = plt.plot(lengths, insertion, '-go', label='insertion sort')
plt.xlabel('Length of number list')
plt.ylabel('Time (s)')
plt.title('Runtime for sorting algorithms visualized on a linear scale')
plt.legend()
plt.rcParams.update({'font.size': 26})
plt.show()
fix, ax = plt.subplots()
ax.xaxis.set_major_locator(mticks.MultipleLocator(1000))
ax.yaxis.set_major_locator(mticks.MultipleLocator(0.5))
plt.xscale('log')
plt.yscale('log')
selection_plot = plt.plot(lengths, selection, '-ro', label='selection sort')
quick_plot = plt.plot(lengths, quick, '-bo', label='quick sort')
insertion_plot = plt.plot(lengths, insertion, '-go', label='insertion sort')
plt.xlabel('Length of number list')
plt.ylabel('Time (s)')
plt.title('Runtime for sorting algorithms visualized on a logarithmic scale')
plt.legend()
plt.rcParams.update({'font.size': 26})
plt.show()
# graph(sorted='random')
# graph(sorted='ascending')
graph(sorted='descending')
|
3c2c806f32ff729fb235e8df850c4a7f5724e888 | Salazar769/Ciclo-1-python | /cadenas y variables.py | 339 | 3.515625 | 4 | val1 = 5
val2 = 2
suma = val1 + val2
print(suma)
resta = val2 - val1
print(resta)
promedio = (val1+val2)/2
print(promedio)
producto = ((val1-val2)/2)*365
print(producto)
centroamerica = ("Guatemala, Belice, El salvador, Honduras, Nicaragua, Costa Rica, Panamá")
print(len(centroamerica))
print(centroamerica[53])
|
56d1a2a479004686a5d35dbe6546746aec391843 | hdgogo/lccspop | /ch1/onetimepad.py | 837 | 3.5 | 4 | #!/bin/python3
# -*- coding: utf-8 -*-
"""
FileName : onetimepad.py
Author : hongda
"""
from secrets import token_bytes
def random_key(length):
# 生成指定长度的随机密钥
tb = token_bytes(length)
return int.from_bytes(tb, "big")
def encrypt(original):
"""通过XOR运算进行加密"""
original_bytes = original.encode()
dummy = random_key(len(original_bytes))
original_key = int.from_bytes(original_bytes, "big")
encrypted = original_key ^ dummy
return dummy, encrypted
def decrypt(key1, key2):
decrypted = key1 ^ key2
temp = decrypted.to_bytes((decrypted.bit_length()+7) // 8, "big")
return temp.decode()
if __name__ == '__main__':
key1, key2 = encrypt("这是一个明文!")
result = decrypt(key1, key2)
print("解密后的原文为:{}".format(result))
|
2a0bf86b5473f6c30150c553afc931a0afdbc927 | tabish606/python | /fromkeys_get_clear_in_dict.py | 944 | 3.921875 | 4 | #fromkeys method gives same values to each keys
#it gives individually a,b and c to unknown
user_info = dict.fromkeys("abc",'unknown')
print(user_info)
#using list
#it gives each keys to unknown(we can use tuple also)
user_info1 = dict.fromkeys(['name','age','state'],'unknown')
print(user_info1)
#get method it does not raise an error when i give the false keys it prints None
d = {'name':'unknown','age':'unknown','state':'unknown' }
#it prints name values
print(d.get('name'))
print(d.get('names'))
#in keywords in get method
if d.get('name'):
print("present")
else:
print("not present")
# we can use subtitute of None in get method
print(d.get('hos','not found'))
#if same keys exist its overwrite the values with nextone
#clear method
#its clear the dictionaries
#d.clear()
#print(d)
#copy method
d1 = d.copy()
print(d1)
#check equality
print(d1 is d)
|
c68ce83ee8cbbb5c73181b5d9c4be40799febd6d | roctubre/data-structures-algorithms | /algorithmic-toolbox/week2_algorithmic_warmup/2_fibonacci_last_digit.py | 819 | 3.84375 | 4 | # Uses python3
import sys
import random
def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current % 10
def get_fibonacci_last_digit(n):
a = 0
b = 1
for i in range(n):
x = (a + b) % 10
a = b
b = x
return a
def stresstest(n):
random.seed(1)
for _ in range(n):
r = random.randint(0,10000)
if get_fibonacci_last_digit_naive(r) != get_fibonacci_last_digit(r):
print("Error!", r)
return
print("All OK.")
if __name__ == '__main__':
#stresstest(1000)
input = sys.stdin.readline()
n = int(input)
print(get_fibonacci_last_digit(n))
|
9446404583ffdbdd77f74fd57fc2bef1ee72f365 | devolopez88/PythonPrro | /hangman.py | 1,894 | 4 | 4 | import random
import os
# It picks a work from the list returned by the file
def pickword(file):
word = ""
ln = random.randrange(0, len(file))
word = file[ln]
return word
# It prints the spot for each letter
def printSpace(word):
print("You have " + str( len(word)) + " opportunities to WIN. let's tring")
for l in word[:-1]:
print("_", end =" ")
# It reads the file has the list of work will be using in the game
def readFile():
w = []
word = ""
with open("./files/words.txt", "r") as file:
for wln in file:
w.append(wln)
word = pickword(w)
printSpace(word)
return word
# It looks the letter type by the user
def searchArray(x, word):
p = 0
for i in word:
for l in x:
if i == l:
print(l, end=" ")
p = p + 1
return p
def run():
word = readFile()
lInput = []
l = ""
tryed = len(word[:-1])
for i in range(0,len(word[:-1])):
print("\nType a letter : ")
l = input()
lInput.append(l)
p = searchArray(lInput,word)
if tryed == p:
print("\nCongratulation you WIN!!!")
break
elif p - tryed == 1:
print("\nJust need one more letter to WIN!!!\n")
else:
print("\nKeep try it.\n")
if p < tryed:
print("\nSorry, you lose. the word was: " + word +"\n")
#v = [i for i in word if i in word ]
#print(v)
#print("\n")
#print( lInput)
#lInput.append(input())
#searchArray(lInput, word)
#""""
#v = search(l, word)
#v = search(lInput, word)
#if v==1:
# print("\nG,")
#else:
# print("\nX,")
#"""
#os.system('cls')
if __name__ == "__main__":
run()
|
e73f24e319c0134c2021b97ddac9bfb62d030d1e | mohammedEshtayah/simulation | /lab4.py | 561 | 3.609375 | 4 | import math ;
import matplotlib.pyplot as plt
import numpy as np;
if __name__ == "__main__":
t=[]
pt=[]
elem=2*325*1000 # نسبة الاسبرين
h=22
k=-math.log(0.5)/h
pv=3000 # البلازمه
dt=0.01 #تغير بالزمن
tt=24 #ساعة
q=1
d=0.12*q
for i in range(int(tt/dt)):
elem= k*elem*dt # نسبة التناقص بالسنة
q=q-elem
if(tt%8==0):
q=q+d
t.append(i*dt)
pt.append(q)
plt.plot(t,pt)
plt.show()
|
e47983a86615394ae14cd8ff9b13c88a164b45cf | Sanchitgupta910/MCA-python-programming | /password.py | 1,647 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 17:40:12 2021
@author: SANCHIT
"""
# Lambda function to check if a given vaue is from 10 to 20.
import random
test = lambda x : False and print("weak password") if((len(x) < 8 or len(x) > 20) or not any(char.isdigit() for char in x) or not any(char.isupper() for char in x or not any(char.islower() for char in x) or not any(char in ['$', '@', '#', '%','!','*','^'] for char in x)) ) else print("Secure Password! ")
# Check if given numbers are in range using lambda function
x=input("Enter the Password")
if test(x)==False:
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "[]{}()*;/.,-_"
all = lowercase + uppercase + numbers + symbols
length = int(input("------------- WEAK PASSWORD ------------\n\nEnter the length of new password"))
while 1:
if length>7 :
break;
else :
print("ENTER LENGTH GREATER THAN 8")
length = int(input("Enter the length"))
#Change this number to change the length of your password
password = "".join(random.sample(all,length)) #creating a random password using the funcn random()
print("Suggested Password {}".format(password))
print("PRESS 1 TO USE THE SAME PASSWORD \n 2 to ENTER NEW PASSWORD")
choose=int(input())
if choose==1:
test(password)
print("YOUR PASSWORD {}".format(password))
else :
print("---------Enter new Password----------")
x=input()
test(x)
while(test(x)==False):
x=input("-------WEAK PASSWORD----------")
test(x) |
8fa4cd96e7c0745d02cf9c0482227dc5bdf2abe0 | emma-metodieva/SoftUni_Python_Advanced_202106 | /01. Lists as Stacks and Queues/01-02-09. Key Revolver.py | 828 | 3.546875 | 4 | # 01-02. Lists as Stacks and Queues - Exercise
# 09. Key Revolver
from collections import deque
price = int(input())
barrel = int(input())
bullets = deque(map(int, input().split()))
locks = deque(map(int, input().split()))
intelligence = int(input())
count = 0
while bullets and locks:
for shot in range(1, barrel + 1):
if not locks or not bullets:
break
bullet = bullets.pop()
lock = locks.popleft()
count += 1
if bullet <= lock:
print('Bang!')
else:
locks.appendleft(lock)
print('Ping!')
if shot == barrel and bullets:
print('Reloading!')
if locks:
print(f"Couldn't get through. Locks left: {len(locks)}")
else:
print(f"{len(bullets)} bullets left. Earned ${intelligence - count * price}")
|
2bfc8bb9b1e90b03366378e1c80611749229625c | agrima13/PythonCoding | /Strings/Reverse_String-II.py | 252 | 3.765625 | 4 | class Solution:
def reverseStr(s: str, k: int):
a = list(s)
for i in range(0, len(a),2*k):
a[i:i + k] = reversed(a[i:i + k])
return "".join(a)
if __name__ == '__main__':
print(reverseStr("abcdef",2)) |
771305622d798a19254257bd5cf6fa2314284f08 | yiyuli/Automatic-Minesweeper-Solver | /rank.py | 821 | 3.984375 | 4 | class Rank(object):
'''
Rank object storing top three records
'''
def __init__(self):
'''
Constructor for Rank object
'''
self.first = 'No record'
self.second = 'No record'
self.third = 'No record'
def update(self, time):
'''
Update rank by new finishing time
:param time: new finishing time
'''
time = int(time.split(' ')[1])
if self.first == 'No record' or time < self.first:
self.third = self. second
self.second = self.first
self.first = time
elif self.second == 'No record' or time < self.second:
self.third = self.second
self.second = time
elif self.third == 'No record' or time < self.third:
self.third = time |
e4a0fdfaf7d2c30c42a1066f01c7d1f94a41b488 | khush-01/Python-codes | /Codechef/FLOW010.py | 136 | 4 | 4 | a = {'b': "BattleShip", 'c': "Cruiser", 'd': "Destroyer", 'f': "Frigate"}
for _ in range(int(input())):
print(a[input().lower()])
|
f6bf3f040544e8639cf0636dfc67b5ec100415eb | madanmeena/python_hackerrank | /set/py-set-union.py | 407 | 4.09375 | 4 | #https://www.hackerrank.com/challenges/py-set-union/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
first_integer_list = map(int, input().split())
m = int(input())
second_integer_list = map(int, input().split())
first_set=set(first_integer_list)
second_set=set(second_integer_list)
total_element = first_set.union(second_set)
print(len(total_element)) |
18a10ea55bbcbcd0e0ec53f87c480f37996abf66 | DryTuna/codeeval | /longest_common_subsequence.py | 1,631 | 3.8125 | 4 | """
DESCRIPTION:
You are given two sequences. Write a program to determine the longest
common subsequence between the two strings (each string can have a
maximum length of 50 characters). NOTE: This subsequence need not be
contiguous. The input file may contain empty lines, these need to
be ignored.
INPUT:
The first argument will be a path to a filename that contains two
strings per line, semicolon delimited. You can assume that there is only
one unique subsequence per test case. E.g.
XMJYAUZ;MZJAWXU
OUTPUT:
MJAU
"""
import sys
def check(x):
a, b = x.split(';')
m = [-1 for i in a]
n = [-1 for i in a]
index = 0
maping = []
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
m[i] = index
n[index] = j
maping.append(a[i])
index += 1
b = b[:j]+'*'+b[j+1:]
break
x = rank(m, n)
res = ""
temp = [-1, -1]
for (i, j) in x:
if i > temp[0] and j > temp[1]:
res += str(maping[i])
temp[0] = i
temp[1] = j
return res
def rank(m, n):
x = [i for i in m if i > -1]
y = [i for i in n if i > -1]
i = 0
res = {}
while i < len(x):
num = len(x)-i + len(y)-y[x[i]] + min(len(x)-i,len(y)-y[x[i]])
res[(i, y[x[i]])] = num
i += 1
return sorted(res, key = lambda x: -res[x])
if __name__ == '__main__':
r = open(sys.argv[1], 'r')
while True:
a = str(r.readline())
if len(a) > 0:
print check(a)
else:
break
r.close()
|
19c2572210edbc792d25d537effffa6a5162abd8 | drwpeng/shiny-meme | /装饰器/decorator_1.py | 2,337 | 3.984375 | 4 |
import time
# 装饰器
# 让其他函数在不需要做任何代码变动的前提下增加额外功能
# 经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景
# 不带参数的装饰器
def decorator1(func):
def wrapper():
start_time = time.time()
func()
end_time = time.time()
print("不带参数的装饰器: " + str(end_time - start_time))
return wrapper
# 带参数的装饰器
def decorator2(func):
def wrapper(a, b):
start_time = time.time()
func(a, b)
end_time = time.time()
print("带参数的装饰器: " + str(end_time - start_time))
return wrapper
# 带不定参数的装饰器
def decorator3(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
print("带不定参数的装饰器: " + str(end_time - start_time))
return wrapper
# 函数的函数装饰器
@decorator1
def fun():
print("sleeping...")
time.sleep(1)
@decorator2
def fun2(a, b):
print("a + b = " + str(a+b))
time.sleep(1)
# 用于类的不带参数的装饰器
def decorator4(func):
def wrapper(self):
start_time = time.time()
func()
end_time = time.time()
print("不带参数的装饰器: " + str(end_time - start_time))
return wrapper
# 用于类的带参数的装饰器
def decorator5(func):
def wrapper(self):
start_time = time.time()
func(self)
end_time = time.time()
print("不带参数的装饰器: " + str(end_time - start_time))
return wrapper
# 用于类的带参数的装饰器
def decorator6(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
print("不带参数的装饰器: " + str(end_time - start_time))
return wrapper
# 类方法的函数装饰器
class Method():
#def __init__(self):
#print("locker.__init__() should be bot called")
@decorator4
def fun3():
print("Running...")
time.sleep(1)
@decorator5
def fun4(self):
pass
@decorator6
def fun5(*args, **kwargs):
pass
p1 = Method()
p1.fun3()
p1.fun4()
p1.fun5()
|
400c69aacd8490c2cc73db8b7d2c57805bb2967a | RadBoris/cardinality | /cardinality.py | 1,246 | 3.984375 | 4 | def main():
combined = 1
g = []
r = str (input ("Enter numbers separated by a space for each column: "))
w = r.split(" ")
for x in w:
if x:
x = int(x)
return w
def searchTable(g):
result = {}
combined_cardinality = []
with open('cardinality.sql', 'r') as f:
lines = f.readlines()
for line in lines:
columns = line.split('|')
g = list(map(int, g))
for column in columns:
if columns.index(column) in g:
combined_cardinality.append(column)
for x in g:
x = int(x)
if x > 0:
x -= 1
if x in result:
result[x].append(columns[x])
else:
result[x] = [columns[x]]
line_list = []
for line in lines:
line = line.rstrip("\n")
columns = line.split('|')
for column in columns:
line_list.append(column)
g = list(map(int, g))
max_cardinality = 1
for key, value in result.items():
max_cardinality *= len(set(result[key]))
print ("Column {0} cardinality: {1}".format(key,len(set(result[key])) ))
print ("Maximum cardinality: {0}".format(max_cardinality))
zipped = zip(line_list[0::2], line_list[1::2])
print ("Combined cardinality: ", len([tuple(x) for x in set(map(frozenset, zipped))]))
if __name__ == "__main__":
numbers_list = main()
searchTable(numbers_list)
|
263890c5d42c22154293a970541f368c3f18f1c2 | suku19/python-associate-example | /controlflow/for_statement.py | 1,349 | 4.40625 | 4 | words = ['cat', 'window', 'defenestrate']
# Measure some strings:
for w in words:
print(w + ' length is: ', len(w))
# Loop over a slice copy of the entire list.
for w in words[:]:
if len(w) > 6:
words.insert(0, 'test')
print(words)
# The range function
for i in range(5):
print('range 5: ', i)
for i in range(5, 10):
print('range (5, 5): ', i)
for i in range(0, 9, 3):
print('range(0, 10, 3): ', i)
# To iterate over the indices of a sequence, you can combine range() and len() as follows:
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
print(list(range(10)))
# if the set generated by the range() function is empty the loop won't execute its body at all.
for i in range(1, 1):
print("Value of i is currently ", i)
'''
The set generated by the range() has to be sorted in ascending order. There’s no way to force the range() to create a
set in a different form. This means that the range()’s second argument must be greater than the first.
Thus, there will be no output here, either →
'''
for i in range(2, 1):
print("Value of i for range(2, 1) is : ", i)
for i in range(1, 11):
print(i, "Mississippi")
i += 2
print("value of i after increment: ", i)
print("Ready or not, here I come!") |
c1fccbaa5e41b2d1b60b0efe28d6cc981fac7804 | jasminjahanpuspo/All_Lab_Code | /AI/untitled3.py | 325 | 3.671875 | 4 |
#lst=[]
#
#n=eval(input("input: "))
#
#for x in range(0,n):
# ele=eval(input())
# lst.append(ele)
#print(lst)
lst=[]
n=eval(input())
for x in range(0,n):
elmt=eval(input())
lst.append(ele)
print(lst)
p=lst.sort()
print(lst[-1])
print(max(lst))
|
22a0ed12e0b5d5f52be2858339efddf3bcbc663a | zomblzum/DailyCoding | /task_1/test.py | 478 | 3.59375 | 4 | import unittest
import sum_searcher as ss
class TestSearch(unittest.TestCase):
def test_search(self):
some_array = [10, 15, 3, 7]
some_result = 17
self.assertTrue(ss.list_contain_equal_sum(some_array, some_result))
def test_search_with_duplicates(self):
some_array = [10, 15, 3, 7, 10]
some_result = 20
self.assertTrue(ss.list_contain_equal_sum(some_array, some_result))
if __name__ == '__main__':
unittest.main() |
f1ffa09d1b8c859106496dba51709ed3d1c036b4 | mkholodnyak/Documents | /SummerPractice/2014/src/python/task2/vector.py | 652 | 3.625 | 4 | # -*- coding: utf8 -*-
__author__ = 'kholodnyak'
from geom.shape import Point
from geom.shape import Shape
class Vector(Shape):
def __init__(self, start, end):
self.start = start
self.end = end
def __iadd__(self, other):
self.end.x += other.end.x - other.start.x
self.end.y += other.end.x - other.start.y
def __isub__(self, other):
self.end.x = self.end.x - other.end.x + other.start.x
self.end.y = self.end.y - other.end.y + other.start.y
def __len__(self):
return Point.len_to(self.end - self.start)
def __lt__(self, other):
return len(self) < len(other)
|
cf6020e0e68a9e81e8eb4717f79d04a14637ff07 | tayalebedeva/hackaton_2021 | /LSH3.py | 4,319 | 4.25 | 4 | class Bird:
name = ''
height = 0
weight = 0
def __init__(self,name,height,weight):
self.name = name
self.height = height
self.weight = weight
def printInfo(self):
print('Info: ', self.name, self.height, self.weight)
def breathing():
print('Im breathing')
def moving():
print('Im moving')
def drinking(self):
print('Im drinking')
self.weight+=1
def dieing():
m=random(1,5)
if m==1:
print('You died because of disease')
if m==2:
print('You died because of old age')
if m==3:
print('You died because of hunger')
if m==4:
print('You died because of thirst')
if m==5:
print('You died because of randomness')
class Swimming(Bird):
oxygen=0
def __init__(self,name,height,weight,oxygen):
Bird.__init__(self,name,height,weight)
self.oxygen=oxygen
def printInfo(self):
print('Info: ', self.name, self.height, self.weight, self.oxygen)
def swimming():
print('Im swimming')
def diving(self):
print('Im diving')
self.oxygen-=1
if self.oxygen==0:
print('You died because of lack of oxygen')
del self.name
def eating(self):
print('Im eating small fishes,seaweeds,worms and insects')
self.weight+=1
class Wading(Bird):
def eating(self):
print('Im eating insects,worms and plants')
self.weight+=1
class Landing(Bird):
def eating(self):
print('Im eating insects, worms,plants,seeds and berries')
self.weight+=1
def running():
print('Im running')
class Raptors(Bird):
speed=0
def __init__(self,name,height,weight,speed):
Bird.__init__(self,name,height,weight)
self.speed=speed
def printInfo(self):
print('Info: ', self.name, self.height, self.weight, self.speed)
def eatbird(self, eatingLanding):
self.weight+=eatingLanding.weight
if speed==0:
print('You died because of crash')
class Scanning(Bird):
def scanning():
print('Im scanning')
def eating(self):
print('Im eating insects, worms,plants,seeds and berries')
self.weight+=1
class Singing(Bird):
singsong=0
def __init__(self,name,height,weight,singsong):
Bird.__init__(self,name,height,weight)
self.singsong=singsong
def printInfo(self):
print('Info: ', self.name, self.height, self.weight, self.singsong)
def singing():
if singsong==0:
print('I cant sing as my singsong is out')
else:
print('Im singing')
singsong-=1
def eating(self):
print('Im eating insects, worms,plants,seeds and berries')
self.weight+=1
swimming=[]
wading=[]
landing=[]
raptors=[]
scanning=[]
singing=[]
k=int(input('Enter needed number of birds'))
for l in range (0,k+1):
question=input('Choose which bird you want:Swimming, Wading, Landing, Raptors, Scanning, Singing')
n=input('Enter name')
h=int(input('Enter height'))
w=int(input('Enter weight'))
if question=='Swimming':
o=int(input('Enter level of oxygen'))
swimming.append(Swimming(n,h,w,o))
if question=='Wading':
wading.append(Wading(n,h,w))
if question=='Landing':
landing.append(Landing(n,h,w))
if question=='Raptors':
s=int(input('Enter speed'))
raptors.append(Raptors(n,h,w,s))
if question=='Scanning':
scanning.append(Scanning(n,h,w))
if question=='Singing':
s=int(input('Enter singsong'))
singing.append(Singing(n,h,w,s))
for i in range (0,len(swimming)):
swimming[i].printInfo()
for i in range (0,len(wading)):
wading[i].printInfo()
for i in range (0,len(landing)):
landing[i].printInfo()
for i in range (0,len(raptors)):
raptors[i].printInfo()
for i in range (0,len(scanning)):
scanning[i].printInfo()
for i in range (0,len(singing)):
singing[i].printInfo()
landing[0].drinking()
landing[0].printInfo()
swimming[0].diving()
swimming[0].printInfo() |
268f06a7b4322320f5abc3e2ba71923562d2e06f | frozen007/algo-study | /Challenge/lcof/lcof-06.py | 1,022 | 3.890625 | 4 | """
剑指 Offer(第 2 版)
https://leetcode-cn.com/problemset/lcof/
剑指 Offer 06. 从尾到头打印链表
https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reversePrint(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
if head==None:
return list()
new_head_ptr=head
ptr_node = head
while ptr_node<>None:
temp_node = ptr_node.next
ptr_node.next = new_head_ptr
new_head_ptr = ptr_node
ptr_node = temp_node
head.next=None
ret_list = list()
ptr_node = new_head_ptr
while ptr_node<>None:
ret_list.append(ptr_node.val)
ptr_node = ptr_node.next
return ret_list
|
cb5d8e22c90ed5d0866c889ad330cf1abf88dc71 | 100rabhsrivastava/python_by_100rabh | /pp9.py | 89 | 3.515625 | 4 | n = int(input())
for i in range(1, 11):
result = n*i
print( n,"x",i ,"=", result) |
ea24f3ceea8f2db74d407b6238805a2527a033f6 | Amansinghtech/iant-python-classes | /exercise2.py | 548 | 3.609375 | 4 | # multiple inheritence
class A:
def __init__(self) -> None:
print("class A init is called")
def feature1(self):
print("this is feature 1")
class B:
def __init__(self) -> None:
print("class B init is called")
def feature2(self):
print('this is feature 2')
class C (A, B):
def __init__(self) -> None:
super().__init__()
print("class C init is called")
def feature3(self):
print("this is feature 2")
test = C()
test.feature1()
test.feature2()
test.feature3()
|
d5fa393de8f6a4ad061ef8ed8618ccc163c8a184 | keivanipchihagh/Competitions | /Quera/مسابقه/تیم کشی.py | 157 | 3.671875 | 4 | a1 = int(input())
b1 = int(input())
a2 = int(input())
b2 = int(input())
a3 = int(input())
b3 = int(input())
print(min(a1, b1) + min(a2, b2) + min(a3, b3)) |
633fa1948b30b789fde6de8352c4dec3501227f6 | Apaisley/python01 | /assignment 8.5 AdamPaisley.py | 269 | 3.71875 | 4 | fname = raw_input('File name')
if len(fname) < 0:
fname ='mbox-short.txt'
try:
fh = open(fname)
except:
print" not a file bruh"
for line in fh:
if not line.startswith('From'):
continue
words_list = line.split()
email = words_list[1]
count += 1
print email |
287854c9cb24e721341dc18f6e34bc903613afcb | AnandMurugan/Python | /ifelseblock.py | 338 | 3.5625 | 4 | #!/usr/bin/env python
user = { 'admin': False, 'active': False, 'name': 'Kevin'}
if user['admin'] and user['active']:
print ("ACTIVE - (ADMIN) %s " % (user['name']))
elif user['admin']:
print ("(ADMIN) %s " % (user['name']))
elif user['active']:
print ("ACTIVE %s " % (user['name']))
else:
print ("%s" % (user['name']))
|
8cb1fc7c90e0201635b0c8fad6cf18beea0f9b28 | NamelessKing/Python-Exercises | /Es13.py | 533 | 4.25 | 4 | # coding=utf-8
'''
The function max() from exercise 1) and the function max_of_three() from
exercise 2) will only work for two and three numbers, respectively.
But suppose we have a much larger number of numbers, or suppose we cannot
tell in advance how many they are? Write a function max_in_list() that
takes a list of numbers and returns the largest one
'''
def max_in_list(list):
max = list[0]
for i in list:
if i > max:
max = i
return max
print max_in_list([100,2,34,5,6,0,7])
|
8aebc65c73775b76fc2b7e5940d50134d312dc58 | iss760/algorithm | /algorism_interview/01.valid_palindrome.py | 641 | 3.53125 | 4 | import re
def is_valid_palindrome(s):
# 전처리: 문자만 추출, 소문자로 변환(대소문자 구분 x 이므로)
s = [_s.lower() for _s in s if _s.isalnum()]
# 회문 판별
for i in range(len(s)//2):
if s[i] != s[len(s) - 1 - i]:
return False
return True
def is_valid_palindrome2(s):
# 전처리
s = s.lower() # 소문자로 변환(대소문자 구분 x 이므로)
s = re.sub('[^a-z0-9]', '', s) # 정규표현식으로 영문자 숫자만 남김
return s == s[::-1]
print(is_valid_palindrome("man :aba,n : am"))
print(is_valid_palindrome2("man :aba,n : am"))
|
1500e032c3fd8836ac8f2a0236176c27f7b03983 | TatianaPan/JavaScript-Exercises_new | /Week3/day1/10_split_bill.py | 315 | 3.609375 | 4 | def split_the_bill(obj):
sum = 0
for key in obj:
sum += obj[key]
amount = sum // len(obj)
for key in obj:
obj[key] = amount - obj[key]
return obj
group = {
'Amy': 20,
'Bill': 15,
'Chris': 10
}
print(split_the_bill(group)) # { 'Amy': -5, 'Bill': 0, 'Chris': 5 } |
822c33cdc95988000c925afc22493269ebae6c5e | r-bergundy/practice | /bin/account.py | 1,249 | 3.921875 | 4 | """ This is a test Account class """
import logging
import sys
class Account:
def __init__(self, name, email, balance):
self.balance = balance
self.name = name
self.email = email
def get_name(self):
logging.info("Retrieving Account Name....")
logging.info("> " + str(self.name))
return self.name
def get_email(self):
logging.info("Retrieving Account Email....")
logging.info("> " + str(self.email))
return self.email
def get_balance(self):
logging.info("Retrieving Account Balance....")
logging.info("> " + str(self.balance))
return self.balance
def withdraw_amount(self, amount_to_withdraw):
logging.info("Withdrawing " + str(amount_to_withdraw))
if self.balance < amount_to_withdraw:
logging.warning("Not enough funds in the balance to withdraw that"
" ammount")
sys.exit(1)
else:
self.balance = self.balance - amount_to_withdraw
def deposit_amount(self, amount_to_deposit):
logging.info("Depositing " + str(amount_to_deposit))
self.balance = self.balance + amount_to_deposit
|
c4a4b5e230874f56ecce147e7dd07d3ab3277980 | siily15/school | /Hangman.py | 336 | 3.953125 | 4 | used_letters =()
word = "Ametikool"
guessed_word =["_,_,_,_,_,_,_,_,"]
letters = list(word)
while True:
print(guessed_word)
print("used letters" + str(used_letters))
letter = input("Type a letter: ")
used_letters.append(letter)
if letter.lower in word.lower():
letter == word
print() |
5501fccb6c9362822f75752274cfc41173180032 | martinhuprich/teamprojekt | /mx_teamprojekt.py | 2,299 | 3.859375 | 4 | import urllib.request
import json
from random import shuffle
class Quiz():
def __init__(self, name, url):
self.name = name
self.url = url
# def get_info(self):
# print(self.name)
# print(self.url)
def get_question_and_answers(self):
#retrieving information from the website open trivia, getting one question with right and incorrect answers
complete_information = json.load(urllib.request.urlopen(self.url))
question = complete_information['results'][0]['question']
correct_answer = complete_information['results'][0]['correct_answer']
false_answers = complete_information['results'][0]['incorrect_answers']
# building a list with all answers, correct and incorrect ones for processing
answers = [complete_information['results'][0]['correct_answer']]
for i in false_answers:
answers.append(i)
shuffle(answers)
#print the question to the console
print(question)
#
#print(answers)
#if only true or false are the options the possible answers need to be adapted (-> true & false)
if len(answers) == 2:
print('1: ' + answers[0] + '\n' + '2: ' + answers[1])
else:
print('1: ' + answers[0] + '\n' + '2: ' + answers[1] + '\n' +'3: '+ answers[2] + '\n' +'4: ' + answers[3])
#check whether there are 2 or 4 options and make sure the user is being provided with the adequate choice
if len(answers) < 3:
user_answer = input("Which answer do you choose? 1 or 2?")
else:
user_answer = input("Which answer do you choose? 1, 2, 3 or 4?")
index = int(user_answer) - 1
#check if the given answer of the user is correct, by accessing the answers list with index. index is calculated by subtracting 1 from the users´ answer
if (answers[index]) == correct_answer:
print("Hooray! You have won!")
else:
print("Uh Oh, that is not the right answer!")
Martin = Quiz("Martin", "https://opentdb.com/api.php?amount=1")
#Martin.get_info()
Martin.get_question_and_answers() |
8087240d9b774be478f17a77e14fe9406968022c | esparig/Group-14 | /daniela997/assignment-1/anagramchecker.py | 1,072 | 4.21875 | 4 | """This module defines an Anagram checker implementation."""
from collections import Counter
class AnagramChecker(object):
"""Anagram checker with basic functionality.
Assumes that character case does not matter,
and inputs should be single words made up of
alphabetical characters.
"""
def __init__(self):
"""Creates an anagram checker.
"""
def check_anagrams(self, sequence1, sequence2):
"""Checks two sequences are anagrams.
"""
if len(sequence1) != len(sequence2):
# If length is not the same return false
return False
else:
# Assumes case doesn't matter by default
return self.compare_words(sequence1.lower(), sequence2.lower())
def compare_words(self, word1, word2):
"""Compares two words to check if they are
made up of the same multiset of characters
using collections.Counter() to count the
occurrences of each character in the sequences
"""
return Counter(word1) == Counter(word2)
|
88ec53865bd0f588e259986bba253f09aba29d7a | KindoIssouf/DataWareHousingScripts | /gradient_example.py | 2,302 | 4.3125 | 4 | import numpy
"""Gradient descent for linear regression.
We will try to learn this linear regression model:
w_0 1 + w_1 x = y
where we want to predict the value of y, from the value of x. We want
to learn the values of the weights w_0 and w_1 from the training data
(x,y).
"""
# we shall simulate data (x,y) with the following weights
w_0,w_1 = 5,7
N = 10 # size of the dataset
# per-instance sum-squared-error
def loss(A,y,w):
N = len(A) # length of dataset
a = A@w - y # error
return a.T@a/N # average squared error
# gradient of the loss
def gradient(A,y,w):
N = len(A) # length of dataset
a = 2*(A@w - y).T@A/N # gradient as row vector
return a.T # return as column vector
def optimize(A,y,iters=10,rate=0.1):
n = len(A.T) # number of features
w = numpy.random.random([n,1]) # initial weights
for i in range(iters):
cur_loss = loss(A,y,w) # current loss
cur_grad = gradient(A,y,w) # current gradient
cur_mag = cur_grad.T@cur_grad # magnitude of gradient
print("iter: %d loss: %.4g grad: %.4g" % (i,cur_loss,cur_mag))
w = w - rate*cur_grad # take a gradient step
return w # final learned weights
if __name__ == '__main__':
"""We want to set up the linear regression problem using the linear
system:
Aw = y
where
A = [ 1; x ]
where
[1; x].T [w_0 w_1] = w_0 1 + w_1 x
[w_0 w_1].T [1; x] = w_0 1 + w_1 x
2*1 . 1*n gives 2*n yeahhhh
"""
w = numpy.matrix([w_0,w_1]).T # weight vector
x = numpy.random.random([N,1]) # random data x
ones = numpy.ones([N,1]) # vector of ones
A = numpy.concatenate([ones,x],axis=1) # the A matrix: [1; x]
noise = numpy.random.random([N,1]) # noise, for simulating data
y = A@w # simulated (noisy) labels
# 10*2 @ 2*1 = 10 * 1
# learn the weights, where we specify the number of iterations and the
# learning rate. increase the number of iterations to get better
# weights
new_w = optimize(A,y,iters=5000,rate=0.01)
print(new_w)
# when the loss is at a minimum, the magnitude of the gradient is zero
|
4a2f30241b986b64e998c459cd984a45744c9657 | kenic1121/Daniel-Pythoon | /Unit2CLab/Unit2CLab.py | 614 | 3.921875 | 4 |
print ('My List:')
numlist = [1,2,3,4,5,6,7,8,9,10]
print (numlist)
print ('Counts all thenumbers and adds them up:')
print (len(numlist))
print ('Get first 5 numbers:')
sublist = numlist[0:5]
print (sublist)
print ('Insert 3 into list:')
sublist.insert (0 , 3)
print (sublist)
print ('Inserts a nummber:')
sublist2 = sublist + [6]
print (sublist2)
print('My Classes:')
classes = ['flee' , 'tree' , 'sight']
print (classes)
print ('Remove a class:')
classes.remove('tree')
print (classes)
print ('Pop a class:')
favclass = classes.pop (0)
print (classes)
print ('My favorite class is' , favclass)
|
b976d0512d6932a56ab590325bf9d63b32eb869a | amerus/python_basic_11_05_20 | /homework/lesson3/prob5.py | 1,694 | 3.640625 | 4 | '''
Программа запрашивает у пользователя строку чисел, разделенных пробелом.
При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел,
разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться
к уже подсчитанной сумме. Но если вместо числа вводится специальный символ, выполнение
программы завершается. Если специальный символ введен после нескольких чисел, то вначале
нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу.
'''
sum = 0.0
def strip_and_yield(in_str):
"""Function, which strips a long space-separated string and yields either its float value, zero,
or STOP string. Can be used to sum user input."""
for us in in_str.strip(' ').split(' '):
if us == '$':
yield 'STOP'
try:
float(us)
yield float(us)
except:
yield float(0)
while(True):
try:
user_str = input("Please, enter a series of numbers to get the sum. (In order to abort, enter '$'):\n")
for value in strip_and_yield(user_str):
sum += value
except:
print ("You chose to abort!")
break
finally:
print("Sum of your numbers is {}".format(sum))
|
244db56653add66390af6642d97d93441ea6b2be | iamvee/python-course-2021 | /oop/property_definition.py | 420 | 3.765625 | 4 | class Square:
def __init__(self, side):
self.side = side
@property
def area(self):
return self.side ** 2
@area.setter
def area(self, value):
ratio = (value / self.area) ** 0.5
self.side = self.side * ratio
if __name__ == '__main__':
s = Square(6)
print(s.side, s.area)
s.side = 10
print(s.side, s.area)
s.area = 144
print(s.side, s.area)
|
13fdd47c11575ed5f0633c3a6d94a9b3b8903e40 | Maxim-Kazliakouski/Python_tasks | /My_first_calc.py | 743 | 4.125 | 4 | a = float(input("Введите первое число: "))
b = float(input("Введите второе число: "))
operation = input("Введите операцию: ")
vibor = operation
#sum = "+"
#sub = "-"
#div = "/"
#mul = "*"
#od = "%"
#pow = "**"
if vibor == "+":
print("Результат", a+b)
elif vibor == "-":
print("Результат", a-b)
elif vibor == "*":
print("Результат", a * b)
elif vibor == "pow":
print("Результат", a ** b)
elif vibor == "div" and b != 0:
print("Результат", a // b)
elif vibor == "mod" and b != 0:
print("Результат", a % b)
elif vibor == "/" and b != 0:
print("Результат", a / b)
else:
print("Деление на 0!") |
8f8d933e91546b1347f2bb6a59e469603142508c | Nishant-nehra/twitter_data_python | /project.py | 1,684 | 3.5 | 4 |
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(s):
for i in s:
if i in punctuation_chars:
s=s.replace(i,'')
return(s)
# lists of words to use
positive_words = []
with open("positive_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
positive_words.append(lin.strip())
negative_words = []
with open("negative_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
negative_words.append(lin.strip())
def get_neg(s):
count=0
wds=s.lower().split()
for i in wds:
if strip_punctuation(i) in negative_words:
count+=1
return count
def get_pos(s):
count=0
wds=s.lower().split()
for i in wds:
if strip_punctuation(i) in positive_words:
count+=1
return count
values=[]
fhand=open('project_twitter_data.csv')
lines=fhand.readlines()
header=lines[0]
field_names=header.strip().split(',')
print(field_names)
for row in lines[1:]:
vals=row.strip().split(',')
positive=get_pos(vals[0])
negative=get_neg(vals[0])
net=positive-negative
retweet=int(vals[1])
reply=int(vals[2])
values.append((retweet,reply,positive,negative,net))
fhand.close()
fhand=open('resulting_data.csv','w')
fhand.write('Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score')
fhand.write("\n")
print(values)
for value in values:
row="{},{},{},{},{}".format(value[0],value[1],value[2],value[3],value[4])
fhand.write(row)
fhand.write("\n")
fhand.close()
|
d8198b9a360f1b63d5c7f32fe23d19d0b28ce879 | s1881079/weather-info-plotting | /task1_plenty.py | 2,057 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 15:44:05 2018
This is a program for reading file plenty.data as float
and do some data mapping
@author: Ananomous
"""
from matplotlib import pyplot
import os
def readPlenty(file_dir):
'''read plenty.data and convert to float'''
data = []
in_file = open(file_dir,'r')
for line in in_file.readlines():
slst_line = line.split(' ')
flst_line = [float(item) for item in slst_line]
data.append(flst_line)
in_file.close()
return data
def someHandle(plenty_data):
'''exchange former half of colomn3 with latter half of column 4'''
cl3 = [i[3] for i in plenty_data]
cl4 = [i[4] for i in plenty_data]
mid_id = int(len(cl3) / 2)
f_half3 = cl3[:mid_id]
l_half4 = cl4[mid_id:]
cl3[mid_id:] = l_half4
cl4[:mid_id] = f_half3
return cl3,cl4
def plotAllPlenty(plenty_data):
'''plot all data in plenty.data
using the first coloum as x and other coloums as y'''
print('plotting all data using the first coloum as x and other coloums as y...')
xid = 0
cid_y = [i for i in range(11)]
cid_y.remove(xid)
for yid in cid_y:
x_data = [i[xid] for i in plenty_data]
y_data = [i[yid] for i in plenty_data]
ax.plot(x_data,y_data)
print('plotting completed')
return 1
if __name__ == '__main__':
#change workspace to proper file directory
workspace = os.getcwd()
os.chdir(workspace)
plenty_dir = 'plenty.data'
print('data source: ' + workspace + plenty_dir)
#read data
plenty_data = readPlenty(plenty_dir)
#plot all data as demo
fig,ax = pyplot.subplots()
ax = plotAllPlenty(plenty_data)
pyplot.show()
#handle some colomns
print('exchange former half of column3 with latter half of column4 after plotting...')
ncl3,ncl4 = someHandle(plenty_data)
plenty_data[3],plenty_data[4] = ncl3,ncl4
print('exchange completed')
|
b1acb74615230a15ac903d05020c366b7790d1c0 | pannkotsky/lutz_demo | /demo/models.py | 532 | 3.59375 | 4 | class Person:
def __init__(self, name, age, pay=0, job=None):
self.name = name
self.age = age
self.pay = pay
self.job = job
def __str__(self):
return "{class_} {name}, {age}. {job} paid {pay}".format(
class_=self.__class__.__name__,
name=self.name,
age=self.age,
job=self.job,
pay=self.pay,
)
def to_dict(self):
return self.__dict__
@classmethod
def from_dict(cls, d):
return cls(**d)
|
d1652a3fc54f45acad689f30dc09e24516108d0f | asperaa/back_to_grind | /Binary_Search/1060. Missing Element in Sorted Array_Clean.py | 475 | 3.734375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""1060. Missing Element in Sorted Array [Clean]
"""
class Solution:
def missingElement(self, nums, k):
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) // 2
if nums[mid] - nums[0] - mid >= k:
right = mid
else:
left = mid + 1
return nums[0] + left - 1 + k |
ff37dc96aaface7771a822fd40fae7e8ef1b5e2b | youkx1123/hogwarts_ykx | /python_practice/class_python/bicycle/bicycle_practice.py | 632 | 3.9375 | 4 | """
写一个Bicycle(自行车)类,有run(骑行)方法, 调用时显示骑行里程km(骑行里程为传入的数字):
再写一个电动自行车类EBicycle继承自Bicycle,添加电池电量valume属性通过参数传入,
同时有两个方法:
1. fill_charge(vol) 用来充电, vol 为电量
2. run(km) 方法用于骑行,每骑行10km消耗电量1度,当电量消耗尽时调用Bicycle的run方法骑行,
通过传入的骑行里程数,显示骑行结果
"""
class Bicycle:
def run(self,km):
print(f"骑行了{km}公里")
class EBicycle(Bicycle):
def run(self, km):
print(f"骑行了{km}公里")
|
da695b152900a852f578253eb667952387a77cd9 | arvindkarir/python-pandas-code | /Py exercises/My code/CSS exercises/05_03_alternate.py | 1,275 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 5 20:44:43 2018
@author: User
"""
def phone_bill(plan, minute, new_user, student):
monthly_fees = {'A':40.00, 'B':50.00, 'C':100.00}
free_minutes = {'A':150, 'B':250, 'C':10000}
per_minute = {'A':0.50, 'B':0.25, 'C':0}
# cap_of_minute_charges = {'A':100, 'B':80, 'C':0}
activation_fee_rate = {'A':20, 'B':20, 'C':20}
charge_minutes = activation_fee = 0
find_minutes = minute - free_minutes[plan]
if find_minutes >0:
bill_minutes = find_minutes
else:
bill_minutes = 0
billable_minutes = (bill_minutes)*per_minute[plan]
# print(billable_minutes,'billed minutes')
if plan == 'A' and billable_minutes >= 100:
charge_minutes = billable_minutes
if plan == 'B' and billable_minutes <= 80:
charge_minutes = billable_minutes
if student == True and plan == 'A':
monthly_fees[plan] *= 0.50
if new_user == True and student == False:
activation_fee = activation_fee_rate[plan]
bill_total = 1.13*(monthly_fees[plan]+ charge_minutes + activation_fee)
print("%.2f" % round(bill_total,2))
phone_bill('A', 80, True, True)
phone_bill('B', 300, True, False)
phone_bill('C', 300, False, False) |
bd3e6cecbf66f957c09d25bacd02a96111f0e51f | HB-Kim0106/HAN | /totalsum.py | 149 | 4.03125 | 4 | #!/usr/bin/python3
import sys
num1 = sys.argv[1]
num = float(num1)
def totalsum(num):
ans = (num * (num+1))/2
print(round(ans))
totalsum(num)
|
82de5edcef6ca2301d895185a4ce505d3eb187ea | satoshi6380/RegexEngine | /Problems/Recursive summation/main.py | 93 | 3.5 | 4 | def rec_sum(n):
# write the insides here!
return n + rec_sum(n - 1) if n > 0 else 0
|
d26bd99cb98051b1dd8cfffb66a4b4a439ce580f | DeadSoul-Zh/LeetCode | /258-AddDigits.py | 384 | 3.65625 | 4 | class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
n = 0
while num >= 0:
n += (num % 10)
num /= 10
if num == 0 :
break;
if n == 0 :
return 0
elif n % 9 != 0:
return n % 9
else:
return 9
|
963db86acfc6897399ec4576cd4786c041d92639 | rajan3010/leetcode | /best_time_to_sell_buy.py | 252 | 3.9375 | 4 | def maxProfit(prices):
minPrice=float('inf')
max_profit=0
for price in prices:
minPrice=min(price, minPrice)
max_profit=max(max_profit,price-minPrice)
return max_profit
prices = [7,1,5,3,6,4]
print(maxProfit(prices)) |
15a3926177637cf7b542459adc368c7bc99568ca | vpc20/python-misc | /HashFunctions.py | 278 | 3.546875 | 4 | import hashlib
print(hashlib.algorithms_available)
filename = input("Enter the input file name: ")
sha256 = hashlib.sha256()
with open(filename, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256.update(byte_block)
print(sha256.hexdigest())
|
b2d2cdbd083e6f406f96a4918f475cca570090bd | ishantk/GW2019PA1 | /venv/Session20A.py | 493 | 4.09375 | 4 | import pandas as pd
nums1 = [10, 20, 30, 40, 50]
nums2 = [11, 22, 33, 44, 55]
emp1 = {"eid":101, "name":"John", "age":20}
emp2 = {"eid":201, "name":"Fionna", "age":22}
emp3 = {"eid":301, "name":"Kia", "age":24}
df1 = pd.DataFrame([nums1, nums2])
df2 = pd.DataFrame([emp1, emp2, emp3])
print(df1)
print()
print(df2)
# We will be getting columns instead of Rows below:
print()
print(df1[0])
print()
print(df2["eid"])
print()
print(df2["eid"][1])
print(df2["name"][1])
print(df2["age"][1])
|
df267152c84dab82ec46efcf4918e537ae80f9bf | rkatipally/python-advanced | /src/raj_numpy/numpy_exercise.py | 560 | 4.09375 | 4 | import numpy as np
# Create an array of 10 zeros
print(np.zeros(10))
# Create an array of 10 ones
print(np.ones(10))
# Create an array of 10 fives
print(np.ones(10)*5)
# Create an array of the integers from 10 to 50
print(np.arange(10, 50))
# Create an array of all the even integers from 10 to 50
print(np.arange(10, 50, 2))
# Create a 3x3 matrix with values ranging from 0 to 8
print(np.arange(0,9).reshape(3,3))
# Create a 3x3 identity matrix
print(np.eye(3))
# Use NumPy to generate a random number between 0 and 1
print(np.random.random(1))
|
1f20a6980648ec445ee1ca40ea6153f917b04a43 | Ducky3283/Beginner-Python | /randomnumgen.py | 676 | 4.15625 | 4 | #import the random module
import random
import time
#generate random number method
ranumber = random.randint(1, 20)
#program introduces itself
print("Hello, Im a random number generator.")
time.sleep(5) #add a time delay of 5 seconds
print("Right now, i am thinking of a number between 1 and 20. I bet you cant guess it")
time.sleep(5) #add another time delay of 5 seconds
#ask for user input
while 1==1:
guess = int(input("Please guess a number: "))
if guess < ranumber:
print("Your guess was too low.")
elif guess > ranumber:
print("Your guess was too high.")
else:
print("You're right! Well done")
break
|
0908363a9e00ca389452d8709f6560deef25affb | chowdhurykaushiki/python-exercise | /insertionSortList.py | 411 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 15:50:23 2018
@author: 212634012
"""
print('outside fun',__name__)
def fun():
print('inside fun',__name__)
num=[4,3,2,1,5]
length=len(num)
for i in range(length):
minIdx=i
for j in range(i+1,length):
if num[j]<num[minIdx]:
minIdx=j
num[i],num[minIdx]=num[minIdx],num[i]
print(num)
|
518c84e1ba49d931ce15627cd4a962be68b7f4da | MelvinCC10/Python_Carsh_Course | /Ch11 - Testing Code/test_code_example.py | 572 | 3.65625 | 4 | import unittest
from sampleFunction import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Test for ;get_formatted_name' function."""
def test_first_last_name(self):
"""Do names like 'Janis Joplin' work?"""
formatted_name = get_formatted_name('janis','joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
def test_first_last_middle_name(self):
"""DO names like 'Robby john jackson' work?"""
formatted_name = get_formatted_name('Robby', 'john', 'jackson')
self.assertEqual(formatted_name,'Robby Jackson John')
unittest.main()
|
b1d0ccfe0fc7c5d146e525cdecf7477f4ea4cdcf | komal-navale/PythonBasicLearning | /Python Variables, Data Types & Casting/Variables.py | 1,816 | 4.6875 | 5 | # 1. A variable is created the moment you first assign a value to it.
x = 5
y = "User"
print(x)
print(y)
# 2. Variables do not need to be declared with any particular type, and can even change type after they have been set.
a = 10
a = "Admin"
print(a) # This will show last assigned value to same variable. In this case it is Admin
# 3. You can get the data type of a variable with the type() function.
z = 12
print(type(z))
# 4. String variables can be declared either by using single or double quotes.
b = "John"
# is the same as
b = 'John'
# 5. Variable names are case-sensitive.
c = 4
C = "Hello"
# C will not overwrite c
# Variable Names
# Legal variable names
myvar = "Komal"
my_var = "Komal"
_my_var = "Komal"
myVar = "Komal"
MYVAR = "Komal"
myvar2 = "Komal"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
# Illegal variable name:
2myvar = "Komal"
my-var = "Komal"
my var = "Komal"
#This example will produce an error in the result
# 1. Assigning many values to multiple variables
x, y, z = "Mango", "Banana", "Chikoo"
print(x)
print(y)
print(z)
# 2. Assigning one value to multiple variables
a = b = c = 5
print(a)
print(b)
print(c)
# 3. Unpack a collection
vehicles = {"Car", "Bicycle", "Truck"}
p, q, r = vehicles
print(p)
print(q)
print(r)
#Output Variables
x = "Object Oriented"
print("Python is "+x)
a = 2
b = 5
c = a+b
print('Value of c is '+str(c))
p = 9
q = 5
print(p-q)
y = "Add"
z = 5
print(y+z)
# Global Variables
x = "Server side web development"
def myFunc1():
x = "Machine Learning"
print('Python is used in '+x)
myFunc1()
print('Python is used in '+x)
print('------------------------------------------------')
#Global keyword
x = "awesome"
def myFunc2():
global x
x = "popular"
myFunc2()
print('Python is '+x)
|
63e2eba2a161aa90e2329a5bf6bad44e041edbb6 | kira-ll/python-learn | /hello.py | 466 | 4.03125 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
name = input('please enter your name:')
print('hello',name)
height = 1.75
weight = 80.5
bmi = weight / (height*height)
if bmi < 18.5:
print("过轻")
elif bmi >= 18.5 and bmi < 25:
print("正常")
elif bmi >= 25 and bmi < 32:
print("过重")
else:
print("肥胖")
names = ['a','b','c']
names.insert(1,'aa')
for name in names:
print(name)
list(range(100))
sum = 0
for x in range(101):
sum = sum + x
print(sum) |
10b3cbe761c667b948d0bd9f3b9d416bc414ed7a | KarlaDiass/AulaEntra21_Karla | /atividadesPY/While_Introdução/exercicio1.py | 1,483 | 4.15625 | 4 | """Exercício 1
(não usar o continue ou o break)
Crie um programa que mostre um memu com as seguites opções:
1) Soma
2) Subtração
3) Multiplicação
S) Para sair!
Para número 1: Peça 2 números e mostre a soma deles
Para número 2: Peça 2 númeors e mostre a subtração deles
Para númeor 3: Peça 2 números e mostre a multiplicação deles
Para S: Mostre uma mensagem de despedida e termine o programa.
Para qualquer outra opção deve aparecer a mensagem "Opção Inválida"
"""
opcao = ''
while opcao != 'S':
opcao = input('''
***CALCULADORA***
1) Soma
2) Subtração
3) Multiplicação
S) Sair
Digite a opção desejada: ''')
print('\n')
if (opcao == '1'):
num1 = int(input("Insira o primeiro número: "))
num2 = int(input("Insira o segundo número: "))
soma = num1 + num2
print(f"O resultado da soma é: {soma}\n")
elif (opcao == '2'):
num1 = int(input("Insira o primeiro número: "))
num2 = int(input("Insira o segundo número: "))
sub = num1 - num2
print(f"O resultado da subtração é: {sub}\n")
elif (opcao == '3'):
num1 = int(input("Insira o primeiro número: "))
num2 = int(input("Insira o segundo número: "))
mult = num1*num2
print(f"O resultado da multiplicação é: {mult}")
elif (opcao =='S'):
print(f"Obrigada pela escolha\nATÉ!\n")
else:
print("Opção Invália") |
2f0b7e2238b6f22326fe6e75a60d6ed0a0cf520f | odormond/adventofcode | /2022/9/nine.py | 2,722 | 3.546875 | 4 | #! /usr/bin/env python
import advent_of_code as adv
test_data = """\
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
"""
def to_motions(data):
return [
(move, int(distance)) for line in data.splitlines() for move, distance in [line.split()]
]
DX = {'R': 1, 'U': 0, 'L': -1, 'D': 0}
DY = {'R': 0, 'U': 1, 'L': 0, 'D': -1}
def move_knot(xh, yh, xt, yt):
if xh-1 <= xt <= xh+1 and yh-1 <= yt <= yh+1:
pass # Touching -> do nothing
elif yh > yt and xh == xt:
yt = yh - 1 # Same column and above
elif yh < yt and xh == xt:
yt = yh + 1 # Same column and below
elif xh > xt and yh == yt:
xt = xh - 1 # Same line and right
elif xh < xt and yh == yt:
xt = xh + 1 # Same line and right
elif yh > yt and xh-1 == xt:
xt, yt = xh, yh - 1 # Next column and above
elif yh < yt and xh-1 == xt:
xt, yt = xh, yh + 1 # Next column and below
elif yh > yt and xh+1 == xt:
xt, yt = xh, yh - 1 # Previous column and above
elif yh < yt and xh+1 == xt:
xt, yt = xh, yh + 1 # Previous column and below
elif xh > xt and yh-1 == yt:
xt, yt = xh - 1, yh # Line above and right
elif xh < xt and yh-1 == yt:
xt, yt = xh + 1, yh # Line above and left
elif xh > xt and yh+1 == yt:
xt, yt = xh - 1, yh # Line below and right
elif xh < xt and yh+1 == yt:
xt, yt = xh + 1, yh # Line below and left
elif xh > xt and yh > yt:
xt, yt = xh - 1, yh - 1 # Straight upper right diagonal
elif xh > xt and yh < yt:
xt, yt = xh - 1, yh + 1 # Straight down right diagonal
elif xh < xt and yh > yt:
xt, yt = xh + 1, yh - 1 # Straight upper left diagonal
elif xh < xt and yh < yt:
xt, yt = xh + 1, yh + 1 # Straight down left diagonal
else:
assert False, "Unexpected configuration"
return xt, yt
def simulate(moves, length):
rope = [(0, 0)] * length
visited = {rope[-1]}
for direction, distance in moves:
for step in range(distance):
xh, yh = rope[0]
xh += DX[direction]
yh += DY[direction]
rope[0] = (xh, yh)
for i, (xt, yt) in enumerate(rope[1:], 1):
xt, yt = move_knot(xh, yh, xt, yt)
rope[i] = (xt, yt)
xh, yh = xt, yt
visited.add((xt, yt))
return len(visited)
assert simulate(to_motions(test_data), 2) == 13
print("Part 1:", simulate(adv.input(to_motions), 2))
test_data2 = """\
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
"""
assert simulate(to_motions(test_data), 10) == 1
assert simulate(to_motions(test_data2), 10) == 36
print("Part 2:", simulate(adv.input(to_motions), 10))
|
c7a01905abccd90f3ebb92753d03fb8c85138b83 | tushgup/python-basics | /solutions.py | 2,266 | 4.125 | 4 | #
1. Count no of letters and digits
countL = 0;
countD = 0;
for c in "Test123":
if (c.isalpha()):
countL = countL + 1;
else :
countD = countD + 1;
print("No of letters: ", countL);
print("No of digits: ", countD);
#
2. Remove punctuation
import string
s = "It's a good day"
for c in s:
if c not in string.punctuation:
print(c, end = '')
# 3. Sort alphabets in string
s = "bdca"
b = sorted(s)
c = ''.join(b)
print(c)
# 4. no of each vowel
s = "aabcdee"
vowel = "aeiou"
v = {}.fromkeys(vowel, 0)
for c in s:
if c in v:
v[c] = v[c] + 1
print(v)
# 5. palindrome string
s = "abba"
s1 = s[::-1]
if (s == s1):
print("String is palindrome")
else :
print("String is not palindrome")
# 6. tuple operations
tupleem = ()
print(tupleem)
tuple1 = (1, "test", 1.3)
print(tuple1)
print(tuple1[0: 2])
tuple2 = tuple1 + tuple('b')
print(tuple2)
l = list(tuple2)
print(l)
# 7. tuple to str
tuple1 = ('t', 'u', 's', 'h')
str1 = ''.join(tuple1)
print(str1)
# 8. del tuple element
tuple1 = ('t', 'u', 's', 'h')
l = list(tuple1)
l.remove('u')
t1 = tuple(l)
print(t1)
# 9. check whether item exists in tuple
tuple1 = ('t', 'u', 's', 'h')
for c in tuple1:
if c is 'h':
print("Element found")
else :
print("Not found")
# 10. change last value tuple
tuple1 = ('t', 'u', 's', 'h')
l = list(tuple1)
l[-1] = 'a'
t1 = tuple(l)
print(t1)
# 11. string concat
x = "hello"
y = "world"
res = x + " " + y
print(res)
# 12. set operations
x = set([1, 2, 3, 4])
y = set([7, 8, 3, 4])
x.remove(3)
print(x)
print(x.union(y))
print(x.intersection(y))
print(x.difference(y))
# 13. array
from array
import array
x = array('I', [1, 2, 3, 4])
for i in x:
print(i)
# 14. list unique elements
x = [1, 2, 3, 1, 4, 2]
y = set(x)
print(y)
# 15. array insertion
x = []
for i in range(3):
x.append([])
for j in range(3):
val = int(input("Enter value"))
x[i].append(val)
print(x)
# 16. 2 d array multiplication
import numpy as np
x = [
[1, 2, 3],
[4, 5, 6],
[8, 9, 10]
]
y = [
[3, 2, 1],
[5, 4, 3, ],
[1, 7, 4]
]
res = np.multiply(x, y)
print(res)
# 17. factors of number
x = 10
for i in range(1, x + 1):
if x % i == 0:
print(i)
# 18. Find HCF / GCD
from math
import gcd
x = gcd(20, 8)
print(x)
|
725f87280f21a42a5bb65e553007c4ccf9b19811 | dmheisel/FortyBelow | /players.py | 1,281 | 4.09375 | 4 | class Player:
def __init__(self, name, hand):
self.name = name
self.hand = hand
def __repr__(self):
return self.name
######################################################################
class Hand:
"""
Player's hand consists of six cards in three columns of two.
Card positions are zero indexed
"""
def __init__(self):
self.cards = []
def __repr__(self):
return str(self.cards)
def __iter__(self):
return iter(self.cards)
def add_card(self, position, card):
self.cards.insert(position, card) # inserts before index
# -1 is unneccessary
def add_cards(self, cards):
self.cards.extend(cards)
def remove_card(self, position):
return self.cards.pop(position - 1)
def clear(self):
self.cards.clear()
def show(self):
"""
prints out the current hand with layout of cards in 3 colums as follows:
===============
~ 1 -- 2 -- 3 ~
~ 4 -- 5 -- 6 ~
===============
"""
print(
f"~ {self.cards[0]} == {self.cards[1]} == {self.cards[2]} ~\n~ {self.cards[3]} == {self.cards[4]} == {self.cards[5]} ~"
)
|
f337995e94f98602a3665b2116a90e8992cb0fec | Vipexi/python_course | /time.py | 379 | 3.890625 | 4 | #! /usr/bin/python3
import time
start_time = time.time()
print(start_time)
for x in range(1000):
for y in range(1000):
xy = x+y
print(xy, end=" ")
end_time = time.time()
print(end_time)
print(" ")
print(end_time - start_time)
for y in range(10):
print(str(y) + " ", end="")
time.sleep(1)
time_now = time.time()
print(time_now)
time.ctime(time_now) |
83dfc00c65680431f065067ce998f9489d452a83 | shalini2503/learn_py | /Assign2-2_Singh.py | 1,560 | 4.3125 | 4 | # This assignment asks to write a program in which
# total travel distance is calculated using a loop structure.
class DistanceTraveled:
speed = 0 # speed is in miles per hours
time = 0 # time is in hour
distance = 0 # distance is in miles
# constructor function
def __init__(self, speed, time):
self.speed = speed
self.time = time
# calculate distance in loop structure
def calculate_distance(self):
print('Hour', 'Distance Traveled')
print('--------------------------')
t1 = int(self.time)
t2 = self.time - t1
i = 0
for i in range(t1):
self.distance += self.speed
print(i+1, " ", round(self.distance, 2))
if t2 > 0:
self.distance += self.speed * t2
print(i+2, " ", round(self.distance, 2))
# this class is used to run stdio for this program
class RunInput:
# constructor function
def __init__(self):
while True:
try:
speed = float(input("Enter the speed of the vehicle in mph ").strip())
time = float(input("Enter the number of hours traveled ").strip())
distance_mph = DistanceTraveled(speed, time)
distance_mph.calculate_distance()
except ValueError:
print("Invalid value provided. Try again...")
except:
print("please try again....")
# initiating the script from here
vechiledistance = RunInput()
|
67f59e5f6ef15ca5389f1a163d02bfae6c35bbef | paramita2302/algorithms | /iv/Arrays/wave_array.py | 382 | 3.765625 | 4 | class Wave():
def wave_array(self, A):
A.sort()
for i in range(0, len(A) - 1, 2):
temp = A[i]
A[i] = A[i + 1]
A[i + 1] = temp
return A
def main():
A = [3, 2, 1, 3]
# A = [-1, 0, -1]
# A = [6, 7, 5]
# A = [-6, -1, 4]
a = Wave()
print(a.wave_array(A))
if __name__ == '__main__':
main()
|
2dafd13cba08e61cf3c09867b6ea1bf41e18b331 | umluizlima/testing-101 | /intro/test_sum.py | 529 | 3.90625 | 4 | def test_sum_passes():
"""Assert if the sum of 1, 2 and 3 equals 6.
As the asserted result is correct, this will pass.
"""
assert sum([1, 2, 3]) == 6, "Should be 6"
def test_sum_fails():
"""Assert if the sum of 1, 1 and 1 equals 6.
As the asserted result is incorrect, this will fail with an AssertionError
and the message "Should be 6".
"""
assert sum([1, 1, 1]) == 6, "Should be 6"
if __name__ == "__main__":
test_sum_passes()
# test_sum_fails()
print("Everything passed")
|
6c7d3e6595a1cb779125d71178578466c946e950 | hamzaMahdi/rec2017 | /REC2017Programming/OnymousApp/onymous.py | 1,552 | 3.640625 | 4 | #the following program is supposed to interact with the JSON object
#currently, the program reaches the local host and is able to import the data from it
#however there is an error in converting the JSON to an object that python can interact with
#this lead us to create onymous_static.py which gets data statically and does not update with the JSON object
from urllib.request import urlopen
import json
import codecs
import requests
import json
from collections import namedtuple
def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values())
def json2obj(data): return json.loads(data, object_hook=_json_object_hook)
url = urlopen('http://localhost:5002/')
webpage = urlopen('http://localhost:5002/').read().decode('utf8')
#print(webpage)
#tr = json.loads(url.decode('utf-8'))
obj = requests.get('http://localhost:5002/')
x = json2obj(url.read())
#json syntacx
#response = url.read()
#json = json.load(url)
'''
if json['success']:
ob = json['response']['ob']
print ("The current weather in Seattle is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF'])
else:
print ("An error occurred: %s") % (json['error']['description'])
'''
'''
response = MyView.as_view()(url) # got response as HttpResponse object
response.render() # call this so we could call response.content after
json_response = json.loads(response.content.decode('utf-8'))
print (url)
print(json_response) # {"your_json_key": "your json value"}
#print(result)
#print '"networkdiff":', result['getpoolstatus']['data']['networkdiff']
''' |
e27a088bbbc5c484a61e1f2a7e601d83fefd3529 | udwivedi394/LinkedList | /palindromeList.py | 1,195 | 4.1875 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
def palindromeList(root):
count = 0
temp = root
while temp:
count += 1
temp = temp.next
temp = root
i = 0
while i < count/2:
temp = temp.next
i += 1
back = reverseList(temp)
traverseLL(root)
traverseLL(back)
temp1,temp2 = root,back
while temp1 and temp2:
if temp1.data != temp2.data:
return False
temp1 = temp1.next
temp2 = temp2.next
return True
def reverseList(ll):
temp = head = ll
prev = None
while temp:
if temp.next == None:
head = temp
next_node = temp.next
temp.next = prev
prev = temp
temp = next_node
return head
def traverseLL(head):
temp = head
while temp:
print temp.data,"->",
temp = temp.next
print "None"
root = Node(1)
root.next = Node(2)
root.next.next = Node(3)
root.next.next.next = Node(2)
root.next.next.next.next = Node(1)
#root.next.next.next.next.next = Node(1)
#traverseLL(root)
#root = reverseList(root)
traverseLL(root)
print palindromeList(root)
|
f4942d0589627101ebc341b060c9dbeba966b2bf | Sakthiumamaheshwari97/multipeoffive | /mult.py | 66 | 3.828125 | 4 | numss=int(input())
for x in range(1,6):
print(x*numss,end=" ")
|
04ff4e8bb6e48e265c329b8719f3152a4921adc2 | DongGunYoon/Algo_DS | /mar_26th/circularLinkedList.py | 967 | 4.09375 | 4 | class Node:
def __init__(self, value, next):
self.value = value
self.next = next
class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
node = Node(value, None)
self.head = node
node.next = node
else:
cur_node = self.head
while cur_node.next != self.head:
cur_node = cur_node.next
cur_node.next = Node(value, self.head)
def print(self):
result = ''
cur_node = self.head
while cur_node.next != self.head:
result += str(cur_node.value) + ' '
cur_node = cur_node.next
result += str(cur_node.value)
print(result)
linked = CircularLinkedList()
linked.append(1)
linked.append(3)
linked.print()
linked.append(5)
linked.append(7)
linked.print()
linked.append(9)
linked.append(11)
linked.print() |
7c2378b06734db998778f404ef4a3c0ce7b49f65 | pankypan/DataStructureAndAlgo | /leetcode/basicDS08_heap/b04_lc253_min_meeting_rooms.py | 1,036 | 3.5 | 4 | import heapq
from typing import List
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
# 按会议开始时间进行排序
intervals.sort(key=lambda item: item[0])
priority_queue = list()
heapq.heappush(priority_queue, intervals[0][1])
for i in range(1, len(intervals)):
meeting = intervals[i]
# meeting 完全大于堆顶 则 堆顶空闲
if meeting[0] >= priority_queue[0]: # 房间空闲: meeting 的开始时间 大于堆顶的 结束时间
heapq.heappop(priority_queue)
heapq.heappush(priority_queue, meeting[1])
else: # 房间不空闲
heapq.heappush(priority_queue, meeting[1])
return len(priority_queue)
if __name__ == '__main__':
s = Solution()
print(s.minMeetingRooms([[1, 10], [2, 7], [3, 19], [8, 12], [10, 20], [11, 30]]))
print(s.minMeetingRooms([[0, 30], [5, 10], [15, 20]]))
print(s.minMeetingRooms([[7, 10], [2, 4]]))
|
3d7da9faeee321fc3d63a703ee8bee35134b355c | Bill2462/AX3003P | /examples/testProtection.py | 3,522 | 3.625 | 4 | """ Example that demonstrates the overcurrent protection (OVP)
and overvoltage protection (OVC).
This script sets the OVP level to 5V and OCP to 0.3A.
Then slowely increases the voltage until the OVP trips.
Next the OVP is reseted and the same procedure is repeated with the OCP.
"""
# This file is part of AX3003P library.
# Copyright (c) 2019 Krzysztof Adamkiewicz <kadamkiewicz835@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the “Software”), to deal in the
# Software without restriction, including without limitation the rights to use, copy,
# modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the
# following conditions: THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
# OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys
from time import sleep
import AX3003P
# Get the port selection from the command line argument.
if len(sys.argv) < 2:
print("usage: python3 helloWorld.py [device]")
print("Example: python3 helloWorld.py /dev/ttyUSB0")
sys.exit(1)
port = sys.argv[1]
# connect to the power supply and enable output
psu = AX3003P.connect(port)
# Set the OVP and OCP level.
print("Setting OVP threshold to 5V...")
psu.setOvpTreshold(5)
print("Setting OCP threshold to 0.5A")
psu.setOcpTreshold(0.3)
print("\n######### Testing the OVP #########")
# set the current to 50mA
psu.setCurrent(0.05)
psu.enableOutput()
# slowly increase the voltage until the OVP trips
voltages = [1, 2, 4, 9] # voltages that we are going to test
for voltage in voltages:
# a little hack to trigger the OVP.
# Normally PSU won't allow us to set voltage higher then OVP threshold.
# However we can first turn the OVP off, set the voltage and turn it back on.
psu.disableOvp()
sleep(2)
psu.setVoltage(voltage)
sleep(4)
psu.enableOvp()
sleep(1) # delay to allow the voltage to stabilize
# check if ovp is tripped
if psu.ovpTripped():
status = "TRIP"
else:
status = "RDY"
# print the status
print("Voltage: " + str(voltage) + "V OVP: " + status)
if status == "TRIP":
break # exit if ovp tripped
# reset OVP and set voltage to 5V
print("Resetting the OVP...")
psu.resetOvp()
psu.setVoltage(5)
#now we have to short the PSU output
print("Short PSU output and press enter to continue")
input()
print("\n######### Testing the OCP #########")
psu.enableOutput()
# slowely increase the current until OCP trips
currents = [0.1, 0.2, 0.3, 1.0]
for current in currents:
psu.disableOcp()
sleep(2)
psu.setCurrent(current)
sleep(4)
psu.enableOcp()
sleep(1) # delay to allow the voltage to stabilize
# check if ovp is tripped
if psu.ocpTripped():
status = "TRIP"
else:
status = "RDY"
# print the status
print("Curent: " + str(current) + "A OCP: " + status)
if status == "TRIP":
break # exit if ocp tripped
#disable output and disconnect
psu.disableOutput()
psu.resetOcp()
psu.disconnect()
|
7128cd1ae9a1b803409d1c9973fbc9560ee3a870 | Helloworld616/algorithm | /SWEA/응용/5186_이진수2/sol1.py | 885 | 3.625 | 4 | import sys
sys.stdin = open('sample_input.txt')
# 이진수 변환 함수
def to_binary(N):
# 이진수 결과 초기화
binary = ''
# N이 0 이하가 될 때까지 반복문 실행
while N > 0:
# N을 2배 더한 값을 변수 double에 할당
double = N*2
# double의 정수 부분만 추출해서 binary에 합산
binary += str(int(double))
# binary의 길이가 12를 넘어가면 overflow 반환
if len(binary) > 12:
return 'overflow'
# doble의 소수 부분만을 N에 할당
N = double - int(double)
# 이진수 변환 결과 반환
return binary
# main
T = int(input())
for tc in range(1, T+1):
# N 입력 받기
# 주의! 실수로 입력 받아야 함!
N = float(input())
# 이진수 변환 결과 출력
print('#{} {}'.format(tc, to_binary(N)))
|
9881aa187cb706cf2c7b7785a78fb175afb1a3d4 | akhandsingh17/assignments | /topics/BinarySearch/CapacityToShipPacakges.py | 2,030 | 4.34375 | 4 | """
A conveyor belt has packages that must be shipped from one port to another within days days.
The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15
Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
refer - https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/discuss/819184/6-questions-in-one-template-of-binary-search-for-beginners-python
Method:
left - inclusive; right - exclusive
use while left < right
if finding min value, define 'isok' function (and return left) ;
if finding max value, define 'isfail' function (and return left-1).
"""
from typing import List
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def isOk(mid):
day = 1
cursum = 0
for weight in weights:
if cursum + weight > mid:
day += 1
cursum = 0
cursum += weight
return day <= days
left = max(weights)
right = sum(weights) + 1
while left < right:
mid = left + (right - left) // 2
if isOk(mid):
right = mid
else:
left = mid + 1
return left
if __name__ == '__main__':
s = Solution()
print(s.shipWithinDays(weights=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days=5))
|
474e049cf6d0f3849bb4df33df87784469174c5e | pperorin/Data-Struct | /3.2 Parenthesis Matching.py | 1,535 | 3.65625 | 4 | class Stack:
def __init__(self,lst = None):
self.lst = lst if lst is not None else []
def push(self,item):
self.lst.append(item)
def pop(self):
self.lst.pop()
def peek(self):
return self.lst[-1]
def size(self):
return len(self.lst)
def isEmpty(self):
return len(self.lst) == 0
def remove(self,item):
self.lst.remove(item)
def lststack(self):
return self.lst
inpt = input('Enter expresion : ')
op = ['{','[','(']
cl = ['}',']',')']
st=Stack()
st1=Stack()
for i in inpt:
if i in op:
st.push(i)
elif i in cl:
if i == '}':
if '{' in st.lststack():
st.remove('{')
else:
st1.push(i)
elif i == ']':
if '[' in st.lststack():
st.remove('[')
else:
st1.push(i)
else:
if '(' in st.lststack():
st.remove('(')
else:
st1.push(i)
if st.isEmpty() and st1.isEmpty():
for f in inpt:
print(f,end='')
print(' MATCH')
elif st.isEmpty():
for a in inpt:
print(a,end='')
print(' close paren excess')
elif st1.isEmpty():
for b in inpt:
print(b,end='')
print(' open paren excess '+str(st.size())+' : ',end='')
for c in st.lststack():
print(c,end='')
else:
for d in st.lststack():
print(d,end='')
for e in st1.lststack():
print(e,end='')
print(' Unmatch open-close') |
0335714468f25c9ee4f4bb2c02f7cb1d2440c3de | nlpjoe/fullstack-nanodegree-vm | /vagrant/tournament/tournament.py | 4,503 | 3.5625 | 4 | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect(database_name="tournament"):
"""Connect to the PostgreSQL database. Returns a database connection."""
try:
db = psycopg2.connect("dbname={}".format(database_name))
cursor = db.cursor()
return db, cursor
except Exception as e:
raise e
def deleteMatches():
"""Remove all the match records from the database."""
db, cursor = connect()
query = "TRUNCATE match CASCADE;"
cursor.execute(query)
db.commit()
db.close()
def deletePlayers():
"""Remove all the player records from the database."""
db, cursor = connect()
query = "TRUNCATE player CASCADE;"
cursor.execute(query)
db.commit()
db.close()
def countPlayers():
"""Returns the number of players currently registered."""
db, cursor = connect()
query = "SELECT count(*) as num from player"
cursor.execute(query)
count = cursor.fetchone()[0]
db.close()
return count
def registerPlayer(name):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique).
"""
db, cursor = connect()
query = "INSERT INTO player (name) values (%s);"
param = (name,)
cursor.execute(query, param)
db.commit()
db.close()
def playerStandings():
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place,
or a player tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by the database)
name: the player's full name (as registered)
wins: the number of matches the player has won
matches: the number of matches the player has played
"""
db, cursor = connect()
query = '''SELECT player.id, name, COALESCE(wins, 0) , COALESCE(matches, 0)
from player left join
((SELECT id, count(*) as matches from player, match
where player.id = match.loser
OR player.id = match.winner
group by player.id) as tm
LEFT JOIN
(SELECT winner as wid, count(*) as wins from match
group by winner) as tw
ON tw.wid = tm.id) as twm
ON player.id = twm.id
ORDER BY wins DESC
'''
cursor.execute(query)
result = cursor.fetchall()
db.close()
return result
class match(object):
"""docstring for match"""
def __init__(self, arg):
super(match, self).__init__()
self.arg = arg
def reportMatch(winner, loser):
"""Records the outcome of a single match between two players.
Args:
winner: the id number of the player who won
loser: the id number of the player who lost
"""
db, cursor = connect()
query = "insert into match (winner, loser) values (%s, %s)"
param = (winner, loser)
cursor.execute(query, param)
db.commit()
db.close()
def swissPairings():
"""Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a player adjacent
to him or her in the standings.
Returns:
A list of tuples, each of which contains (id1, name1, id2, name2)
id1: the first player's unique id
name1: the first player's name
id2: the second player's unique id
name2: the second player's name
"""
db, cursor = connect()
cursor = db.cursor()
cursor.execute('''SELECT player.id, name, wins FROM player LEFT JOIN
(SELECT winner, count(*) as wins from match group by winner) as tw
ON player.id = tw.winner
ORDER BY wins
''')
result = cursor.fetchall()
db.close()
pairings = []
for index in range(0, len(result), 2):
item = (result[index][0], result[index][1],
result[index+1][0], result[index+1][1])
pairings.append(item)
return pairings
|
ab6c06de37bf84a28d04d0b673f791dd7adc7447 | 42Inc/MIP | /Sem-2/Lab-1/src/readWrite_v2.py | 1,941 | 3.734375 | 4 | #!/usr/bin/env python3
experiment = 50 # Amount of tries in one experiment
measuring = 1000 # Amount of measurings in one try
alphabet = 26 # Length of the given alphabet (Default: Eng - 26 letters)
def genRnd():
readersData = [[0 for cnt in range(experiment)] for cnt in range(2)]
for attempt in range(1, experiment + 1):
firstReaderAvg = 0 # Average amount of read letters for the first reader's stream
secondReaderAvg = 0 # Average amount of read letters for the second reader's stream
for cnt in range(1, measuring + 1):
firstReader = 0 # Amount of read letters for the first reader's stream on the current measuring
secondReader = 0 # Amount of read letters for the second reader's stream on the current measuring
GodBlessRNG = 1 # RND number for deciding when we need to end current measuring
while (GodBlessRNG != 0):
GodBlessRNG = rnd.randint(0, 100)
if (1 <= GodBlessRNG < attempt and firstReader + 1 <= alphabet):
firstReader += 1
elif (attempt <= GodBlessRNG < (2 * attempt) and secondReader + 1 <= alphabet):
secondReader += 1
else:
continue
firstReaderAvg += firstReader
secondReaderAvg += secondReader
readersData[0][attempt - 1] = firstReaderAvg / 1000
readersData[1][attempt - 1] = secondReaderAvg / 1000
return readersData
def drawGraph(y_arr):
x_arr = [cnt for cnt in range(experiment)] # Array of values similar to alphabet. Made for better graph performance
plt.plot(x_arr, y_arr[0], label="First reader's stream")
plt.plot(x_arr, y_arr[1], label="Second reader's stream")
plt.ylabel("Average amount of read letters")
plt.xlabel("Alphabet")
plt.legend()
plt.show()
def main():
data = genRnd()
drawGraph(data)
if __name__ == '__main__':
try:
import sys
import numpy as np
import random as rnd
import matplotlib.pyplot as plt
except Exception as err:
print("Error while loading dependencies:", err)
exit(-1)
main()
|
a7ea53e96c428ca41356a28e86bf93b663197f72 | ParadoxPD/Random-Projects | /NCode/OCT/4.py | 133 | 3.765625 | 4 |
def number_sum(n):
return sum([int(x) for x in str(n)])
N = int(input())
R = int(input())
print(number_sum(R*number_sum(N)))
|
7cfdead1e1789d68ba58a23dc93cf1f467fb7687 | stevenraybon/Python | /Imputation/Imputation_Methods.py | 8,314 | 3.578125 | 4 | ###Comparing Imputation Methods
###10/10/2017
'''
Goal of code:
Want to compare "prediction errors" of different imputation methods.
Will compare Scikit-Learn Imputation methods (mean, median, mode) and
a method using OLS to predict missing values.
Going forward, a better way to isolate predictive power
is to divide sample into 'units' and then find means across diff units.
Sections:
(1) Get data: I used data from NLSY (longitudinal study) that I had on hand.
(2) Clean data: get rid of NaN's in dataset
(3) Remove values of annual earnings randomly
(4) Use different imputation methods to compute imputed values of missing data
(5) Compare sum of squared "error" of predicted values vs actual values
'''
from numpy import random as rand
import pandas as pd
import numpy as np
import os
from sklearn import linear_model
import matplotlib.pyplot as plt
from sklearn.preprocessing import Imputer
import math
'''
(1) Get Data
'''
df = pd.read_csv('NLSY97.csv')
col_keep = ['inid', 'year', 'age', 'married', 'female', 'urban', 'hrsusu', 'ann_earnings', 'edulev', 'White', 'Black', 'Am_Indian', 'Asian']
data = df[col_keep]
'''
(2) Clean Data
There are lots of NaN's:
Create a new dataframe that gets rid of any records with NaN's ...
present in any column
'''
#data[data['age'].isnull()==True].head(10)
#data.isnull().values.any()
cleandata_int = data.dropna(axis=0, how="any")
#cleandata_int.isnull().values.any()
'''
Generate dummy variables for vars that are entered as factors.
Then drop the old columns to keep DF tidy.
Merge cleandata_int with the dummy vars to get cleanData
'''
sex_d = pd.get_dummies(cleandata_int['female'])
edulev_d = pd.get_dummies(cleandata_int['edulev'])
cols_to_drop = ['edulev', 'female']
cleandata_int.drop(cols_to_drop, axis=1, inplace=True)
to_merge = [cleandata_int, sex_d, edulev_d]
cleanData = pd.concat(to_merge, axis=1)
'''
(3) Remove Values of Earnings Randomly
Create a random vector
Based on the random values in it, we can remove x% of data
by indicating a threshold (i.e. if we want to remove 10%
of the data, then we can specify data be removed for random
numbers over 0.90 .
'''
rand.seed(123)
randvec = []
for i in range(len(cleanData)):
randvec.append(rand.uniform(0,1))
'''
We will just randomly remove values of annual earnings. This
way, we can use regression and the other variables to come up
with a model to predict the values of the missing entries.
For about 10% of the data, replace ann_earnings with NaN
keep the real values in the missing_earn array
this will just keep an index corresponding to the data removed
'''
missing_earn = [[0 for n in range(2)] for m in range(len(cleanData))]
truncdata = cleanData.copy()
for i in range(len(cleanData)):
if randvec[i]>.9 :
missing_earn[i][0] = i
missing_earn[i][1] = cleanData.iloc[i,6]
truncdata.iloc[i,6] = np.nan
else:
missing_earn[i][0] = i
missing_earn[i][1] = np.nan
missing_earn_df = pd.DataFrame(missing_earn, columns=['index','value'])
missing = missing_earn_df.dropna()
'''
(4) Imputation Methods
Here we use the 3 imputation methods in Scikit-Learn's Imputer() class
-Mean
-Median
-Mode
I also specify a linear regression model that uses all other variables
as covariates to predict the values of the missing entries
For each imputer, the data is taken from the truncated data matrix (truncdata)
and the imputer is applied to the raw data. The data is then transformed into
a pandas dataframe.
'''
imputer_mean = Imputer(strategy='mean')
imputer_median = Imputer(strategy='median')
imputer_mode = Imputer(strategy='most_frequent')
cols = truncdata.columns
truncdata_values = truncdata.values
'''
Mean
'''
transformed_values_mean = imputer_mean.fit_transform(truncdata_values)
data_mean_df = pd.DataFrame(transformed_values_mean,columns=cols)
'''
Median
'''
transformed_values_median = imputer_median.fit_transform(truncdata_values)
data_median_df = pd.DataFrame(transformed_values_median,columns=cols)
'''
Mode
'''
transformed_values_mode = imputer_mode.fit_transform(truncdata_values)
data_mode_df = pd.DataFrame(transformed_values_mode,columns=cols)
'''
Regression
'''
'''
Need to define X and y"
X will contain the regression covariates and records that do
not correspond to NaN values for annual earnings. truncdata_no_nan
is thus created and y,X created from it.
'''
cols_drop = ['inid', 'year', 'female', 'HighSchool','ann_earnings']
truncdata_no_na = truncdata.dropna()
X_train = truncdata_no_na.drop(cols_drop, axis=1, inplace=False)
y_train = truncdata_no_na["ann_earnings"]
'''
Train/Test model:
The test values for X are the NaN values from the truncdata matrix. The ols_model
contains the model estimates. We will use those estimates to predict values of
annual earnings using the covariate values corresponding to NaN's.
Lastly, turn results into dataframe.
'''
model = linear_model.LinearRegression()
ols_model = model.fit(X_train,y_train)
X_test = truncdata.ix[truncdata["ann_earnings"].isnull()==True,X_train.columns]
ols_predicted = ols_model.predict(X_test)
pred_df = pd.DataFrame(ols_predicted, index=missing["index"])
pred_df.columns = ["OLS_Pred"]
'''
Use predicted OLS values to impute.
Create indices in truncdata (the df that contains
all values - NaN and non-NaN - of annual earnings) and
in pred_df (the df that contains predicted values)
so that a new matrix can be created that merges the two
dataframes. The merging will allow us to get the predicted
values in with the actual values and then we can create a column
that combines both.
Final result is a df that includes the actual and imputed values
of annual earnings. Call it imputedData.
'''
pred_df["indexes"]=missing["index"]
index_copy = []
for i in range(len(truncdata)):
index_copy.append(i)
truncdata["indexes"] = index_copy
merged = pd.merge(truncdata, pred_df, on='indexes', how='left')
'''
If annual earnings is NaN (has been removed) then populate the
new_earnings column with imputed values. If it's not NaN, then
populate column with actual value.
'''
for i in range(len(merged)):
if math.isnan(merged["ann_earnings"][i]):
merged.ix[i,"new_earnings"] = merged.ix[i,"OLS_Pred"]
else:
merged.ix[i,"new_earnings"] = merged.ix[i,"ann_earnings"]
'''
Collect results into clean dataframe
'''
cleanedData_act = cleanData["ann_earnings"].reset_index()
compare_df = [cleanedData_act["ann_earnings"], data_mean_df["ann_earnings"], data_median_df["ann_earnings"], data_mode_df["ann_earnings"], merged["new_earnings"]]
imputedData = pd.concat(compare_df, axis=1)
imputedData.columns = ["Actual", "Impute(Mean)", "Impute(Median)", "Impute(Mode)", "OLS"]
'''
(5) Compare prediction error
Create a dataframe that includes sqrt[(predicted - actual)^2] for
each imputation method. About 90% of the entries will be 0 since
the data didn't change.
Sum up the errors and put into an array that
will be used to graph.
'''
pred_error_cols = ['Imputed Mean', 'Imputed Median', 'Imputed Mode', 'Imputed OLS']
pred_error_data = [[0 for n in range(4)] for m in range(len(imputedData))]
pred_error_df = pd.DataFrame(pred_error_data,columns=pred_error_cols)
for i in range(len(imputedData)):
pred_error_df.ix[i,'Imputed Mean'] = math.sqrt((imputedData.ix[i,"Impute(Mean)"] - imputedData.ix[i,"Actual"] )**2)
pred_error_df.ix[i,'Imputed Median'] = math.sqrt((imputedData.ix[i,"Impute(Median)"] - imputedData.ix[i,"Actual"] )**2)
pred_error_df.ix[i,'Imputed Mode'] = math.sqrt((imputedData.ix[i,"Impute(Mode)"] - imputedData.ix[i,"Actual"] )**2)
pred_error_df.ix[i,'Imputed OLS'] = math.sqrt((imputedData.ix[i,"OLS"] - imputedData.ix[i,"Actual"] )**2)
'''
Calculate sums
'''
sum_mean = pred_error_df['Imputed Mean'].sum()
sum_median = pred_error_df['Imputed Median'].sum()
sum_mode = pred_error_df['Imputed Mode'].sum()
sum_ols = pred_error_df['Imputed OLS'].sum()
sums = [sum_mean, sum_median, sum_mode, sum_ols]
sum_arr = np.array(sums)
'''
Graph Results
'''
tick_labels = ('Mean', 'Median', 'Mode', 'OLS')
heights = [sum_mean, sum_median, sum_mode, sum_ols]
x = range(len(sum_arr))
plt.bar(x,heights, align='center', alpha=0.5 )
plt.xticks(range(len(sum_arr)), tick_labels)
plt.title("Prediction Error by Imputation Method")
plt.savefig('PredErrorBar.pdf')
plt.show()
|
c501b1aabf12bc966c3d4a118332c58bd2000dac | jgomez07/Election_Analysis | /Resources/If-elif-else.py | 640 | 4.3125 | 4 | # What is the score?
score = int(input("What is your test score? "))
# Determine the grade.
if score >= 90:
print('Your grade is an A.')
elif score >= 80:
print('Your grade is a B.')
elif score >= 70:
print('Your grade is a C.')
elif score >= 60:
print('Your grade is a D.')
else:
print('Your grade is an F.')
#the length of the decision structure determines
# whether you use a nested if-else statement or the if-elif-else statement.
# If you have to scroll horizontally on your computer screen to see all the code in an
# if-else statement , then you should use an if-elif-else statement. |
df910e98dd3c2f00c00aaf3ff7c6aa7b9e8ccd3e | ndri/challenges | /old/40.py | 201 | 4.09375 | 4 | #!/usr/bin/env python
# 40 - Find the largest number in an array, and print its position
from random import randint
array = [randint(0,99) for i in range(20)]
print array
print array.index(max(array))
|
29144eca28894e2704c27acafc639ab5dd98469b | jmyao17/Learning_Vocabulary | /lec01/YourName.py | 1,291 | 4.40625 | 4 |
# **********************************************************
## lecture01: first python code
# **********************************************************
## - practice with the input() function
## - concept of variables: string and integer number
## - proactice with print() function
print("R2D2: Welcome to Star Wars!")
# name=input("R2D2: What's your name? \n")
# # - don't forget qotation mark "" for a string
# ## - \n is used for change line
# print("R2D2: Hi, "+name+"!")
# print("R2D2: I hope you are doing well today.")
## - The operator + is for joining two strings.
# **********************************************************
# Now let's try to repeat the above operation with variables
# **********************************************************
R2D2_S1 = "R2D2: What's your name? \n"
name = input(R2D2_S1)
R2D2_S2 = "R2D2: Hi, "+ name+"!"
R2D2_S3 = "R2D2: I hope you are doing well today."
print(R2D2_S2)
print(R2D2_S3)
## Now let's add some more information
age = input("R2D2: How old are you? \n")
next_year_age = int(age) + 1
R2D2_S4="R2D2: Wow! Next year you will be "+str(next_year_age)+" years old."
print(R2D2_S4)
R2D2_S5="R2D2: Congratulation! Let's fight Darth Vader together!"
print(R2D2_S5)
|
bf36cc412c903cdd1a46109d436c6afdf187aa2c | 5l1v3r1/kinematics_py_calculator | /Calc.py | 787 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
print("V")
print("D")
print("T")
choice = input ("Please make a choice: ")
if choice == "V":
print("V = D / T")
D = float( input ("D = ") )
T = float( input ("T = ") )
print("V = "),
print(D/T)
elif choice == "D":
print("D = V * T")
V = float( input ("V = ") )
T = float( input ("T = ") )
print("D = "),
print(V*T)
elif choice == "T":
print("T = D / V")
D = float( input ("D = ") )
V = float( input ("V = ") )
print("T = "),
print(D/V)
print("hours"),
print( (D/V) * 60 )
print("minutes")
else:
print("I don't understand your choice.")
main()
|
4837e8769ab408661c6c502d7e88c51be2c6b9d1 | gfike19/machineLearning | /work/students-10-12.py | 1,763 | 3.875 | 4 | import pandas as pd
import numpy as np
studentData = pd.read_excel("C:/Users/aerot/coding/machineLearning/Week3/Assignments/students.xlsx")
studentDf = pd.DataFrame(studentData)
# Filter class 1 and class 2 students - COMPLETE
# print("Class 1\n")
# print(studentData[(studentData["class"] == 1)],"\n")
# print("Class 2\n")
# print(studentData[(studentData["class"] == 2)])
# sortByClass = studentDf.sort_values(by="class")
# print(sortByClass)
# TODO Add percentage of all students in separate percentage column
# class1 = pd.DataFrame(studentData["class"])
# studentData.insert(4, "Class Percent", )
# Topper of class 1 in math - COMPLETE
# topMathClass1 = pd.DataFrame(studentData[(studentData["class"] == 1)])["maths"]
# print(studentDf["class"] == 1, "\n")
# print(topMathClass1.head())
# Topper of class 2 in english -COMPLETE
# topEngClass2 = pd.DataFrame(studentData[(studentData["class"] == 2)])["english"]
# print(studentDf["class"] == 2, "\n")
# print(topEngClass2.head())
# Topper in both classes - COMPLETE ?
# print(studentData.head())
# TODO Names of the students which starts with ‘A’ along with their class
# namesStartA = pd.DataFrame(studentData[studentData["Name"]]).apply(startsWith("A"))
# print(namesStartA)
# Names of all students who failed in class 1 in any subject (less than 40% mark is a fail in any subject) COMPLETE ?
# class1F = studentData[(studentData["class"] == 1) & ((studentData["maths"] < 40) | (studentData["science"] < 40) | (studentData["english"] < 40))]
# print(class1F)
# Names of students in class 1 who failed in all subjects - COMPLETE ?
# class1F = studentData[(studentData["class"] == 1) & (studentData["maths"] < 40) & (studentData["science"] < 40) & (studentData["english"] < 40)]
# print(class1F)
|
8ccbbe72bf43b591ef783aea08dde2b5af7650d4 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/kndsit001/question1.py | 620 | 4.125 | 4 | """Program to Determine Palindrome
Sithasibanzi Kondleka
9 May 2014"""
words = input("Enter a string:\n")
def palindrome(string):
if string == "": #a message that contains nothing is technically a palindrome
return "Palindrome!"
if len(string) == 1:
return "Palindrome!" #a message that contains 1 letter is technically a palindrome
else:
if string[0] == string[-1]: #isolating the letters at the ends
return palindrome(string[1:-1])
else:
return "Not a palindrome!" #should the ends not match it is not a pali-pal
print(palindrome(words)) |
a8d3dd1b28f4d1ec27544eb9ad418a7f87407008 | Seorimii/PythonStudy2019 | /mar_24/0324_54.py | 193 | 3.609375 | 4 | class Add:
def add(self,n1,n2):
return n1+n2
class Calculator(Add):
def sub(self,n1,n2):
return n1-n2
obj= Calculator()
print(obj.add(1,2))
print(obj.sub(1,2)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.