blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2f7684e7aa08437358aead7c7c1b4e6029d8402b | AnhTuan2804/LearnPython | /learn.py | 729 | 3.671875 | 4 | import datetime
# item = [12, 2,6,4,9]
# print(item)
# print(sum(item))
# item.sort()
# print(item)
# def sumItem(list):
# total = 0
# for subitem in list:
# total +=subitem
# return total, total
# print(sumItem(item)[0])
class person():
name = 'Dog'
age = 20
color = 'blue'
eye = 'green'
def getColor(self):
return self.color
def getAge(abc):
return abc.age
class Teo(person):
def getEye(self):
return self.eye
# boy = person()
# print(boy.getAge())
# print(boy.getColor())
# print('end')
# TeoEm = Teo()
# print(TeoEm.getColor())
# print(TeoEm.getEye())
print(datetime.date.today())
print(datetime.date.today().year)
arr = ['aca', 'aaa']
|
bbce0488f3266680f4aa4368584031c16a2d255b | andjo16/course-help | /DM550 - Introduction to Programming/Python_examples/MandelbrötColour.py | 3,786 | 3.828125 | 4 | """Messy, but fairly optimized code for drawing the mandelbrot set using
turtle graphics"""
import turtle
"""These values can be modyfied to change the rendering"""
width = 200 #Size in max distance from 0,0. Medium performance impact
#width = 500 fits a maximized window on a 1080p screen
height = width #Needs to be a square to render properly
maxiterations = 255 #Precision or sharpness. Higher values needed when zooming.Low performance impact
#A value of 255 gives good colours at 100% zoom
spacing = 1 #Only check every x pixels. Use 1 for perfect image. High performance impact.
#Use a higher value to test rendering. Usefull when zooming
zoompercent = 100 / 100 #How zoomed in. Modyfies performance of maxiterations
zoomx = 0 #Offset x and y to zoom in on.
zoomy = 0 #These two are supposed to be coordinates on the mandelbrot set, but it changes with zoom.
updatetime = 5 #number of lines to update at a time. Changeging performance impact
"""Global variables, not supposed to be changed"""
updatecount = 0
xoffset = 0.75 * width #Approxymately centers the set on canavas
tu = turtle.Turtle() #Prepares the turtle
tu.speed(0)
tu.hideturtle()
tu.up()
turtle.tracer(0, 0)
turtle.Screen().colormode(255)
escaped = prevesc = 0
"""Methods"""
def draw(x, y):
"""Draws a single pixel at x,y"""
tu.up()
tu.setpos(x,y)
tu.down()
tu.setpos(x + 1,y)
def maprangex(val):
"""Maps a pixel x-coordinate to be rendered to be between -1 and 1"""
tomax = 1
tomin = -1
valnorm = (val + width) / (width + width)
return (tomin + valnorm * (tomax - tomin) + zoomx) / zoompercent
def maprangey(val):
"""Maps a pixel y-coordinate to be rendered to be between -1 and 1"""
tomax = 1
tomin = -1
valnorm = (val + height) / (height + height)
return (tomin + valnorm * (tomax - tomin) + zoomy) / zoompercent
def mandelbrot(x, y):
"""Returns true if pixel at x,y is in the (approxemated) mandelbrot set"""
normx = maprangex(x)
normy = maprangey(y)
xcalc = 0.0
ycalc = 0.0
iteration = 0
expon = 2
while (xcalc**expon + ycalc**expon < 2**expon and iteration < maxiterations):
temp = xcalc**expon - ycalc**expon + normx
ycalc = 2*xcalc*ycalc + normy
xcalc = temp
iteration += 1
if (xcalc**expon + ycalc**expon < 2**expon):
return iteration
return iteration
def mapcolor(val, maxval):
"""This sets the turtle pen colour based on how many iterations out
of the maximum iterations have been reached"""
norm = val / maxval
#Red, green and blue components
r = int(193.80370873*norm**2+61.19629127*norm)
g = int(-1020*norm**2+1020*norm)
b = int(193.80370873*norm**2-448.80370873*norm+255)
#Forces colours to be withing 0-255
r = forcerange(r)
g = forcerange(g)
b = forcerange(b)
tu.pencolor(r, g, b)
def forcerange(colval):
"""Caps a value at 0 and 255"""
if colval > 255:
return 255
elif colval < 0:
return 0
else:
return colval
"""Main code"""
for y in range(-height, height + 1, spacing): #For every line
prevesc = escape = 0 #Reset variables
for x in range(int(-width*2.5), width + 1, spacing): #For every pixel in line
escape = mandelbrot(x, y) #Checks if pixel escaped
if escape != prevesc:
if tu.ycor() != y:
tu.up()
else:
tu.down()
tu.setpos(x + xoffset,y)
if escape != maxiterations:
mapcolor(escape, maxiterations)
else:
tu.pencolor(0,0,0)
prevesc = escaped
updatecount += 1
if updatecount > updatetime: #Updates the drawing every updatetime lines
turtle.update()
updatecount = 0
turtle.update() #Final update
turtle.mainloop() #mainloop prevents the window from freezing |
57bab83657cbb240b216a56e4fc69018277840bb | kemingy/daily-coding-problem | /src/subarray_sum.py | 544 | 3.984375 | 4 | # Given an array of numbers, find the maximum sum of any contiguous subarray of
# the array.
def max_sum(array):
maximum, cur = 0, 0
for a in array:
cur = max(0, cur + a)
maximum = max(maximum, cur)
return maximum
if __name__ == '__main__':
for array in [
[34, -50, 42, 14, -5, 86],
[-5, -1, -8, -9],
[-2, -3, 4, -1, -2, 1, 5, -3]]:
print('Maximum sum of contiguous subarray of {} is {}'.format(
array, max_sum(array)
))
|
7800bb5de4761f760a3ad91e0436160d2a1dc865 | Keshav1506/competitive_programming | /Linked_List/005_leetcode_P_160_IntersectionOfTwoLinkedLists/Solution.py | 12,357 | 3.734375 | 4 | #
# Time : O(m+n)
# Space: O(1)
# @tag : Linked List
# @by : Shaikat Majumdar
# @date: Aug 27, 2020
# **************************************************************************
# LeetCode - Problem - 160: Intersection of Two Linked Lists
#
# Write a program to find the node at which the intersection of two singly linked lists begins.
#
# For example, the following two linked lists:
# ___ ___
# / \ / \
# A: | a1 |-->| a2 | ____ ____ ____
# \ ___ / \ ___ / \ / \ / \ / \
# ___ ___ __ + c1 |--->| c2 |--->| c3 |
# / \ / \ / \ + | \ ____ / \ ____ /
# B: | b1 |-->| b2 |-->| b3 |/ \ ____ /
# \ ___ / \ ___ / \ ___/
# begin to intersect at node c1.
#
# Example 1:
#
# ___ ___
# / \ / \
# A: | 4 |-->| 1 | ____ ____ ____
# \ ___ / \ ___ / \ / \ / \ / \
# ___ ___ __ + 8 |--->| 4 |--->| 5 |
# / \ / \ / \ + | \ ____ / \ ____ /
# B: | 5 |-->| 6 |-->| 1 |/ \ ____ /
# \ ___ / \ ___ / \ ___/
#
# Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
# Output: Reference of the node with value = 8
# Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
# From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5].
# There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
#
#
# Example 2:
#
# ___ ___ ___
# / \ / \ / \
# A: | 1 |-->| 9 |-->| 1 | ____ ____
# \ ___ / \ ___ / \ ___ /\ / \ / \
# __ + 2 |--->| 4 |
# / \ + | \ ____ /
# B: | 3 |/ \ ____ /
# \ ___/
# Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
# Output: Reference of the node with value = 2
# Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
# From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4].
# There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
#
#
# Example 3:
#
# ___ ___ ___
# / \ / \ / \
# A: | 2 |-->| 6 |-->| 4 |
# \ ___ / \ ___ / \ ___ /
#
# ___ ___
# / \ / \
# B: | 1 |-->| 5 |
# \ ___ / \ ___ /
#
# Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
# Output: null
# Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5].
# Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
# Explanation: The two lists do not intersect, so return null.
#
#
# Notes:
#
# * If the two linked lists have no intersection at all, return null.
# * The linked lists must retain their original structure after the function returns.
# * You may assume there are no cycles anywhere in the entire linked structure.
# * Each value on each linked list is in the range [1, 10^9].
# * Your code should preferably run in O(n) time and use only O(1) memory.
#
# **************************************************************************
# Source: https://leetcode.com/problems/intersection-of-two-linked-lists/ (Leetcode - Problem 160 - Intersection of Two Linked Lists)
# https://practice.geeksforgeeks.org/problems/intersection-point-in-y-shapped-linked-lists/1/ (GeeksForGeeks - Intersection Point in Y Shapped Linked Lists)
#
# **************************************************************************
# Solution Explanation
# **************************************************************************
# Two Pointers:
# * Maintain two pointers pA and pB initialized at the head of A and B, respectively.
# Then let them both traverse through the lists, one node at a time.
# * When pA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.);
# similarly when pB reaches the end of a list, redirect it the head of A.
# * If at any point pA meets pB, then pA/pB is the intersection node.
# * To see why the above trick would work, consider the following two lists:
# A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'.
# Since B.length (=4) < A.length (=6), pB would reach the end of the merged list first,
# because pB traverses exactly 2 nodes less than pA does. By redirecting pB to head A, and pA to head B,
# we now ask pB to travel exactly 2 more nodes than pA would. So in the second iteration,
# they are guaranteed to reach the intersection node at the same time.
# * If two lists have intersection, then their last nodes must be the same one.
# So when pA/pB reaches the end of a list, record the last element of A/B respectively.
# If the two last elements are not the same one, then the two lists have no intersections.
#
import unittest
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __eq__(self, other):
if not self.equal(other):
# print("List1 != List2 where")
# print("List1:")
# print(str(self))
# print("List2:")
# print(str(other))
# print("\n")
return False
else:
return True
def equal(self, other):
if other is not None:
return self.val == other.val and self.next == other.next
else:
return False
def __repr__(self):
lst = []
p = self
while p:
lst.append(str(p.val))
p = p.next
return "List: [{}].".format(",".join(lst))
def initList(self, nums):
if not nums:
return None
head = None
current = None
for n in nums:
if not head:
head = ListNode(n)
current = head
else:
node = ListNode(n)
current.next = node
current = node
return head
def printList(self, head):
string = ""
if not head:
return string
while head.next:
if head.val is None:
string += "%s->" % str(head.val)
else:
string += "%d->" % head.val
head = head.next
if head.val is None:
string += "%s->" % str(head.val)
else:
string += "%d" % head.val
return string
# length of linked list => recursive function
def length(self, head):
if head is None:
return 0
else:
return 1 + self.length(head.next)
# length of linked list => iterative function
# def length(self, head):
# temp = head
# count = 0
# while(temp):
# count += 1
# temp = temp.next
# return count
class Solution:
# Suppose there are two linked lists A and B with an intersection I starting at node X.
# The length of intersection is L, A's length is L1+L and B's is L2+L.
#
# And we have two pointers, pa and pb, walk through A and B in such way that pa first walks through A
# then switch to B while pb first walks through B then switch to A.
#
# In such manner, when pa and pb have walked a distance of L1+L2+L, pa has walked through |A|+|B-I| (L1+L+L2)
# and reaches X while pb has walked through |B|+|A-I| (L2+L+L1) and reaches X as well.
# Therefore, both pa and pb points to the start node of intersection when they first meet each other (pa == pb).
#
# Meanwhile, if A and B has no intersection (L = 0), pa reaches the end of B and pb reaches the end of A.
# Both of them point to None (pa==pb==None), which is also what to return.
# So we can combine two cases in such way:
#
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if headA is None or headB is None:
return None
# listNode = ListNode()
# print(listNode.printList(headA))
# print(listNode.printList(headB))
# 2 pointers
pointerA, pointerB = headA, headB
# listNode = ListNode()
i = 0
while pointerA != pointerB:
i += 1
# print(f'Iteration: [ {i} ].')
# if either pointer hits the end, switch head and continue the second traversal,
# if not hit the end, just move on to next
pointerA = pointerA.next if pointerA else headB
# print(listNode.printList(pointerA))
pointerB = pointerB.next if pointerB else headA
# print(listNode.printList(pointerB))
# pointerA = headB if pointerA == None else pointerA.next
# pointerB = headA if pointerB == None else pointerB.next
# only 2 ways to get out of the loop, they meet or the both hit the end=None
# print(listNode.printList(pointerA))
return pointerA
# the idea is if you switch head, the possible difference between length would be countered.
# On the second traversal, they either hit or miss.
# if they meet, pa or pb would be the node we are looking for,
# if they didn't meet, they will hit the end at the same iteration, pa == pb == None, return either one of them is the same,None
class Test(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_getIntersectionNode(self) -> None:
listNode = ListNode()
s = Solution()
for headA, headB, solution in (
[
listNode.initList([4, 1, 8, 4, 5]),
listNode.initList([5, 6, 1, 8, 4, 5]),
listNode.initList([1, 8, 4, 5]),
],
[
listNode.initList([1, 9, 1, 2, 4]),
listNode.initList([3, 2, 4]),
listNode.initList([2, 4]),
],
[
listNode.initList([10, 20, 5, 10]),
listNode.initList([30, 40, 50, 5, 10]),
listNode.initList([5, 10]),
],
[listNode.initList([2, 6, 4]), listNode.initList([1, 5]), None],
):
self.assertEqual(
solution,
s.getIntersectionNode(headA, headB),
"Should find the node at which the intersection of two singly linked lists begins",
)
for headA, headB, solution in (
[
listNode.initList([4, 1, 8, 4, 5]),
listNode.initList([5, 6, 1, 8, 4, 5]),
1,
],
[listNode.initList([1, 9, 1, 2, 4]), listNode.initList([3, 2, 4]), 2],
[
listNode.initList([10, 20, 5, 10]),
listNode.initList([30, 40, 50, 5, 10]),
5,
],
[listNode.initList([2, 6, 4]), listNode.initList([1, 5]), None],
):
self.assertEqual(
solution,
s.getIntersectionNode(headA, headB).val
if s.getIntersectionNode(headA, headB)
else None,
"Should find the node at which the intersection of two singly linked lists begins",
)
if __name__ == "__main__":
# listNode = ListNode()
# s = Solution()
# headA = listNode.initList([4, 1, 8, 4, 5])
# headB = listNode.initList([5, 6, 1, 8, 4, 5])
# print(f'output = [ {listNode.printList(s.getIntersectionNode(headA, headB))} ].')
unittest.main()
|
26430923a360291c8989a841d477ce38d3d1b62c | dbsima/python-playground | /programming-foundation-with-python/rename-file-names/rename-file-names.py | 473 | 3.875 | 4 | import os
def rename_files():
current_dir = os.path.dirname(os.path.abspath(__file__))
path_to_dir = current_dir + '/prank'
file_list = os.listdir(path_to_dir)
os.chdir(path_to_dir)
for file_name in file_list:
new_name = ''.join([i for i in file_name if not i.isdigit()])
print "The file " + file_name + " is now named " + new_name
os.rename(file_name, new_name)
os.chdir(current_path)
rename_files()
|
91608f884fad01a9a0f65ca46d06893e665cebfe | Anzanrai/AlgorithmicToolbox | /week2_solution/gcd.py | 636 | 3.71875 | 4 | # Uses python3
import sys
def gcd_naive(a, b):
current_gcd = 1
for d in range(2, min(a, b) + 1):
if a % d == 0 and b % d == 0:
if d > current_gcd:
current_gcd = d
return current_gcd
def remainder(a, b):
return a % b, b
def gcd_euclid(a, b):
if a > b:
if a % b != 0:
return gcd_euclid(b, a%b)
else:
return b
else:
if b % a != 0:
return gcd_euclid(a, b%a)
else:
return a
if __name__ == "__main__":
input_val = input()
a, b = map(int, input_val.split())
print(gcd_euclid(a, b))
|
8b5b9fb9435a9f19f3228eadffd664fe780475cb | saurabh-pandey/AlgoAndDS | /leetcode/linkedList/singly_linked_list/tests/test_odd_even.py | 698 | 3.546875 | 4 | import singly_linked_list.odd_even_a1 as a1
import singly_linked_list.operations_a1 as sll_a1
solutions = {"attempt_1": a1}
slls = {"attempt_1": sll_a1}
class TestOddEvenList:
def test_example1(self):
for attempt, solve in solutions.items():
sll = slls[attempt]
head = sll.create([1,2,3,4,5])
oddEven = solve.oddEvenList(head)
assert sll.toList(oddEven) == [1,3,5,2,4]
def test_example2(self):
for attempt, solve in solutions.items():
sll = slls[attempt]
head = sll.create([2,1,3,5,6,4,7])
oddEven = solve.oddEvenList(head)
assert sll.toList(oddEven) == [2,3,6,7,1,5,4]
|
7330bfad0a0a0aba5b0ef00df904013d5c02274e | Hunt66/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 191 | 3.65625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
if matrix is None or len(matrix) is 0 or matrix[0] is None:
return matrix
return [[i ** 2 for i in j] for j in matrix]
|
a0eb5d44b62d28cf0f049bd8b817de968ac183a1 | stanml/image_similarity | /python_scripts/text_similarity.py | 2,138 | 3.53125 | 4 | import itertools as it
import editdistance
# The segmentation algorithm can potentially extract text in an arbitrary order,
# therefore, the Levenshtein measure can classifiy text with exactly the same
# sentences as being different because of the order. This class gives a score
# based on matched segments by taking the Levenshtien distance between text
# segments to determine a match, and then returning the overall similarity score
# of matched segments within the image.
class TextSimilarity:
def __init__(self, text_array1, text_array2, threshold=None):
self.clean_text1 = self.__remove_blanks(text_array1)
self.clean_text2 = self.__remove_blanks(text_array2)
self.max_characters = self.__max_text(self.clean_text1, self.clean_text2)
self.matches = []
self.total_characters = []
if threshold is None:
self.match_threshold = 70
else:
self.match_threshold = threshold
def return_matches(self):
if (len(self.clean_text1) or len(self.clean_text2)) == 0:
return False
else:
self.__get_matches()
matches = sum(self.matches)
return (float(matches) / self.max_characters) * 100
def __get_matches(self):
return map(lambda x: self.__matched_element(x), self.__combinations())
def __matched_element(self, pair):
score, matched_words = self.__n_text_matches(pair[0], pair[1])
if score > self.match_threshold:
self.matches.append(matched_words)
def __n_text_matches(self, text1, text2):
max_letters = self.__max_elems(text1, text2)
matched_words = max_letters - editdistance.eval(text1, text2)
score = (float(matched_words) / max_letters) * 100
return score, matched_words
def __max_elems(self, array1, array2):
return max(len(array1), len(array2))
def __max_text(self, text1, text2):
return max(self.__count_characters(text1), self.__count_characters(text2))
def __count_characters(self, array):
return len(''.join(array))
def __remove_blanks(self, text_array):
return set(filter(None, text_array))
def __combinations(self):
return list(it.product(self.clean_text1, self.clean_text2))
|
d13ff39717f581af0159df12819fd548411d2aee | Vworri/Computational-Physics-Review | /madelungConstant.py | 1,601 | 3.59375 | 4 | import scipy.constants as s_const
from math import pi
#In condensed matter physics, the Madelung constant gives the total electric potential felt by an atom in a solid.
#In this program, we will use the sodium chloride wich is arranged in a cubic lattice. The vertexes of the cube alternate
#positive to negative with the same charge e. If we give each vertex three coordinates, then the sodium atoms will fall
# where j+k+i is even. The chloride atoms will fall where i+j+k is odd.
#We also know that the Madelung constant is equal to the summation of of the potential energy of all the atoms in the
#lattice divided by (4*pi*epsilon_0)*the spacing of the lattice.
#The potential enery of a charge is Q/4*pi*epsilon*r with r being the distance between the atom and the origin.
#The summation domain is from one end of the cube to the other excluding the origin.
e = s_const.elementary_charge #absolute value of electron charge
epsilon_0 = s_const.epsilon_0 # permittivity of vacuum
L = 600 #1/2 the width of the cube
a =1 #spacing of the atoms
V_tot = 0 #initial potential energy
# This works but the O^3 iteration is a bummer. I think if I let it sit at L= 1000 my computer will die
for i in range(-L,L+1):
for j in range(-L,L+1):
for k in range(-L,L+1):
if (i == 0 or j==0 or k==0):
V_tot +=0
elif ((i+j+k)%2 == 0):
V_tot += e/(4*pi*epsilon_0*a*((i**2)+(j**2)+(k**2))**0.5)
else:
V_tot -= e/(4 * pi * epsilon_0 * a * ((i ** 2) + (j ** 2) + (k ** 2))**0.5)
print((V_tot*(4 * pi * epsilon_0 * a ))/e)
|
6a1f0e6bcd7c1f3d7ed3d512d76046617608c904 | lanngo27/data-structures-algorithms | /recursion/prime_numbers/tests.py | 844 | 4.125 | 4 | import unittest
import math
from prime_numbers import has_divisors
class TestPrimeNumbers(unittest.TestCase):
def test_with_10_not_prime_numbers(self):
"""has_divisors returns True if numbers are not prime numbers. (10p)"""
numbers = [4,8,10,15,20,155,270,300,444,985]
for number in numbers:
self.assertTrue(has_divisors(number, int(math.sqrt(number) // 1) + 1), "Number {} is not a prime number.".format(number))
def test_with_10_prime_numbers(self):
"""has_divisors returns False if numbers are prime numbers. (10p)"""
numbers = [3,5,7,11,13,17,19,23,29,31]
for number in numbers:
self.assertFalse(has_divisors(number, int(math.sqrt(number) // 1) + 1), "Number {} is a prime number.".format(number))
if __name__ == "__main__":
unittest.main(verbosity=2)
|
b1c8876b6d7a7f2a795711584e4d2d1c3e568617 | aka-luana/AulaEntra21_Luana | /Entra21-Python Maykon/01-Exercicios/Aula008/parte2.py | 1,978 | 3.875 | 4 | import parte1
from parte1 import listaPessoa
listaEndereco = []
def cadastroEndereco():
if(len(listaPessoa) == 0):
print("Primeiro cadastre uma pessoa.")
else:
numeroId = input("Digite o seu ID: ")
if(numeroId.isspace()):
while(numeroId.isspace()):
numeroId = input("ID em branco. Digite novamente: ")
numeroId = int(numeroId)
if(numeroId > len(listaPessoa) or numeroId < 0):
print("Id inválido")
else:
rua = input("Digite a sua rua: ")
if(rua.isspace()):
while(rua.isspace()):
rua = int(input("Rua em branco. Digite novamente: "))
numero = input("Digite o número: ")
if(numero.isspace()):
while(numero.isspace()):
numero = input("Número em branco. Digite novamente: ")
numero = int(numero)
complemento = input("Digite o complemento: ")
if(complemento.isspace()):
while(complemento.isspace()):
complemento = int(input("Complemento em branco. Digite novamente: "))
bairro = input("Digite o bairro: ")
if(bairro.isspace()):
while(bairro.isspace()):
bairro = int(input("Bairro em branco. Digite novamente: "))
cidade = input("Digite o cidade: ")
if(cidade.isspace()):
while(cidade.isspace()):
cidade = int(input("Cidade em branco. Digite novamente: "))
estado = input("Digite o estado: ")
if(estado.isspace()):
while(estado.isspace()):
estado = int(input("Estado em branco. Digite novamente: "))
listaEndereco.append({'ID':numeroId, 'Rua':rua, 'Numero-Casa':numero, 'Complemento':complemento, 'Bairro':bairro, 'Cidade':cidade, 'Estado':estado})
print("Cadastrado com sucesso!") |
401ce4682507daad5f48d776f832f466fbbd910f | dkavaler/cracking_the_coding_interview | /chapter1/1.2.py | 850 | 3.515625 | 4 | from collections import defaultdict
TEST_STRINGS = [('kjjkll', 'kkjjll'), ('dkaj', 'jkad',),
('abcde', 'edcba'), ('eeaee', 'aaeaa'),
('defg', 'gfde'), ('akjd', 'buif')]
CORRECT_RESULTS = [True, True, True, False, True, False]
# O(len(string1) + len(string2)) using hash table
def is_permutation(string1, string2):
if len(string1) != len(string2):
return False
seen_d = defaultdict(int)
for c in string1:
seen_d[c] += 1
for c in string2:
seen_d[c] -= 1
for c, count in seen_d.items():
if count != 0:
return False
return True
def check_result(result):
return all([result[i] == CORRECT_RESULTS[i] for i in range(len(result))])
if __name__ == '__main__':
result = [is_permutation(s1, s2) for s1, s2 in TEST_STRINGS]
assert check_result(result) |
72e82eae3b2441f68c5e681a232577c49dcaa44a | leandro-matos/python-scripts | /aula02/ex14.py | 193 | 3.578125 | 4 | sal = float(input('Qual é o salário do Funcionário? R$ '))
aumentoSal = sal + (sal * 15/100)
print(f'Um funcionário que ganhava {sal}, com 15% de aumento, passa a receber {aumentoSal:.2f}') |
ca3ac506e199133d845f8234277bfc6b4a13134a | vivek-144/1BM17CS144-PYTHON | /8_DataBase.py | 1,882 | 4.0625 | 4 | import sqlite3
from sqlite3 import Error
conn = sqlite3.connect('student.db')
print("Connection Established")
cur = conn.cursor()
def create_table():
cur.execute("CREATE TABLE STUDENT (SID int primary key, name text, age int, marks int)")
conn.commit()
print("STUDENT table created.")
def insertor():
cur.execute("INSERT INTO STUDENT(SID,NAME,AGE,MARKS) VALUES(1650, 'Sooraj', 20, 71)")
cur.execute("INSERT INTO STUDENT(SID,NAME,AGE,MARKS) VALUES(1651, 'John', 21, 80)")
cur.execute("INSERT INTO STUDENT(SID,NAME,AGE,MARKS) VALUES(1652, 'David', 21, 78)")
cur.execute("INSERT INTO STUDENT(SID,NAME,AGE,MARKS) VALUES(1653, 'Cameroon', 20, 70)")
conn.commit()
print("Values inserted into STUDENT Table.")
def DisplayAll():
print('All Student\'s Data:')
val = cur.execute('SELECT * FROM STUDENT')
for row in val:
print('Student ID:', row[0])
print('Student Name:', row[1])
print('Student Age:', row[2])
print('Student Marks:', row[3])
print('')
def DisplayQuery():
print('Students With Marks Less Than 75:')
val = cur.execute('SELECT * FROM STUDENT WHERE marks<75')
for row in val:
print('Student ID:', row[0])
print('Student Name:', row[1])
print('Student Age:', row[2])
print('Student Marks:', row[3])
print('')
def updator():
cur.execute('UPDATE STUDENT SET name = "Akash" where SID = 1653')
conn.commit()
def delete():
cur.execute('DELETE FROM STUDENT WHERE SID = 1652')
conn.commit()
n=0
while n==0:
try:
create_table()
insertor()
DisplayAll()
DisplayQuery()
updator()
print("||| Data after Updation |||")
DisplayAll()
delete()
print("||| Data after Deletion |||")
DisplayAll()
except Error as e:
print(e)
n=1
|
ff75ffede3bfa18c62dae3c55f68cb30139d17f9 | parrisma/Reinforcement-Learning | /examples/PolicyGradient/TestRigs/RewardFunctions/LocalMaximaRewardFunction1D.py | 4,262 | 3.5625 | 4 | import math
from typing import Tuple
import numpy as np
from examples.PolicyGradient.TestRigs.Interface.RewardFunction1D import RewardFunction1D
"""
This Reward Function has two local maxima and one global maxima. This is modelled as 2.5 cycles
of a sinusoidal curve with the 2nd (central) peek weighed as give it a larger magnitude than the
peeks either side. The function is symmetrical around the turning point of the central peek.
So the RL Agent should be able to find and maximise to move the agent to the central peek even
when starting at the state space extremity and having to pass through the local maxima.
If x is a value in radians and state space is in range (0 to m)then the reward function is:
sin(x)* EXP(1-ABS((x-(m/2))/(m/2)))
"""
class LocalMaximaRewardFunction1D(RewardFunction1D):
__state_min = int(0)
__state_max = int(60)
__state_step = int(1)
__center_state = int(__state_max / 2.0)
__x_min = float(0)
__x_max = float(2.5 * (2 * math.pi))
__x_step = float(15.0 * (math.pi / 180.0)) # 15 degree steps as radians
def __init__(self):
"""
Start in a default reset state.
"""
self.state = None
self.num_steps = int((self.__state_max - self.__state_min) / self.__state_step)
self.done_state = int(self.num_steps / 2)
self.reset()
return
def reset(self) -> np.array:
"""
Reset state to a random step between state space min and max
:return: The state after reset was performed.
"""
self.state = self.__state_step * np.random.randint(self.num_steps)
return np.array([self.state])
def reward(self,
state: float) -> float:
"""
Compute the reward for the given state;
If x is a value in radians and state space is in range (0 to m)then the reward function is:
sin(x)* EXP(1-ABS((x-(m/2))/(m/2)))
:param state:
:return: Reward for given state
"""
x = state * self.__x_step
return math.sin(x) * math.exp(1 - math.fabs((x - (self.__x_max / 2.0)) / (self.__x_max / 2.0)))
def step(self,
actn: int) -> Tuple[np.array, float, bool]:
"""
Take the specified action
:param actn: the action to take
:return: The new state, the reward for the state transition and bool, which is true if episode ended
"""
if actn == 0:
self.state += self.__state_step
elif actn == 1:
self.state -= self.__state_step
else:
raise RuntimeError("Action can only be value 0 or 1 so [" + str(actn) + "] is illegal")
dn = (self.state < self.__state_min or self.state > self.__state_max or self.state == self.done_state)
return np.array([self.state]), self.reward(self.state), dn
@classmethod
def state_space_dimension(cls) -> int:
"""
The dimensions of the state space
:return: Always 1 as this is for 1D reward functions.
"""
return super(LocalMaximaRewardFunction1D, cls).state_space_dimension()
def state_shape(self) -> Tuple[int, int]:
"""
What are the dimensions (Shape) of the state space
:return: Tuple describing the shape
"""
return super(LocalMaximaRewardFunction1D, self).state_shape()
@classmethod
def num_actions(cls) -> int:
"""
The number of actions
:return: Always 2 as this is a 1D state space so only 2 directions of state space traversal.
"""
return super(LocalMaximaRewardFunction1D, cls).num_actions()
def state_min(self):
"""
What is the minimum value of 1D state space
:return: Minimum value of 1D state space
"""
return self.__state_min
def state_max(self):
"""
What is the maximum value of 1D state space
:return: Maximum value of 1D state space
"""
return self.__state_max
def state_step(self):
"""
What is the discrete step increment used to traverse state space (by actions)
:return: The discrete step increment used to traverse state space (by actions)
"""
return self.__state_step
|
d478f8b6d5c7811e432ffb23d2d892dec4a72893 | starbucksdolcelatte/AI_Practice_2019 | /Programming_Mathematics/[01]Number_Theory-Prime_Number/mersenne.py | 408 | 3.84375 | 4 | def isPrime2(n):
# To-do
if(n<=1):
return False
if(n%2 == 0):
return False
else:
for i in range(1, int(n**0.5)):
if(n % (i*2+1) == 0):
return False
return True
pass
def mersenne(n):
return isPrime2(2**n-1)
# 결과 출력을 위한 코드입니다. 자유롭게 값을 바꿔보며 확인해보세요.
print(mersenne(2))
|
b536c689d8bef8ec9de689d80eba9c03f74444e4 | kevin-goetz/Python-Specialization | /01_Programming for Everybody (Getting Started with Python)/PY4E_Exercise 4.1.py | 252 | 3.609375 | 4 | # %%
"""
Exercise 4.1: Run the program on your system and see what numbers you get.
Run the program more than once and see what numbers you get.
"""
import random # noqa
for i in range(10):
x = round(random.random()*100)
print(x)
|
cae63bb302d25fd70c99763ee56c3b919675548c | norrismei/coding-fun | /linked_list_remove_duplicates_from_sorted_ll.py | 2,255 | 4.28125 | 4 | # You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order.
# Delete nodes and return a sorted list with each distinct value in the original list.
# The given head pointer may be null indicating that the list is empty.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def print_singly_linked_list(node):
while node:
print(str(node.data))
node = node.next
def removeDuplicates(head):
# if linked list is empty, return None
if head is None:
return None
# if linked list only has one node, then there are no duplicates to remove
if head.next is None:
return head
else:
# starting with first two nodes as prev and curr, move through list, comparing current to previous
previous = head
current = head.next
while current:
# if current is equal to previous, then this is a duplicate that we have to delete
if current.data == previous.data:
# link previous's next node to current's next node so the linkedlist stays intact
previous.next = current.next
# current node updates to the next node we just linked from previous
current = current.next
# continue with loop to compare new current to previous
continue
# else current is greater than previous, keep moving through linked list
else:
# previous becomes the node we just looked at
previous = current
# current node moves on to the next node
current = current.next
return head
ll = SinglyLinkedList()
for num in [1, 2, 2, 3, 3, 5]:
ll.insert_node(num)
print_singly_linked_list(removeDuplicates(ll.head))
|
938e83c42b759eafb41db21adb090f77007cf92e | aumaro-nyc/leetcode | /trees/114.py | 864 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root: return
self.queue = []
def preorder(root):
"""
Performs pre-order traversal and appends nodes to Queue
"""
if not root: return
self.queue.append(root)
preorder(root.left)
preorder(root.right)
preorder(root)
current = self.queue.pop(0)
current.left = None
while self.queue:
temp = self.queue.pop(0)
temp.left = None
current.right = tmp
current = tmp
|
cc69510c34e62d218652b963e82cc5a068660661 | HelloMyFriend-o/Weathergetabot | /database/db.py | 663 | 3.546875 | 4 | import psycopg2 as psycopg2
from loader import PG_DB, PG_USER, PG_PASS, PG_HOST, PG_PORT
def connect_to_db():
connection = psycopg2.connect(
database=PG_DB,
user=PG_USER,
password=PG_PASS,
host=PG_HOST,
port=PG_PORT
)
return connection
def create_a_tb():
connection = connect_to_db()
cursor = connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS users
(
first_name TEXT,
last_name TEXT,
user_id INTEGER,
city TEXT,
lat FLOAT,
lon FLOAT
)""")
# Disconnecting from the DB.
connection.commit()
connection.close()
|
c0f4440364657b75b98af371d05ad5a8f647022a | Debjit337/Python | /7.1.Tuple work.py | 843 | 4.25 | 4 | mytuple= ('A','B','C','D','E')
print(mytuple[3])
print(mytuple[1:3])
print(mytuple[-3:-1])
Coming=('A','B','C')
Notcoming=('D','E','F')
Changes=list(Coming)
Changes.append('D')
Changes.append('E')
print(Changes)
Coming=tuple(Changes)
print(Coming)
Changes=list(Coming)
Changes.remove('C')
Changes.remove('B')
print(Changes)
Coming=tuple(Changes)
print(Coming)
invitationcard='''
--------------------------------------------
Coming
--------------------------------------------
1.{}
2.{}
3.{}
'''.format(mytuple[0],mytuple[3],mytuple[4])
print(invitationcard)
invitationcard='''
--------------------------------------------
Not Coming
--------------------------------------------
1.{}
2.{}
3.{}
'''.format(mytuple[1],mytuple[2],mytuple[3])
print(invitationcard) |
49e9c154a3217c2b26ab7f3c4091fb2d80718c72 | dola258/Python | /ex01/var.py | 580 | 4.03125 | 4 | # 1. 파이썬은 인터프리터 언어이다.
# 2. 파이썬은 모든 것이 객체이다.
# 3. 파이썬은 변수의 타입이 없다. 타입 추론을 지원한다.
# 4. boolean 의 true, false 첫글자 대문자로
# 5. ''' ~~~ ''' 사이는 문자열
# 6. "" '' 상관없이 사용가능
a=1
b=1.2
c="문자"
d='문자'
e=True
f=False
g='''
안녕하세요.
반가워요.
하하하핳
'''
print (type(a)) # 1 int
print (type(b)) # 1.2 float
print (type(c)) # str
print (type(d)) # str
print (type(e)) # bool
print (type(f)) # bool
print (type(g)) # str
|
fe45d5e2a4ca70c0e8ed2859fc86e336a3797959 | zahid1905/PracticeJAVAPrograms | /ejercicios5/src/Hanoi.py | 751 | 3.8125 | 4 | def hanoi(n, torre0, torre2, torre1):
if n > 0:
# Mover la torre de tamaño n-1 a la torre1
hanoi(n - 1, torre0, torre1, torre2)
# Mover el disco de torre0 a torre2
if torre0[0]:
# Sacar el ultimo número del arreglo y sustituirlo por un 0
disco = torre0[0].pop()
print ("Moviendo " + str(disco))
# Colocar un valor al "final" del arreglo
torre1[0].append(disco)
print (torre0[0], torre2[0], torre1[0])
# Mover la torre de tamaño n-1 de torre1 a torre2
hanoi(n - 1, torre2, torre0, torre1)
torre0 = ([4,3,2,1], "torre0")
torre1 = ([], "torre1")
torre2 = ([], "torre2")
hanoi(len(torre0[0]),torre0,torre2,torre1) |
fc600fe69a95b3129053f04ce7e3b72551d514c6 | jonathanbarrow/python_basics | /dict_accum1.py | 1,113 | 3.625 | 4 | d = {'vowels': 0, 'consonants': 0, 'nonalpha': 0, 'abcd_words': [], 'punct_words': []}
def breakout_1(some_str):
for char in some_str:
if char.lower() in ['a', 'e', 'i', 'o', 'u']:
d['vowels'] += 1
elif not char.isalpha():
d['nonalpha'] += 1
else:
d['consonants'] += 1
start_lst = []
punc_lst = []
for word in some_str.split():
if word[-1] in ['.', '?', '!']:
d['abcd_words'].append(word)
if word[0] in ['a', 'b', 'c', 'd']:
d['punct_words'].append(word)
return d
str1 = "Just a small-town girl Livin\' in a lonely world! She took the midnight train goin\' anywhere. Just a city boy Born and raised in South Detroit. He took the midnight train goin\' anywhere? A singer in a smoky room. The smell of wine and cheap perfume? For a smile they can share the night It goes on and on, and on, and on. Strangers waiting Up and down the boulevard. Their shadows searching in the night! Streetlights people Livin\' just to find emotion! Hidin\' somewhere in the night!"
print(breakout_1(str1)) |
85098267410dc7d297923ad15ca349de5de00327 | mhhuang95/LeetCode | /python/leetcode468.py | 1,153 | 3.5 | 4 | class Solution(object):
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
if '.' in IP and self.isvalidv4(IP):
return "IPv4"
if ':' in IP and self.isvalidv6(IP):
return "IPv6"
return "Neither"
def isvalidv4(self, IP):
ips = IP.split('.')
if len(ips) !=4:
return False
for x in ips:
if len(x) == 0:
return False
if len(x) != 1 and x[0] == '0':
return False
for i in x:
if i not in ['0','1','2','3','4','5','6','7','8','9']:
return False
if int(x)>255:
return False
return True
def isvalidv6(self, IP):
ips = IP.split(':')
if len(ips) != 8:
return False
for x in ips:
x = x.lower()
if len(x) == 0 or len(x) >4:
return False
for i in x:
if i not in ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']:
return False
return True |
ed8e41739f0b8aed39f1b050342f530bdb6efc14 | LoveDT/leetcode | /236 Lowest Common Ancestor of a Binary Tree/nonrec.py | 1,115 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
pathp,pathq = self.findpath(root,p),self.findpath(root,q)
length = min(len(pathp),len(pathq))
result,x = None,0
while x<length and pathp[x]==pathq[x]:
result,x = pathp[x],x+1
return result
def findpath(self,root,target):
path = []
lastvisited = None
while path or root:
if root:
path.append(root)
root = root.left
else:
top = path[-1]
if top.right and lastvisited!=top.right:
root = top.right
else:
if top is target:
return path
lastvisited = path.pop()
root = None
return path
|
42bddc090d1afe6123c7282191dd37ecc1fb4462 | qinliu1023/practices | /658. Find K Closest Elements.py | 2,334 | 3.9375 | 4 | """
Given a sorted array, two integers k and x, find the k closest elements to x in the array. The
result should also be sorted in ascending order. If there is a tie, the smaller elements are
always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]
Note:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 10**4
Absolute value of elements in the array and x will not exceed 10**4
UPDATE (2017/9/19):
The arr parameter had been changed to an array of integers (instead of a list of integers).
Please reload the code definition to get the latest changes.
"""
class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
distance = {}
for num in arr:
distance[num] = abs(num-x)
# sort dictionary by its values and then by its keys
# https://stackoverflow.com/questions/7742752/sorting-a-dictionary-by-value-then-by-key
# distance_sorted is a list
distance_sorted = sorted(distance.items(), key=lambda x: (x[1],x[0]))
output = []
for pair in distance_sorted[:k]:
output.append(pair[0])
return sorted(output)
"""
Above function fails when there are duplicate nums in arr, as python dictionary doesn't support duplicate keys
Wrong Answer: Last executed input: [0,1,1,1,2,3,6,7,8,9], 9, 4
# https://stackoverflow.com/questions/10664856/make-dictionary-with-duplicate-keys-in-python
# http://docs.python.org/library/collections.html#collections.defaultdict
"""
class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
import collections
distance = collections.defaultdict(list)
for num in arr:
distance[abs(num-x)].append(num)
distance_sorted_keys = sorted(distance.keys())
output = []
for i in distance_sorted_keys:
output.extend(distance[i])
return sorted(output[:k])
|
865a787af5bd44e005284b50be5ecc1e8a194619 | katebee/Battleships | /battleships.py | 2,158 | 3.890625 | 4 | __author__ = 'Admin'
import config
import players
class Game(object):
def __init__(self, ocean_size, fleet_size, max_turns):
self.ocean_size = ocean_size
self.fleet_size = fleet_size
self.max_turns = max_turns
def declare_ocean_size(self):
print "The ocean is a {0} by {0} grid".format(self.ocean_size)
@staticmethod
def declare_active_ships(player):
if player.active_ships > 1:
print "%d enemy ships detected! \n" % player.active_ships
else:
print "%d enemy ship detected! \n" % player.active_ships
def run_game(player_1, player_2):
while not check_game_over(player_1, player_2):
for turn in range(1, config.max_turns + 1):
print "TURN", turn
current_turn(player=player_1, opponent=player_2)
current_turn(player=player_2, opponent=player_1)
break
def current_turn(player, opponent):
opponent.visible_board.print_board()
player.attack(opponent)
if all_ships_destroyed(opponent):
declare_winner(player)
def check_game_over(*players):
for player in players:
if all_ships_destroyed(player):
return True
return False
def all_ships_destroyed(player):
if player.active_ships == 0:
return True
return False
def declare_winner(player):
print "That was the last battleship..."
print player.name.upper() + " WINS!"
quit()
# ############ GAME START #######################################
if __name__ == "__main__":
# create a new game
game = Game(ocean_size=config.ocean_size, fleet_size=config.fleet_size, max_turns=config.max_turns)
# initialise players
player_1 = players.HumanPlayer("HUMAN")
player_2 = players.ComputerPlayer("COMPUTER")
player_1.check_player_name()
# start game - position ships and declare ocean and fleet size
game.declare_ocean_size()
player_1.private_board.print_board()
player_1.position_fleet(config.fleet_size)
player_2.position_fleet(config.fleet_size)
game.declare_active_ships(player_2)
run_game(player_1, player_2) |
2685bb61c7438ca2e7ef7d7e827173d87e5e8b4e | Mark-Seaman/UNC-CS350-2017 | /Exercises/Results/adam5491/Development_Exercise/file_text.py | 706 | 3.84375 | 4 | # file_text.py
# Read the text from a file
def read_file(filepath):
with open(filepath) as f:
return f.read()[:-1]
# Write the text string to a file
def write_file(filepath, text):
with open(filepath, 'w') as f:
f.write(text+"\n")
# Test that the file reads and writes the same data
def test_file():
text = "Meow cats"
path = 'test.txt'
write_file(path, text)
t = read_file(path)
print('text:'+text+'$')
print('t:'+t+'$')
assert(t==text)
text = "Bark dogs"
write_file(path, text)
print('text:'+text+'$')
print('t:'+t+'$')
assert(t!=text)
# Second assertion now passes
# Run test
if __name__ == '__main__' :
test_file()
|
aae9ab50c28faf153738109b5a7093e0c04f3244 | anhle730s/python | /le_kieu_anh-12MMC-1813020005/BT2.py | 581 | 3.890625 | 4 | #đề 2:
#bài 2: Viết hàm với tham số truyền vào là một tháng và trả về mùa tương ứng trong năm. Sử dụng hàm vừa cài đặt, nhập vào một tháng và in ra màn hình mùa trong năm
def mua(n):
if ( n == 1 or n <= 3):
return("Xuân")
elif (n == 4 or n <= 6):
return("Hạ")
elif ( n == 7 or n <= 9):
return("Thu")
elif ( n == 10 or n <=12):
return("Đông")
else:
return("nhập sai tháng")
if __name__ == "__main__":
n=int(input("nhap n= "))
print(mua(n)) |
c2eca8500c373aabd1cb1f777947d8c3f5c4ee5c | Marlenqyzy/PP2 | /week1/w3school/64.py | 422 | 3.734375 | 4 | '''thisset = {"apple", "banana", "cherry"}
print(thisset)
thisset = {"apple", "banana", "cherry", "apple"} #duplicate will be ignored
print(thisset)
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
myset = {"apple", "banana", "cherry"}
print(type(myset)
'''
thisset = set(("apple", "banana", "cherry"))
print(thisset) |
f9207cb3bea0621b4e34853f044f10f44341b2c9 | jcafiero/Courses | /CS115/Homework/hw10.py | 585 | 3.75 | 4 | #Stephanie Green
#12/5/14
#Homework 10
def isnode(node):
if type(node) == type(()) and len(node) == 3:
return True
return False
def sumTree(tree):
if type(tree) != type(()):
return 0
elif isnode(tree) and type(tree[0]) == type(0):
return tree[0] + sumTree(tree[1]) + sumTree(tree[2])
elif isnode(tree):
return sumTree(tree[1]) + sumTree(tree[2])
return 0
def mirrorTree(tree):
if isnode(tree) and len(tree) == 3:
return (tree[0], mirrorTree(tree[2]), mirrorTree(tree[1]))
else:
return ()
|
4f4b164de2a437c2543039b07e7aafb16152c40a | Mounicask/Leetcode-problems | /THE MINION CHALLENGE.py | 371 | 3.5 | 4 | name='BANANA'
lis=['A','E','I','O','U']
list1=[]
length=len(name)
vowcount,conscount=0,0
for i in range(0,length):
if(name[i] in lis):
vowcount=vowcount+(length-i)
else:
conscount=conscount+(length-i)
if(vowcount>conscount):
print("kevin",vowcount)
elif(vowcount==conscount):
print("Draw")
else:
print("Stuart",conscount) |
a84fddce12998dee4e64c60cb861e13e0605b252 | odavidsonteixeira/RPG-python | /rpg_2v.py | 35,804 | 3.703125 | 4 | from random import randint
# Mago
vida_max_mago = randint(10, 20)
mana_max = randint(5, 10)
vida_max_guerreiro = randint(15, 25)
est_max = randint(5, 15)
# Monstro
vida_max_monstro = 20
nome = input('Qual é o nome do seu aventureiro?'
'\n---> ')
print('Wow! Que belo nome')
print('=-' * 40)
classe = input(f'Agora escolha uma classe\n'
f'Opções:'
f'\n1-Mago'
f'\n2-Guerreiro'
f'\n---> ').lower()
print('=-' * 40)
if classe == 'mago' or classe == '1':
print(f'Você escolheu a classe mago, você possui {vida_max_mago} de vida e '
f'\n{mana_max} de mana')
if classe == 'guerreiro' or classe == '2':
print(f'Você escolheu a classe guerreiro, você possui {vida_max_guerreiro} de vida e '
f'\n{est_max} de estamina')
print(f'Olá {nome}, blá blá blá historinha desnecessária....')
if classe == 'mago' or classe == '1':
num_monstro = 1
num_chefao = 1
chefao = 11
atk_min = 0
atk_max = 5
atk_monstro = 2
while True:
mana = mana_max
vida = vida_max_mago
vida_monstro = vida_max_monstro
print(f'Wow, Acaba de aparecer um monstro!!!! (0 c 0)')
rd = 1
while vida_monstro > 0:
acao_monstro = randint(0, 2)
print('=-' * 40)
print(f'\n\n R O D A D A #{rd}\n')
print('=-' * 40)
print(f'\nStatus do Monstro:'
f'\nMonstro N°#{num_monstro} vida: [{vida_monstro}/{vida_max_monstro}] '
f'\nAtaque: [Defende um terço do dano recebido]')
print('=-' * 40)
action = input(f'{nome} [vida: {vida}/{vida_max_mago}]'
f'\nOpções de ações:'
f'\n1- Ataque'
f'\n2- Curar'
f'\n3- Defesa'
f'\n4- Descansar -----> ').lower() # .lower() => transforma o valor digitado em minúsculo
print('=-' * 40)
# Ataque do personagem e cura do monstro
if mana >= 2:
if action == 'ataque' or action == '1':
atk = 10 # randint(atk_min, atk_max)
mana -= 2
gelo = randint(1, 10)
if gelo == 10:
print('Wow!!! Voê congelou o monstro, deixando o sem reação'
'\npor 1 rodada!')
acao_monstro = 0
if acao_monstro == 2:
dfs_monstro = int(atk / 3)
print('O monstro defendeu o seu ataque')
print(f'Por isso você deu apenas {dfs_monstro} de dano no monstro!')
vida_monstro -= dfs_monstro
else:
print(f'Wow!!! Você acaba de dar {atk} de dano no monstro!!!')
vida_monstro -= atk
# if/else corrigindo o bug do monstro com vida negativa
if vida_monstro >= 1:
print(f'Deixando ele com {vida_monstro} de vida!!!'
f'\nPorém acabou gastando 2 de mana nesse'
f'\nataque, ficando com {mana} de mana')
else:
print('=-' * 40)
seg = input(f'Deseja continuar? (s/n)').lower()
if seg == 's' or seg == 'sim':
print(f'Você {nome}, esse(a) bravo(a) e destemido(a) mago(a) derrotou '
f'\no horrendo monstro e salvou as pessoas novamente! '
f'\nParabéns nobre mago(a), agora você pode '
f'\nseguir sua jornada!')
vida_max_mago += 5
atk_min += 5
atk_max += 5
vida_max_monstro += 10
atk_monstro += 3
num_monstro += 1
else:
print(f'Você {nome}, esse(a) bravo(a) e destemido(a) mago(a) derrotou '
f'\no horrendo monstro e salvou as pessoas novamente! '
f'\nParabéns nobre mago(a), nos vemos em breve!')
exit()
elif action != 'ataque' or action != '1' and acao_monstro == 2:
print('O monstro usou de defesa!')
else:
print(f'Putz!!! Você não possui mana suficiente,'
f'\ndescanse para recuperar mana')
# Cura do personagem
if mana >= 2:
if action == 'curar' or action == '2':
cura = randint((int(vida / 10)), (int(vida / 2.5)))
new_vida = vida + cura
mana -= 2
# if/else corrigindo o bug da vida excedendo 50 de HP
if new_vida > vida_max_mago:
cura = vida_max_mago - vida
new_vida_curada = vida + cura
print(f'Como?!??!?'
f'\nVocê acaba de recuperar {cura} de vida,'
f'\nantes você tinha {vida} de vida, mas agora acaba de ter {new_vida_curada}'
f'\nPorém acabou gastando 2 de mana nesse'
f'\nprocesso, ficando com {mana} de mana')
vida = vida_max_mago
else:
print(f'Como?!??!?'
f'\nVocê acaba de recuperar {cura} de vida,'
f'\nantes você tinha {vida} de vida, mas agora acaba de ter {new_vida}')
vida = new_vida
print(f'\nPorém acabou gastando 2 de mana nesse'
f'\nprocesso, ficando com {mana} de mana')
else:
print(f'Putz!!! Você não possui mana suficiente,'
f'\ndescanse para recuperar mana')
if action == 'descansar' or action == '4':
descansar = randint(1, 7)
new_mana = mana + descansar
if new_mana > mana_max:
descansar = mana_max - mana
new_mana = mana + descansar
print(f'Você olhou pro monstro e correu mata adentro'
f'\nNisso você resolve meditar e recupera '
f'\níncriveis {descansar} de mana,'
f'\ntotalizando {new_mana} de mana')
mana = new_mana
else:
print(f'Você olhou pro monstro e correu mata adentro'
f'\nNisso você resolve meditar e recupera '
f'\níncriveis {descansar} de mana,'
f'\ntotalizando {new_mana} de mana')
mana = new_mana
# Ataque do monstro e defesa do personagem
if acao_monstro == 1:
print('=-' * 40)
# A ação de defesa está aqui porque só é possível defender quando o monstro ataca
if mana >= 2:
if action == 'defesa' or action == '3':
defesa = int(atk_monstro / 2)
print('Nossa que defesa!!!')
print(f'Você sofreu apenas {defesa} de dano após essa defesa espetacular!')
vida -= defesa
mana -= 2
print(f'Porém você gastou 2 de mana nessa ação,'
f'\nficando com {mana} de mana')
else:
print(f'O monstro te deu {atk_monstro} de dano ')
vida -= atk_monstro
# Morte do personagem
if vida <= 0:
print('=-' * 40)
print("Infelizmente você morreu após essa árdua batalha!!!")
exit()
else:
print(f'Sua vida agora é {vida}')
else:
print(f'Putz!!! Você não possui mana suficiente,'
f'\ndescanse para recuperar mana')
print(f'O monstro te deu {atk_monstro} de dano ')
vida -= atk_monstro
# Morte do personagem
if vida <= 0:
print('=-' * 40)
print("Infelizmente você morreu após essa árdua batalha!!!")
exit()
else:
print(f'Sua vida agora é {vida}')
rd += 1
mana += 1
if mana < mana_max:
print(f'Você recuperou 1 de mana, totalizando {mana} de mana')
elif mana == mana_max:
mana = mana_max
print(f'Você possui {mana} de mana')
if num_monstro == chefao:
vida_max_chefao = vida_monstro * 3
vida_chefao = vida_max_chefao
atk_chefao = atk_monstro * 3
rd = 1
while vida_chefao > 0:
acao_chefao = randint(0, 2)
print('=-' * 40)
print(f'\n\n R O D A D A #{rd}\n')
print('=-' * 40)
print(f'\nStatus do Chefão:'
f'\nChefão N°#{num_chefao} vida: [{vida_chefao}/{vida_max_chefao}] '
f'\nAtaque: [Defende um terço do dano recebido]')
print('=-' * 40)
action = input(f'{nome} [vida: {vida}/{vida_max_mago}]'
f'\nOpções de ações:'
f'\n1- Ataque'
f'\n2- Curar'
f'\n3- Defesa'
f'\n4- Descansar -----> ').lower() # .lower() => transforma o valor digitado em minúsculo
print('=-' * 40)
# Ataque do personagem e cura do monstro
if mana >= 2:
if action == 'ataque' or action == '1':
atk = randint(atk_min, atk_max)
mana -= 2
gelo = randint(1, 10)
if gelo == 10:
print("Wow!!! Você congelou o chefão, deixando"
"\nele sem ação durante 1 rodada!")
acao_chefao = 0
if acao_chefao == 2:
dfs_chefao = int(atk / 3)
print('O chefão defendeu o seu ataque')
print(f'Por isso você deu apenas {dfs_chefao} de dano nele!')
vida_chefao -= dfs_chefao
else:
print(f'Wow!!! Você acaba de dar {atk} de dano no chefão!!!')
vida_chefao -= atk
# if/else corrigindo o bug do monstro com vida negativa
if vida_chefao >= 1:
print(f'Deixando ele com {vida_chefao} de vida!!!'
f'\nPorém acabou gastando 2 de mana nesse'
f'\nataque, ficando com {mana} de mana')
else:
print('=-' * 40)
seg = input(f'Deseja continuar? (s/n)').lower()
if seg == 's' or seg == 'sim':
print(f'Você {nome}, esse(a) bravo(a) e destemido(a) mago(a) derrotou '
f'\n o horrendo chefão e salvou as pessoas novamente! '
f'\nParabéns nobre mago(a), agora você pode '
f'\nseguir sua jornada!')
vida_max_mago += 5
atk_min += 5
atk_max += 5
vida_max_monstro += 10
atk_monstro += 3
num_monstro += 1
chefao += 10
num_chefao += 1
else:
print(f'Você {nome}, esse(a) bravo(a) e destemido(a) mago(a) derrotou '
f'\n o horrendo monstro e salvou as pessoas novamente! '
f'\nParabéns nobre mago(a), nos vemos em breve!')
exit()
elif action != 'ataque' or action != '1' and acao_chefao == 2:
print('O chefão usou de defesa!')
else:
print(f'Putz!!! Você não possui mana suficiente,'
f'\ndescanse para recuperar mana')
# Cura do personagem
if mana >= 2:
if action == 'curar' or action == '2':
cura = randint((int(vida / 10)), (int(vida / 2.5)))
new_vida = vida + cura
mana -= 2
# if/else corrigindo o bug da vida excedendo 50 de HP
if new_vida > vida_max_mago:
cura = vida_max_mago - vida
new_vida_curada = vida + cura
print(f'Como?!??!?'
f'\nVocê acaba de recuperar {cura} de vida,'
f'\nantes você tinha {vida} de vida, mas agora acaba de ter {new_vida_curada}'
f'\nPorém acabou gastando 2 de mana nesse'
f'\nprocesso, ficando com {mana} de mana')
vida = vida_max_mago
else:
print(f'Como?!??!?'
f'\nVocê acaba de recuperar {cura} de vida,'
f'\nantes você tinha {vida} de vida, mas agora acaba de ter {new_vida}'
f'\nPorém acabou gastando 2 de mana nesse'
f'\nprocesso, ficando com {mana} de mana')
vida = new_vida
else:
print(f'Putz!!! Você não possui mana suficiente,'
f'\ndescanse para recuperar mana')
if action == 'descansar' or action == '4':
descansar = randint(1, 7)
new_mana = mana + descansar
if new_mana > mana_max:
descansar = mana_max - mana
new_mana = mana + descansar
print(f'Você olhou pro chefão e correu mata adentro'
f'\nNisso você resolve meditar e recupera '
f'\níncriveis {descansar} de mana,'
f'\ntotalizando {new_mana} de mana')
else:
print(f'Você olhou pro chefao e correu mata adentro'
f'\nNisso você resolve meditar e recupera '
f'\níncriveis {descansar} de mana,'
f'\ntotalizando {new_mana} de mana')
# Ataque do monstro e defesa do personagem
if acao_chefao == 1:
print('=-' * 40)
# A ação de defesa está aqui porque só é possível defender quando o monstro ataca
if mana >= 2:
if action == 'defesa' or action == '3':
defesa = int(atk_chefao / 2)
mana -= 2
print('Nossa que defesa!!!')
print(f'Você sofreu apenas {defesa} de dano após essa defesa espetacular!'
f'\nPorém acabou gastando 2 de mana nesse'
f'\nprocesso, ficando com {mana} de mana')
vida -= defesa
else:
print(f'O monstro te deu {atk_chefao} de dano ')
vida -= atk_chefao
# Morte do personagem
if vida <= 0:
print('=-' * 40)
print("Infelizmente você morreu após essa árdua batalha!!!")
exit()
else:
print(f'Sua vida agora é {vida}')
else:
print(f'Putz!!! Você não possui mana suficiente,'
f'\ndescanse para recuperar mana')
print(f'O monstro te deu {atk_chefao} de dano ')
vida -= atk_chefao
# Morte do personagem
if vida <= 0:
print('=-' * 40)
print("Infelizmente você morreu após essa árdua batalha!!!")
exit()
else:
print(f'Sua vida agora é {vida}')
rd += 1
mana += 1
if mana < mana_max:
print(f'Você recuperou 1 de mana, totalizando {mana} de mana')
else:
mana = mana_max
print(f'Você possui {mana} de mana')
if classe == 'guerreiro' or classe == '2':
num_monstro = 1
num_chefao = 1
chefao = 11
atk_min = 0
atk_max = 5
atk_monstro = 2
while True:
estamina = est_max
vida = vida_max_guerreiro
vida_monstro = vida_max_monstro
print(f'Whow, Acaba de aparecer um monstro!!!! (0 c 0)')
rd = 1
while vida_monstro > 0:
acao_monstro = randint(0, 2)
print('=-' * 40)
print(f'\n\n R O D A D A #{rd}\n')
print('=-' * 40)
print(f'\nStatus do Monstro:'
f'\nMonstro N°#{num_monstro} vida: [{vida_monstro}/{vida_max_monstro}] '
f'\nAtaque: [Defende um terço do dano recebido]')
print('=-' * 40)
action = input(f'{nome} [vida: {vida}/{vida_max_guerreiro}]'
f'\nOpções de ações:'
f'\n1- Ataque'
f'\n2- Curar'
f'\n3- Defesa'
f'\n4- Descansar -----> ').lower() # .lower() => transforma o valor digitado em minúsculo
print('=-' * 40)
# Ataque do personagem e cura do monstro
if estamina >= 2:
if action == 'ataque' or action == '1':
atk = randint(atk_min, atk_max)
estamina -= 2
if acao_monstro == 2:
dfs_monstro = int(atk / 3)
print('O monstro defendeu o seu ataque')
print(f'Por isso você deu apenas {dfs_monstro} de dano no monstro!')
vida_monstro -= dfs_monstro
else:
print(f'Wow!!! Você acaba de dar {atk} de dano no monstro!!!')
vida_monstro -= atk
# if/else corrigindo o bug do monstro com vida negativa
if vida_monstro >= 1:
print(f'Deixando ele com {vida_monstro} de vida!!!'
f'\nPorém acabou gastando 2 de estamina nesse'
f'\nataque, ficando com {estamina} de mana')
else:
print('=-' * 40)
seg = input(f'Deseja continuar? (s/n)').lower()
if seg == 's' or seg == 'sim':
print(f'Você {nome}, esse(a) bravo(a) e destemido(a) guerreiro(a) derrotou '
f'\n o horrendo monstro e salvou as pessoas novamente! '
f'\nParabéns nobre guerreiro(a), agora você pode '
f'\nseguir sua jornada!')
vida_max_guerreiro += 5
atk_min += 5
atk_max += 5
vida_max_monstro += 10
atk_monstro += 3
num_monstro += 1
else:
print(f'Você {nome}, esse(a) bravo(a) e destemido(a) guerreiro(a) derrotou '
f'\n o horrendo monstro e salvou as pessoas novamente! '
f'\nParabéns nobre guerreiro(a), nos vemos em breve!')
exit()
elif action != 'ataque' or action != '1' and acao_monstro == 2:
print('O monstro usou de defesa!')
else:
print(f'Putz!!! Você não possui estamina suficiente,'
f'\ndescanse para recuperar estamina')
# Cura do personagem
if estamina >= 2:
if action == 'curar' or action == '2':
cura = randint(int(vida / 10), int(vida / 2.5))
new_vida = vida + cura
estamina -= 2
# if/else corrigindo o bug da vida excedendo 50 de HP
if new_vida > vida_max_guerreiro:
cura = vida_max_guerreiro - vida
new_vida_curada = vida + cura
print(f'Como?!??!?'
f'\nVocê acaba de recuperar {cura} de vida,'
f'\nantes você tinha {vida} de vida, mas agora acaba de ter {new_vida_curada}'
f'\nPorém acabou gastando 2 de estamina nesse'
f'\nprocesso, ficando com {estamina} de estamina')
vida = vida_max_guerreiro
else:
print(f'Como?!??!?'
f'\nVocê acaba de recuperar {cura} de vida,'
f'\nantes você tinha {vida} de vida, mas agora acaba de ter {new_vida}'
f'\nPorém acabou gastando 2 de estamina nesse'
f'\nprocesso, ficando com {estamina} de estamina')
vida = new_vida
else:
print(f'Putz!!! Você não possui estamina suficiente,'
f'\ndescanse para recuperar estamina')
if action == 'descansar' or action == '4':
descansar = randint(1, 7)
new_est = estamina + descansar
if new_est > mana_max:
descansar = est_max - estamina
new_est = estamina + descansar
print(f'Você olhou pro monstro e correu mata adentro'
f'\nNisso você resolve descansar e recupera '
f'\níncriveis {descansar} de estamina,'
f'\ntotalizando {new_est} de estamina')
else:
print(f'Você olhou pro monstro e correu mata adentro'
f'\nNisso você resolve meditar e recupera '
f'\níncriveis {descansar} de estamina,'
f'\ntotalizando {new_est} de estamina')
# Ataque do monstro e defesa do personagem
if acao_monstro == 1:
print('=-' * 40)
# A ação de defesa está aqui porque só é possível defender quando o monstro ataca
if estamina >= 2:
if action == 'defesa' or action == '3':
estamina -= 2
defesa = int(atk_monstro / 2)
print('Nossa que defesa!!!')
print(f'Você sofreu apenas {defesa} de dano após essa defesa espetacular!'
f'Porém acabou gastando 2 de estamina nessa ação,'
f'\nficando com {estamina} de estamina')
vida -= defesa
else:
print(f'O monstro te deu {atk_monstro} de dano ')
vida -= atk_monstro
# Morte do personagem
if vida <= 0:
print('=-' * 40)
print("Infelizmente você morreu após essa árdua batalha!!!")
exit()
else:
print(f'Sua vida agora é {vida}')
else:
print(f'Putz!!! Você não possui estamina suficiente,'
f'\ndescanse para recuperar estamina')
print(f'O monstro te deu {atk_monstro} de dano ')
vida -= atk_monstro
# Morte do personagem
if vida <= 0:
print('=-' * 40)
print("Infelizmente você morreu após essa árdua batalha!!!")
exit()
else:
print(f'Sua vida agora é {vida}')
rd += 1
estamina += 1
if estamina < est_max:
print(f'Você recuperou 1 de estamina, totalizando {estamina} de estamina')
else:
estamina = est_max
print(f'Você possui {estamina} de estamina')
if num_monstro == chefao:
vida_max_chefao = vida_monstro * 3
vida_chefao = vida_max_chefao
atk_chefao = atk_monstro * 3
rd = 1
while vida_chefao > 0:
acao_chefao = randint(1, 2)
print('=-' * 40)
print(f'\n\n R O D A D A #{rd}\n')
print('=-' * 40)
print(f'\nStatus do Chefão:'
f'\nChefão N°#{num_chefao} vida: [{vida_chefao}/{vida_max_chefao}] '
f'\nAtaque: [Defende um terço do dano recebido]')
print('=-' * 40)
action = input(f'{nome} [vida: {vida}/{vida_max_guerreiro}]'
f'\nOpções de ações:'
f'\n1- Ataque'
f'\n2- Curar'
f'\n3- Defesa'
f'\n4- Descansar -----> ').lower() # .lower() => transforma o valor digitado em minúsculo
print('=-' * 40)
# Ataque do personagem e cura do monstro
if estamina >= 2:
if action == 'ataque' or action == '1':
atk = randint(atk_min, atk_max)
estamina -= 2
if acao_chefao == 2:
dfs_chefao = int(atk / 3)
print('O chefão defendeu o seu ataque')
print(f'Por isso você deu apenas {dfs_chefao} de dano nele!')
vida_chefao -= dfs_chefao
else:
print(f'Wow!!! Você acaba de dar {atk} de dano no chefão!!!')
vida_chefao -= atk
# if/else corrigindo o bug do monstro com vida negativa
if vida_chefao >= 1:
print(f'Deixando ele com {vida_chefao} de vida!!!'
f'\nPorém acabou gastando 2 de estamina nesse'
f'\nataque, ficando com {estamina} de estamina')
else:
print('=-' * 40)
seg = input(f'Deseja continuar? (s/n)').lower()
if seg == 's' or seg == 'sim':
print(f'Você {nome}, esse(a) bravo(a) e destemido(a) guerreiro(a) derrotou '
f'\n o horrendo chefão e salvou as pessoas novamente! '
f'\nParabéns nobre guerreiro(a), agora você pode '
f'\nseguir sua jornada!')
vida_max_guerreiro += 5
atk_min += 5
atk_max += 5
vida_max_monstro += 10
atk_monstro += 3
num_monstro += 1
chefao += 10
num_chefao += 1
else:
print(f'Você {nome}, esse(a) bravo(a) e destemido(a) guerreiro(a) derrotou '
f'\n o horrendo monstro e salvou as pessoas novamente! '
f'\nParabéns nobre guerreiro(a), nos vemos em breve!')
exit()
elif action != 'ataque' or action != '1' and acao_chefao == 2:
print('O chefão usou de defesa!')
else:
print(f'Putz!!! Você não possui estamina suficiente,'
f'\ndescanse para recuperar estamina')
# Cura do personagem
if estamina >= 2:
if action == 'curar' or action == '2':
cura = randint(int(vida / 10), int(vida / 2.5))
new_vida = vida + cura
estamina -= 2
# if/else corrigindo o bug da vida excedendo 50 de HP
if new_vida > vida_max_guerreiro:
cura = vida_max_guerreiro - vida
new_vida_curada = vida + cura
print(f'Como?!??!?'
f'\nVocê acaba de recuperar {cura} de vida,'
f'\nantes você tinha {vida} de vida, mas agora acaba de ter {new_vida_curada}'
f'\nPorém acabou gastando 2 de estamina nesse'
f'\nprocesso, ficando com {estamina} de estamina')
vida = vida_max_guerreiro
else:
print(f'Como?!??!?'
f'\nVocê acaba de recuperar {cura} de vida,'
f'\nantes você tinha {vida} de vida, mas agora acaba de ter {new_vida}'
f'\nPorém acabou gastando 2 de estamina nesse'
f'\nprocesso, ficando com {estamina} de estamina')
vida = new_vida
else:
print(f'Putz!!! Você não possui estamina suficiente,'
f'\ndescanse para recuperar estamina')
if action == 'descansar' or action == '4':
descansar = randint(1, 7)
new_est = estamina + descansar
if new_est > est_max:
descansar = est_max - estamina
new_mana = estamina + descansar
print(f'Você olhou pro chefão e correu mata adentro'
f'\nNisso você resolve meditar e recupera '
f'\níncriveis {descansar} de estamina,'
f'\ntotalizando {new_est} de estamina')
else:
print(f'Você olhou pro chefao e correu mata adentro'
f'\nNisso você resolve meditar e recupera '
f'\níncriveis {descansar} de estamina,'
f'\ntotalizando {new_est} de estamina')
# Ataque do monstro e defesa do personagem
if acao_chefao == 1:
print('=-' * 40)
# A ação de defesa está aqui porque só é possível defender quando o monstro ataca
if estamina >= 2:
if action == 'defesa' or action == '3':
estamina -= 2
defesa = int(atk_chefao / 2)
print('Nossa que defesa!!!')
print(f'Você sofreu apenas {defesa} de dano após essa defesa espetacular!'
f'\nPorém você acabou gastando 2 de estamina nessa ação,'
f'\nficando com {estamina} de estamina')
vida -= defesa
else:
print(f'O monstro te deu {atk_chefao} de dano ')
vida -= atk_chefao
# Morte do personagem
if vida <= 0:
print('=-' * 40)
print("Infelizmente você morreu após essa árdua batalha!!!")
exit()
else:
print(f'Sua vida agora é {vida}')
else:
print(f'Putz!!! Você não possui estamina suficiente,'
f'\ndescanse para recuperar estamina')
print(f'O monstro te deu {atk_chefao} de dano ')
vida -= atk_chefao
# Morte do personagem
if vida <= 0:
print('=-' * 40)
print("Infelizmente você morreu após essa árdua batalha!!!")
exit()
else:
print(f'Sua vida agora é {vida}')
rd += 1
estamina += 1
if estamina < est_max:
print(f'Você recuperou 1 de mana, totalizando {estamina} de estamina')
else:
estamina = est_max
print(f'Você possui {estamina} de estamina')
|
0e85111c4deaa6923b8b28d7367d5c4b826f8a88 | SKosztolanyi/Python-exercises | /75_Creating set class object and methods.py | 2,180 | 4.125 | 4 | class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
if not e in self.vals:
self.vals.append(e)
def member(self, e):
"""Assumes e is an integer
Returns True if e is in self, and False otherwise"""
return e in self.vals
def remove(self, e):
"""Assumes e is an integer and removes e from self
Raises ValueError if e is not in self"""
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
return '{' + ','.join([str(e) for e in self.vals]) + '}'
## In defining this method I rely heavily on previous definitions of methods
## I will be creating an empty list using intSet in the __init__ definition.
## I will need to use .member method to compare if the element is in both lists
## I will be using .insert method, to add (not .append directly) a common element to a new list.
def intersect(self, other):
'''
A method that returns a new intSet containing elements that appear in both sets.
'''
intersect_values = intSet()
for ele in self.vals:
if other.member(ele):
intersect_values.insert(ele)
return intersect_values
## I want to return lenght of a set, so i define the method as __len__
## It cannot have different name, because I need it to be XY.len() method.
def __len__(self):
''' This simple method returns lenght of the set'''
return len(self.vals)
# Test examples from grader:
setA = {-17,-16,-15,-11,-3,8,13}
setB = {-19,-16,-9,-7,-3,-1,7,15,18}
setA.intersect(setB)
setC = {-19,-17,-16,-8,0,7,17,19}
setD = {-20,-18,-14,-3,-2,11,14}
setC.intersect(setD)
print len(setA) |
164bc45622ecde62979494d8cc49c702dc9fbf34 | fariharajput/Python_3 | /week4/lab9-Mar4/q2.py | 1,649 | 4.34375 | 4 | # Question 2: Let’s sort the array using Merge Sort
# Let’s suppose we have a list
# list1= [1,5,67,2,43,6,4,2,2,4,6,2,1,68,5,4 ]
# Write a function that
# takes list1 an input
# Sort all elements in the list in an ascending order
# Returns the sorted list
# Hint: Check this video to learn more about merge sort: https://www.youtube.com/watch?v=JSceec-wEyw&ab_channel=GeeksforGeeks
# Note: You are not allowed to use the list build-in function .sort()
# Deliverables:
# Pseudo-code
# Code
##############################################################################################
# Pseudo-code
# divide the list into two parts
# divide each part of the list into two parts
# divide every child part until > 1
# sort last two elements
# then join two parts and sort
# and so on
# Code
def merge(left, right):
leftIndex, rightIndex = 0, 0
list1 = []
while leftIndex < len(left) and rightIndex < len(right):
if left[leftIndex] < right[rightIndex]:
list1.append(left[leftIndex])
leftIndex += 1
else:
list1.append(right[rightIndex])
rightIndex += 1
list1 += left[leftIndex:]
list1 += right[rightIndex:]
return list1
def mergeSort(list1):
if len(list1) <= 1:
return list1
# divide array in half and merge sort recursively
half = len(list1) // 2
left = mergeSort(list1[:half])
right = mergeSort(list1[half:])
return merge(left, right)
# main program
list1 = [1, 5, 67, 2, 43, 6, 4, 2, 2, 4, 6, 2, 1, 68, 5, 4]
print('unsorted list is {0}'.format(list1))
print(' sorted list is {0}'.format(mergeSort(list1)))
|
adf6e27d163e0ccbeb1215da6418a1492a61fa82 | SteveLyu07/DA202010 | /poc_pandas/try0_excel.py | 1,358 | 3.578125 | 4 | # -*- coding: UTF-8 -*-
# ------------------------(max to 80 columns)----------------------------------
# author by : (学员ID)
# created: 2020.9
# Description:
# pandas 技术验证用
# 各类基本技巧的练习
# 注:需安裝 pip install xlrd
# ------------------------(max to 80 columns)----------------------------------
import os
import pandas as pd
# path = os.path.realpath(os.curdir) # 获取当前目录的绝对路径
print("\n---try(2)---")
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
excelpath = path + "/poc_pandas/data/DataOfExcel.xlsx" # 加上文件名
print('reading excle file from:', excelpath)
#try(1) 读取excel的第一张表单
df = pd.read_excel(excelpath)
print(df)
#try(2) 读取excel的指定表单
print("\n---try(2)(1)---")
df = pd.read_excel(excelpath,sheet_name='ShuHu108People')
print(df)
print("\n---try(2)(2)---")
df = pd.read_excel(excelpath,sheet_name=[0,1])
print(df)
#try(3)
print("\n---try(3)---")
df = pd.read_excel(excelpath,sheet_name=['Students'],usecols=[2,3],skiprows=[0])
print(df)
#try(4)
print("\n---try(4)---")
df = pd.read_excel(excelpath,sheet_name=['Students'],usecols=[2,3],skiprows=[0])
print(df)
'''
OrderedDict(
[('Students',xxxxx)]
)'''
print("\n***changed dataframe***")
df2 = pd.DataFrame(df['Students'])
print(df2)
#纯粹的dataframe
|
8a1dfd3742cfdb2dd46665bc208547126ff20b61 | dws940819/DataStructures | /DS3_BaseStructures/lesson3_queue.py | 6,359 | 4.3125 | 4 | '''
队列:是一系列有顺序的元素集合,新元素加入在队列的一端,这一端叫做“队尾”
已有元素的移出发生在队列的另一端,叫做“对首(front)”,当一个元素被加入到队列之后,它就从队尾向对首前进,直到它成为下一个即将被移出队列的元素
先进先出(FIFO):最新被加入的元素处于队尾,在队列中停留最长时间的元素处于队首
抽象数据类型(ADT):
Queue()创建一个空队列对象,无需参数,返回空的队列
enqueue(item) 将数据项添加到队尾,无返回值
dequeue() 从队首移出数据项,无需参数,返回值为队首数据项
isEmpty() 是否队列为空,无需参数,返回值为布尔值
size() 返回队列中的数据项的个数,无需参数
用python list实现队列
队尾在列表的位置
enqueue insert() O(n)
dequeue pop() O(1)
'''
# class Queue():
# def __init__(self):
# self.items = []
# def enqueue(self,item):
# self.items.insert(0,item)
# def dequeue(self):
# return self.items.pop()
# def isEmpty(self):
# return self.items == []
# def size(self):
# return len(self.items)
# q = Queue()
# q.enqueue(6)
# q.enqueue('cat')
# q.enqueue(False)
# print(q.size())
# print(q.isEmpty())
# q.dequeue()
'''
马铃薯游戏(击鼓传花)选定一个人作为开始的人,数到num个人,将此人淘汰
'''
# from pythonds.basic.queue import Queue
# name_list = ['嬴政','刘邦','项羽','刘备','刘彻','李世民','赵匡胤','朱元璋','朱棣','乾隆']
# num = 4
# def send_flower(name_list,num):
# q = Queue()
# for name in name_list:
# q.enqueue(name)
# while q.size() > 1:
# for i in range(num):
# q.enqueue(q.dequeue())
# n = q.dequeue()
# print(n)
# return q.dequeue()
# print(send_flower(name_list,num))
'''
模拟打印机
平均每天任意一个小时有大约10个学生在实验室里,在这一小时中通常每人发起2次打印任务,每个打印任务的页数从1到20页不等,实验室中的打印机老旧,如果以草稿模式打印,每分钟可以打印10页;打印机可以转换完成高品质的打印模式,但每分钟只能打印5页,较慢的打印速度可能会使学生等待太长的时间,应该采用哪种打印模式?
学生 (等待时间 + 打印时间)
打印任务 (打印任务队列)
打印机(状态:打印中,空闲)
1-20 不等,随机数模拟
总共10*2 = 20次打印任务,平均每3分钟产生一个打印任务
在3分钟内的任意一秒产生一个打印任务的概率是:task/180,随机数模拟,如果生成的随机数是180,就可以认为生成了一个任务。
过程:
1.创建一个打印任务队列,每个任务在生成时被赋予一个“时间戳”
2.一个小时中的每一秒(currentSecond)都需要判断:
是否有新的打印任务生成,如果有,把它加入打印队列;
如果打印机空闲并且队列不为空:
1.从队列中拿出一个任务交给打印机
2.从加入打印机时间 - 加入队列的时间 = 等待时间
3.将改任务的等待时间加入到一个列表中,方便后续时候,计算总的学生打印花费的时间
4.基于打印的页数的随机数,求出需要多长时间打印
3.打印机工作中,那对于打印机而言,就是工作了一秒:对于打印任务而言,它离打印结束又近了一秒
4.打印任务完成,剩余时间为0,打印机进入空闲状态
Python实现:
1.三个对象:打印机(Printer)打印任务(Task) 打印队列(PrintQueue)
2.Printer需要实时监测是否正在执行打印任务,判断自己处于空闲还是打印中的状态,设置是打印草稿还是打印高品质的,如果打印中,需要结合随机的打印页数,计算打印的时间,打印结束后,需要将打印状态设置为空闲
'''
import random
import pythonds.basic.queue import Queue
class Printer:
def __init__(self,ppm):
# 设置是打印的速率
self.pagerate = ppm
self.currentTask = None
# 打印机当前任务的剩余时间
self.timeRemaining = 0
# 内部任务需要的时间计算函数
def tick(self):
if self.currentTask != None:
self.timeRemaining = self.timeRemaining - 1
if self.timeRemaining <= 0:
slef.currentTask = None
# 切换打印机状态
def is_busy(self):
if self.currentTask != None:
return True
else:
return False
def startNew(self,newTask):
self.currentTask = newTask
self.timeRemaining = newTask.getPages()*60/self.pagerate
class Task:
def __init__(self,time):
self.timestamp = time
self.pages = random.randrange(1,21)
def getStamp(self):
return self.timestamp
def getPages(self):
return self.pages
def waitTime(self,currenttime):
return currenttime - self.timestamp
def main(numSeconds,pagesPerMinute):
labPrinter = Printer(pagesPerMinute)
printQueue = Queue()
watingtimes = []
for currentSecond in range(numSeconds):
if newPrintTask():
task = Task(currentSecond)
printQueue.enqueue(task)
if(not labPrinter.is_busy()) and (not printQueue.isEmpty()):
nexttask = printQueue.dequeue()
watingtimes.append(nexttask.waitTime(currentSecond))
labPrinter.startNew(nexttask)
labPrinter.tick()
averageWait = sum(watingtimes) / len(watingtimes)
print('平均等待%6.2f秒 还剩%3d任务'%(averageWait,printQueue.size()))
def newPrintTask():
num = random.randrange(1,181)
if num == 180:
return True
else:
return False
for i in range(10):
simulation(3600,5)
'''
1.学生数变为20
2.不局限在一个小时内的话,这些学生都打印完需要多长时间
'''
|
e38fd352597542627a4429dfe445f0af714d988a | mathtkang/Data-Structure | /3-5.트리의 너비.py | 2,216 | 3.625 | 4 | # class Tree:
# def __init__(self, i, l, r) :
# self.index = i
# self.left = l
# self.right = r
# self.depth = -1
# def setDepth(self, d) :
# self.depth = d
# def addNode(self, i, l, r) :
# if self.index == None or self.index == i :
# self.index = i
# self.left = Tree(l, None, None) if l != None else None
# self.right = Tree(r, None, None) if r != None else None
# return True
# else :
# flag = False
# if self.left != None :
# flag = self.left.addNode(i, l, r)
# if flag == False and self.right != None :
# flag = self.right.addNode(i, l, r)
# return flag
def inorder(tree, depth):
result = []
if tree.left != None:
result += inorder(tree.left, depth + 1)
tree.setDepth(depth) # 재귀 : 루트노드로부터 거리가 1 멀어짐
result.append(tree)
if tree.right != None:
result += inorder(tree.right, depth + 1)
return result
def getWidth(myTree):
'''
myTree의 너비가 가장 넓은 레벨과 그 레벨의 너비를 반환하는 함수를 작성하세요.
가장 넓은 레벨 l과 그 레벨의 너비 w를 튜플로 반환해야 합니다.
반환값 형식 : (l, w)
'''
result = inorder(myTree, 1)
n = len(result)
# 정점의 개수는 1000개 이하이다. (입력조건)
# 깊이의 최댓값은 1000
# left[i] = 깊이가 i인 모든 노드들 중에서, 가장 왼쪽에 있는 노드의 행
# right[i] = 깊이가 i인 모든 노드들 중에서, 가장 오른쪽에 있는 노드의 행
# 어떤 깊이의 너비는 right[i] - left[i]
left = [1001 for i in range(1001)]
right = [-1 for i in range(1001)]
maxDepth = 0
for i in range(n):
d = result[i].depth
left[d] = min(left[d], i)
right[d] = max(right[d], i)
maxDepth = max(maxDepth, d)
ansDepth = 0
ans = 0
for i in range(1, maxDepth+1):
temp = right[i] - left[i] + 1
if ans < temp:
ansDepth = i
ans = temp
return (ansDepth, ans)
|
abd1db19c2fafe343d2e2a17a07bd72b9250a5df | ahmedyoko/python-course-Elzero | /lists13.py | 1,676 | 4.6875 | 5 | #------------------------
#lists :
#.........
#1- items enclosed in square brackets []
#2- ordered item and accessed by index
#3- mutable => Add , delete , Edit
#4- list items : are not unique
#5-list can have different data type
#------------------------
MyAwesomelist = ['one','two','one',1,2.5,True]
print(MyAwesomelist)
# index : output in the form of string or the type of element
print(MyAwesomelist[1])
print(MyAwesomelist[-1])
print(MyAwesomelist[-3])
print(MyAwesomelist[-2])
print(type(MyAwesomelist[-3]))
print('#'*50)
print(MyAwesomelist)
#for slice : output in the form of list
print(MyAwesomelist[1:4]) #['two', 'one', 1]
print(MyAwesomelist[:4])#['one', 'two', 'one', 1]
print(MyAwesomelist[1:]) #['two', 'one', 1, 2.5, True]
#using steps of slice: [start: end: step]
print('steps')
print(MyAwesomelist[::1]) #the whole list
print(MyAwesomelist[::2])
# out of range error: when you write index does not exist
# print(MyAwesomelist[130])
print("out of range error")
print('#'*50)
print("modify the list")
#modify of elements in the list
#............................
#1-modify one element in the list
print(MyAwesomelist) #['one', 'two', 'one', 1, 2.5, True]
MyAwesomelist[1] = 2
print(MyAwesomelist[1]) #2
print(MyAwesomelist) # ['one', 2, 'one', 1, 2.5, True]
#2-modify more than one element in the list
MyAwesomelist = ['one','two','one',1,2.5,True]
MyAwesomelist[0:2] = [] # remove this elements => ['one', 1, 2.5, True]
print(MyAwesomelist)
MyAwesomelist = ['one','two','one',1,2.5,True]
MyAwesomelist[0:3] = ['A','B','C']
print(MyAwesomelist)
MyAwesomelist[0:3] = ['A'] #replace 3 elements by one element
print(MyAwesomelist) # ['A', 1, 2.5, True]
|
2ae1a67c64d41e9fac44778570d8ef9e659eb48a | cybelewang/leetcode-python | /code693BinaryNumberWithAlternatingBits.py | 1,085 | 4.125 | 4 | """
693 Binary Number with Alternating Bits
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
"""
class Solution:
# another solution from OJ
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
num = n ^ (n >> 1)
return not (num & (num + 1))
# my own solution
def hasAlternatingBits2(self, n):
"""
:type n: int
:rtype: bool
"""
s = bin(n)
return s.count('00') == 0 and s.count('11') == 0
test_cases = [5, 7, 11, 10]
for n in test_cases:
print(Solution().hasAlternatingBits(n)) |
8aea11062ed72fde49628d38304510902cce8416 | Naydell/Python | /ex009.py | 435 | 3.984375 | 4 | n = int(input('Digite um número: '))
n1 = n * 1
n2 = n * 2
n3 = n * 3
n4 = n * 4
n5 = n * 5
n6 = n * 6
n7 = n * 7
n8 = n * 8
n9 = n * 9
print('8 x 1 = {}'.format(n1))
print('8 x 2 = {}'.format(n2))
print('8 x 3 = {}'.format(n3))
print('8 x 4 = {}'.format(n4))
print('8 x 5 = {}'.format(n5))
print('8 x 6 = {}'.format(n6))
print('8 x 7 = {}'.format(n7))
print('8 x 8 = {}'.format(n8))
print('8 x 9 = {}'.format(n9))
|
3d56ae4a1b0a5c2c77c9faae057b867d99245c98 | ssthouse/PythonCookBook | /test_generator/test_generator.py | 211 | 3.640625 | 4 | # coding=utf-8
def generate_three_num():
for i in range(5):
print("yield %d" % i)
yield i
def test_use_generator():
for i in generate_three_num():
i += 1
test_use_generator()
|
2f1c03f29f8931681fb8e9fce3b3c0748143e7fb | TanyaGerenko/T.Gerenko | /Ex26.py | 1,045 | 3.84375 | 4 | #Написать функцию для перевода десятичного числа в другую систему исчисления (2-36). В качестве параметров, функция получает десятичное число и систему счисления.
#Возвращает строку - результат перевода десятичного числа.
def ConvertNumber(n,base):
D=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
MyStack=[]
MyNumber=[]
while n>0:
MyStack.append(n%base)
n=n//base
print(MyStack)
while len(MyStack)>0:
x=MyStack.pop()
if x>10:
MyNumber.append(D[x-1])
else:
MyNumber.append(x)
print(MyNumber)
str1 = ''.join(str(e) for e in MyNumber)
return str1
n=int(input("n="))
base=int(input("base="))
print(ConvertNumber(n,base))
|
ced33841455ddae4f53b6596aa3236b998a2216c | AdamZhouSE/pythonHomework | /Code/CodeRecords/2484/60793/269297.py | 229 | 3.703125 | 4 | for test in range(0, int(input())):
input()
ls1 = list(map(int, input().split()))
ls2 = list(map(int, input().split()))
ls3 = set(ls1) | set(ls2)
for x in ls3[:-1]:
print(x, end=" ")
print(ls3[-1]) |
e74a0921242666d5e66a20bcf6df5cd69e4724d9 | justinjhjung/st_algorithm | /greedy/greedy_coinchange.py | 485 | 3.875 | 4 | from sys import stdin
def input():
return stdin.readline().strip()
def leastcoin(coins, change):
res = 0
for coin in coins:
if coin > change:
continue
leastamnt = change//coin
res += leastamnt
change -= leastamnt * coin
return res
test_num = int(input())
for i in range(test_num):
coin_num = int(input())
coins = [int(x) for x in input().split()][::-1]
change = int(input())
print(leastcoin(coins, change)) |
10ed1976041126596cbfd48aa9d7736a4507ef86 | vitormicael/FATEC-MECATRONICA-1600792021046-vitormicael | /LTP1-2020-2/Pratica05/exercício02-refeito.py | 343 | 3.84375 | 4 | lado1 = int(input('Informe o valor do primeiro lado: '))
lado2 = int(input('Informe o valor do segundo lado: '))
lado3 = int(input('Informe o valor do terceiro lado: '))
if (lado1 > 0) and (lado2 > 0) and (lado3 > 0):
if (lado1 + lado2) > lado3 and (lado2 + lado3) > lado1 and (lado1 + lado3) > lado2:
print('Pode formar um triângulo')
|
8110896fa2728263f0726a162dccc64f3efa0227 | hirad-p/ascend | /bytebybyte/autocomplete/autocomplete.py | 231 | 3.671875 | 4 | import sys
words = ["abc", "acd", "bcd", "def", "a", "aba"]
def autocomplete(prefix):
return [x for x in words if x.startswith(prefix)]
if __name__ == "__main__":
suggestions = autocomplete(sys.argv[1])
print(suggestions)
|
6771f4ea316060a2e5550649e4ad510e6aa6da7f | dgeoffri/adventofcode | /2021/day03b.py | 1,669 | 3.5625 | 4 | #!/usr/bin/env python3
def get_gamma_rate(the_input):
return idk(the_input, 0)
def get_epsilon_rate(the_input):
return idk(the_input, -1)
def get_oxygen_generator_rating(the_input):
return idk(the_input, 0, True)
def get_co2_scrubber_rating(the_input):
return idk(the_input, -1, True)
def idk(the_input, position, buildstrfilter = False):
buildstr = ''
if buildstrfilter:
filterfunc = lambda x: x.startswith(buildstr)
else:
filterfunc = lambda x: True
for x in range(len(inputdata[0])):
the_digit = [ y[x] for y in filter(filterfunc, inputdata) ]
tallies = {}
for possibility in set(the_digit):
tallies[possibility] = the_digit.count(possibility)
buildstr += sorted(tallies.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)[position][0]
return buildstr
if __name__ == "__main__":
with open('day03.txt', 'r') as inputfile:
inputdata = inputfile.read().splitlines()
gamma_rate = int(get_gamma_rate(inputdata), 2)
epsilon_rate = int(get_epsilon_rate(inputdata), 2)
oxygen_generator_rating = int(get_oxygen_generator_rating(inputdata), 2)
co2_scrubber_rating = int(get_co2_scrubber_rating(inputdata), 2)
print("gamma rate: {}".format(gamma_rate))
print("epsilon rate: {}".format(epsilon_rate))
print("power consumption: {}".format(gamma_rate * epsilon_rate))
print("oxygen generator rating: {}".format(oxygen_generator_rating))
print("co2 scrubber rating: {}".format(co2_scrubber_rating))
print("life support rating: {}".format(oxygen_generator_rating * co2_scrubber_rating))
|
cd1cea69fdf616dba14676af4bf98fb397123ac9 | gokuleswaran/python-class | /parser.py | 5,395 | 3.609375 | 4 | #!/usr/bin/python
# Robert Theis
# Sept. 15, 2012
# Introduction to Python Programming
# Parses a valid Protein Data Bank (PDB) format text file for a protein.
import argparse, os, requests, sys
def atom_element(atom):
return atom[0]
def atom_residue(atom):
return atom[1]
def atom_x_pos(atom):
return atom[2]
def atom_y_pos(atom):
return atom[3]
def atom_z_pos(atom):
return atom[4]
def bounding_box(x_range, y_range, z_range):
return [(x_range[0], y_range[0], z_range[0]), \
(x_range[0], y_range[0], z_range[1]), \
(x_range[0], y_range[1], z_range[0]), \
(x_range[0], y_range[1], z_range[1]), \
(x_range[1], y_range[0], z_range[0]), \
(x_range[1], y_range[0], z_range[1]), \
(x_range[1], y_range[1], z_range[0]), \
(x_range[1], y_range[1], z_range[1])]
def build_url(id):
return "http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb" + \
"&compression=NO&structureId={0}".format(id)
def download_pdb(pdbid):
# Download the file
print "Downloading..."
r = requests.get(build_url(pdbid))
if r.status_code != 200:
sys.exit("Downoad failed.")
print "Download complete."
return r.text
def is_atom_line(line):
if line[:4] == 'ATOM':
return True
else:
return False
def is_header_line(line):
if line[:6] == 'HEADER':
return True
else:
return False
def is_title_line(line):
if line[:5] == 'TITLE':
return True
else:
return False
def openfile(filename):
fh = open(filename, "r+")
str = fh.read()
fh.close()
return str
# Returns a data structure representing an atom: element, residue, and position
def parse_atom_line(line):
if is_atom_line(line) == False:
return False
# element, residue, x-position, y-position, z-position
return list([line[76:78], line[17:20], line[30:38], line[38:46], line[46:54]])
# Goes through all PDB lines and tallies properties for the protein as a whole
# Returns a PDB dictionary representing the tallied values for the protein
def parse_pdb(pdb_lines):
pdb = {'id': None, 'title': '', 'atom_count': 0, 'corners': None, 'volume': 0}
residues = {}
atom_count = 0
x_range = (None, None)
y_range = (None, None)
z_range = (None, None)
for line in pdb_lines:
if is_atom_line(line) == True:
# Increase atom count
atom_count = atom_count + 1
# Check position values
atom = parse_atom_line(line)
x_range = update_range(x_range, atom_x_pos(atom))
y_range = update_range(y_range, atom_y_pos(atom))
z_range = update_range(z_range, atom_z_pos(atom))
# Tally the residue
residue = line[17:20]
if residue in residues:
residues[residue] = residues[residue] + 1
else:
residues[residue] = 1
elif is_title_line(line):
pdb['title'] = pdb['title'].rstrip() + line[10:] + ' '
elif is_header_line(line):
pdb['id'] = line[62:66]
pdb['atom_count'] = atom_count
pdb['corners'] = bounding_box(x_range, y_range, z_range)
pdb['volume'] = volume(x_range, y_range, z_range)
return pdb
# Returns the atom count for a protein, given a PDB dictionary
def pdb_atom_count(pdb):
return pdb['atom_count']
# Returns the corners of the 3D bounding box for a protein, given a PDB dictionary
def pdb_bounding_box_corners(pdb):
return pdb['corners']
# Returns the volume of the 3D bounding box for a protein, given a PDB dictionary
def pdb_bounding_box_volume(pdb):
return pdb['volume']
# Returns the PDB ID, given a PDB dictionary
def pdb_id(pdb):
return pdb['id']
def pdb_lines(pdb_data):
return pdb_data.split('\n')
def pdb_title(pdb):
return pdb['title']
# Given a minimum/maximum value pair and a number, returns an updated min/max if
# the number falls outside of the min/max range, otherwise returns original pair
def update_range(old_range, num):
num = float(num)
if old_range[0] == None: # range is undefined for the first run
return(num, num)
min = old_range[0]
max = old_range[1]
if num < min:
min = num
elif num > max:
max = num
return (min, max)
def validate_pdbid(pdbid):
if len(pdbid) != 4:
return False
for char in pdbid:
if char.isalpha() == False and char.isdigit() == False:
return False
return True
def volume(x_range, y_range, z_range):
x = float(x_range[1]) - float(x_range[0])
y = float(y_range[1]) - float(y_range[0])
z = float(z_range[1]) - float(z_range[0])
return x * y * z
def main():
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('id', action="store")
opts = parser.parse_args()
filename= opts.id + '.pdb'
if not os.path.exists(filename):
fh = open(filename, "w")
fh.write(download_pdb(opts.id))
fh.close()
pdbfile = openfile(filename)
pdb = parse_pdb(pdb_lines(pdbfile))
print "TITLE: ", pdb_title(pdb)
print "ID: ", pdb_id(pdb)
print "ATOM COUNT: ", pdb_atom_count(pdb)
print "CORNERS: ", pdb_bounding_box_corners(pdb)
print "VOLUME: ", pdb_bounding_box_volume(pdb)
main()
|
f8ca8aa0dce4083ee289b8786e4a5d961536a27b | konishis/exercise_python_koni | /exercise_python_koni/projecteuler/Q1.py | 1,158 | 4.28125 | 4 | '''
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
'''
3 または 5 の倍数である 10 未満のすべての自然な数値をリストすると、
3、5、6、9 が得られます。これらの倍数の合計は 23 です。
1000 以下の 3 または 5 のすべての倍数の合計を検索します。
'''
# def multiplesAnyNum(InAnyNum,Incnt):
# for num in range(Incnt):
# if num % InAnyNum == 0:
# yield num
# def cntmultipleNums(InAnyNum,Incnt):
# sumnum = 0
# for count , num in enumerate(multiplesAnyNum(InAnyNum, Incnt),1):
# sumnum += num
# return sumnum
# multipleNum1 = 3
# multipleNum2 = 5
# Count = 1001
# Ans = cntmultipleNums(multipleNum1,Count) + cntmultipleNums(multipleNum2,Count)
# print(Ans)
COUNT = 1000
def sumAnyMultipleNum(InNum):
tmp = 0
for num in range(1,COUNT):
if num % InNum == 0:
tmp += num
return tmp
Ans = sumAnyMultipleNum(3) + sumAnyMultipleNum(5) |
b545f9cd79f53d89490562dbf504956316257b19 | KaiHoshijo/Chess | /King.py | 14,896 | 3.546875 | 4 | import pygame
class king(pygame.sprite.Sprite):
def __init__(self, screen, board, image, rect, row, col, colour):
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.board = board
self.image = image
self.rect = rect
self.row = row
self.col = col
self.colour = colour
self.sidePieces = []
self.enemyPieces = []
self.originalImage = self.image
startPosition = (row, col)
self.setPosition(startPosition)
self.chosenRect = None
self.chosenPosition = None
self.hasMove = False
# self.image.set_alpha(100)
def update(self):
pass
def delete(self):
self.sidePieces.remove(self)
self.kill()
def render(self):
return pygame.sprite.RenderPlain(self.sidePieces + self.enemyPieces)
# get position
def getPosition(self):
return (self.row, self.col)
# get rect for the king's position
def getRect(self):
return self.rect
# get opposite colour
def getOppositeColour(self):
if (self.colour == "W"):
return "B"
else:
return "W"
# setting position based on row and col
def setPosition(self, position):
newCenter = self.board.getPosition(position[0], position[1])[-1]
if (newCenter != None):
self.board.setPositionColour(self.getPosition(), "E")
self.rect.center = newCenter
self.row = position[0]
self.col = position[1]
self.board.setPositionColour(position, self.colour)
else:
raise Exception("There is no position there")
# set side pieces
def setSidePieces(self, pieces):
self.sidePieces = pieces
# set enemy pieces
def setEnemyPieces(self, pieces):
self.enemyPieces = pieces
# setting the image of the piece
def setImage(self, image):
self.image = image
# find available moves
def findMoves(self, show = True, isKing=False):
# print(isKing)
# return all moves available
allMoves = [self.moveLeft(), self.moveRight(), self.moveUp(), self.moveDown(),
self.moveUpLeft(), self.moveUpRight(), self.moveDownLeft(), self.moveDownRight()]
if (not isKing):
return allMoves
# castling
if (not self.hasMove):
for piece in self.sidePieces:
piecePosition = piece.getPosition()
if (not piece.hasMove):
if (piecePosition[1] == 0):
allMoves.append(self.moveTwoLeft())
elif (piecePosition[1] == 7):
allMoves.append(self.moveTwoRight())
safeMoves = []
for move in allMoves:
# print(move)
if (len(move) == 1):
position = (self.row + move[-1][1], self.col + move[-1][2])
if (not self.kingCheck(position = position)[0]):
safeMoves.append(move)
else:
for submove in move:
position = (self.row + submove[1], self.col + submove[2])
if (not self.kingCheck(position = position)[0]):
safeMoves.append([submove])
else:
break
return safeMoves
# show available moves after being clicked
def showMoves(self, show=True, isKing=False):
# all centers for the king to move to
allRects = []
# print(isKing)
# getting all moves available
allMoves = self.findMoves(show = show, isKing = isKing)
# creating dots where all moves are available
for moves in allMoves:
draw = True
for move in moves:
possible = move[0]
if (possible):
change = move[1:]
row, col = self.row, self.col
position = self.board.getPosition(row+change[0], col+change[1])
positionCenter = position[-1]
if (show and position[0] != self.colour and draw):
positionRect = pygame.draw.circle(self.screen, (0, 255, 0), positionCenter, 8)
else:
transparency = pygame.Color(0, 0, 0, 0)
transparency.a = 0
# print(transparency)
positionRect = pygame.draw.circle(self.screen, transparency, positionCenter, 0)
allRects.append([positionRect, (row+change[0], col+change[1]), draw])
if (position[0] != 'E'):
draw = False
return allRects
# check if move is valid
def validMove(self, newRow, newCol):
"""
newRow: the new row position
newCol: the new col position
"""
if (newRow in range(8) and newCol in range(8)):
newPosition = (newRow, newCol)
# if (self.colour != self.board.getPosition(newRow, newCol)[0]):
# print("Move okay!")
return True
# print("Not okay!")
return False
# move the King
def move(self, rowMove, colMove):
"""
rowMove: checking where to move the piece through rows (can be positive or negative)
colMove: checking where to move the piece through cols (can be positive or negative)
"""
row, col = self.row, self.col
return self.validMove(row+rowMove, col+colMove)
# move left
def moveLeft(self):
allMoves = [[self.move(0, -1, ), 0, -1]]
if (self.passPoint(allMoves) == self.colour): return [[False, 0, -1]]
return allMoves
# move right
def moveRight(self, ):
allMoves = [[self.move(0, 1, ), 0, 1]]
if (self.passPoint(allMoves) == self.colour): return [[False, 0, 1]]
return allMoves
# move up
def moveUp(self, colour=""):
if (colour == ""):
colour = [self.colour]
allMoves = [[self.move(1, 0, ), 1, 0]]
if (self.passPoint(allMoves) in colour): return [[False, 1, 0]]
return allMoves
# move down
def moveDown(self, colour=""):
if (colour == ""):
colour = [self.colour]
allMoves = [[self.move(-1, 0, ), -1, 0]]
if (self.passPoint(allMoves) in colour): return [[False, -1, 0]]
return allMoves
# move up left
def moveUpLeft(self, ):
allMoves = [[self.move(1, -1, ), 1, -1]]
if (self.passPoint(allMoves) == self.colour): return [[False, 1, -1]]
return allMoves
# move up right
def moveUpRight(self, ):
allMoves = [[self.move(1, 1, ), 1, 1]]
if (self.passPoint(allMoves) == self.colour): return [[False, 1, 1]]
return allMoves
# move down left
def moveDownLeft(self, ):
allMoves = [[self.move(-1, -1, ), -1, -1]]
if (self.passPoint(allMoves) == self.colour): return [[False, -1, -1]]
return allMoves
# move down right
def moveDownRight(self, ):
allMoves = [[self.move(-1, 1, ), -1, 1]]
if (self.passPoint(allMoves) == self.colour): return [[False, -1, 1]]
return allMoves
# move two right
def moveTwoRight(self, ):
allMoves = []
for col in range(self.col+1, self.col+3):
newCol = col - self.col
allMoves.append([self.move(0, newCol), 0, newCol])
if (self.passPoint(allMoves) == self.colour): break
return allMoves
# move two left
def moveTwoLeft(self, ):
allMoves = []
for col in range(self.col-1, self.col-3, -1):
newCol = col - self.col
allMoves.append([self.move(0, newCol), 0, newCol])
if (self.passPoint(allMoves) == self.colour): break
return allMoves
# move when dragged
def dragMove(self, king=False):
# having the king follow the mouse
self.rect.center = pygame.mouse.get_pos()
# getting the all available moves and their positions
allRects = self.showMoves(isKing = king)
for rect, position, draw in allRects:
# checking if the piece is touching its potential moves
if (rect.colliderect(self.rect) and draw):
self.chosenRect = rect
self.chosenPosition = position
# confirm move
def confirmDragMove(self, move):
# ensuring that the piece only moves to a desired sport
currentPosition = self.getPosition()
if (self.chosenRect != None):
# check if the mouse is touching still touching the square after the mouse let go
if (self.rect.colliderect(self.chosenRect)):
if (self.takePiece(self.chosenPosition)):
move = self.increaseMove(move)
print("Taken!")
self.setPosition(self.chosenPosition)
if (self.chosenPosition[1] + 2 == currentPosition[1] and (currentPosition == (0, 4) or currentPosition == (7, 4))):
for piece in self.sidePieces:
if (piece.getPosition() == (self.row, 0)):
piece.setPosition((self.row, self.chosenPosition[1]+1))
break
if (self.chosenPosition[1] - 2 == currentPosition[1] and (currentPosition == (0, 4) or currentPosition == (7, 4))):
for piece in self.sidePieces:
if (piece.getPosition() == (self.row, 7)):
piece.setPosition((self.row, self.chosenPosition[1]-1))
break
else:
self.setPosition(currentPosition)
# resetting for later use
self.currentPositon = None
self.chosenRect = None
return [True, move]
self.setPosition(currentPosition)
return [False, move]
# take piece if chess conditions are met
def takePiece(self, position, delete=True):
"""
position: The position that's attempted to move to
pieces: All playable pieces of opposite colour
"""
desired = self.board.getPosition(position[0], position[1])
# only run this if the piece is the opposite colour
if (desired[0] == self.getOppositeColour()):
chosen = None
for piece in self.enemyPieces:
pieceMoves = piece.showMoves(False)
piecePositions = [(move[1][0], move[1][1]) for move in pieceMoves]
# print(piecePositions, position[-1], position[-1] in piecePositions)
# check if the piece trying to be taken is protected
if (piece.getPosition() == position):
chosen = piece
# if (position in piecePositions):
# # print("Can't take")
# # return false since the piece can't be taken
# return False
if (delete):
chosen.delete()
elif (desired[0] == self.colour):
# don't take if the piece is the same colour as this piece
return False
# can take piece if the position has an opposite colour chess piece that can't be taken or is an empty square
return True
# can't go pass this point
def passPoint(self, allMoves):
if (allMoves[-1][0]):
position = (self.row + allMoves[-1][1], self.col + allMoves[-1][2])
colour = self.board.getPosition(position[0], position[1])[0]
return colour
# check if king is in check
def kingCheck(self, position = ""):
if (position == ""):
position = self.getPosition()
position = (position[0], position[1])
for piece in self.enemyPieces:
pieceMoves = piece.showMoves(False)
piecePositions = [(move[1][0], move[1][1]) for move in pieceMoves]
if (position in piecePositions):
return [True, piecePositions]
# self.setImage(self.originalImage)
return [False, None]
# check if king is in checkmate
def kingCheckMate(self, piecePositions):
# if the king can still move or pieces can block this move then no checkmate
if (self.stillMove() or self.block(piecePositions)):
return False
# else checkmate!
return True
# check if king is in stalemate
def kingStaleMate(self):
if (not self.stillMove() and len(self.sidePieces) == 1):
return True
return False
# check if the king can still move
def stillMove(self, position = ''):
currentPosition = position
if (position == ""):
currentPosition = self.getPosition()
# check if its potential positions end in check
allMoves = self.findMoves()
for move in allMoves:
if (move[-1][0]):
# return true if there is a safe position
nextPosition = (self.row+move[0][1], self.col+move[0][2])
if (self.validMove(nextPosition[0], nextPosition[1])):
check = self.kingCheck(nextPosition)
take = self.takePiece(nextPosition, delete=False)
if (not check[0] and take):
return True
# return false since there's no safe positions
return False
# block abilities
def block(self, piecePositions):
block = False
for piece in self.sidePieces:
pieceMoves = piece.showMoves(False)
helpPositions = [(move[1][0], move[1][1]) for move in pieceMoves]
for position in helpPositions:
if (position in piecePositions):
piece.image.set_alpha(0)
originalPosition = piece.getPosition()
piece.setPosition(position)
if (not self.kingCheck()[0]):
block = True
piece.setPosition(originalPosition)
piece.image.set_alpha(255)
if (block):
return block
return block
# increaes move
def increaseMove(self, move):
return move + 1 |
5d07526a325ed8f77e57255e11d2811d48e97465 | Elizabeth6743/My-First-Project | /Project1.py | 4,938 | 4.03125 | 4 | score = 0
First_name = input("What is your First name?")
Last_name = input("What is your Last name?")
age = input("What is your age?")
print("Hello " + First_name + " " + Last_name)
print("Welcome to a Nation Wide PANDEMIC")
print("Let's see how much you know about Covid-19")
# Question 1
answer1 = input("How many confirmed Covid-19 cases are there in Massachusetts? \na.10,000 \nb.30,000 \nc.over 60,000 \nEnter answer:")
if answer1 == "c" or answer1 == "over 60,000":
score += 1
print("That is correct")
print("score: ", score)
else:
print("Wrong answer! The correct answer is c.over 60,000")
print("score: ", score)
# Question 2
answer2 = input("Since the Pandemic how many related deaths have been reported in Massachusetts? \na.Less than 500 \nb.1,000 \nc.over 4,000 \nEnter answer:")
if answer2 == "c" or answer2 == "over 4,000":
score += 1
print("Hooray that is correct")
print("score: ", score)
else:
print("That is not correct the answer. The correct answer is c.over 4,000")
print("score: ", score)
# Question 3
answer3 = input("What county has the most reported Covid-19 cases? \na.Middlesex County \nb.Essex County \nc.Suffolk County \nd.Norfolk County \nEnter answer:")
if answer3 == "a" or answer3 == "Middlesex County":
score += 1
print("Way to go that is correct")
print("score: ", score)
else:
print("Incorrect! The correct answer is a.Middlesex County")
print("score: ", score)
# Question 4
answer4 = input("What are some ways to protect yourself during this Pandemic? \na.Wear a mask \nb.Social distance \nc.Wash your hands for at least 20 seconds with soap \nd.All of the above \nEnter answer:")
if answer4 == "d" or answer4 == "All the Above":
score += 1
print("That is correct")
print("score: ", score)
else:
print("Sorry wrong answer. The correct answer is d.All of the above")
print("score: ", score)
# Question 5
answer5 = input("How much is the fine in Lawrence,MA if you don't wear a mask? \na.$50 \nb.$150 \nc.$300 \nd.$500 \nEnter answer:")
if answer5 == "c" or answer5 == "$300":
score += 1
print("That is correct!")
print("score: ", score)
else:
print("Wrong answer! The correct answer is c.$300")
print("score: ", score)
# Question 6
answer6 = input("The city of Lawrence will fine anyone ages ___ and up for not wearing a mask in Lawrence,MA \na.6 \nb.5 \nc.2 \nd.4 \nEnter answer:")
if answer6 == "a" or answer6 == "6":
score += 1
print("Correct answer")
print("score: ", score)
else:
print("That is not right! The correct answer is a.6")
print("score: ", score)
# Question 7
answer7 = input("What are the symptoms for Covid-19 \na.Cough \nb.Muscle pain \nc.Shortness of breathe \nd.All of the above \nEnter answer:")
if answer7 == "d" or answer7 == "All of the above":
score += 1
print("That is correct")
print("score: ", score)
else:
print("Wrong answer! The correct answer is d.All of the above")
print("score: ", score)
# Question 8
answer8 = input("Who does Covid-19 impact the most? \na.People over the age of 65 \nb.People of all ages \nc.People with underlining conditions \nd.People under 50 \nEnter answer:")
if answer8 == "b" or answer8 == "People of all ages":
score += 1
print("That is correct")
print("You are on a roll")
print("score: ", score)
else:
print("That is not correct! The correct answer is b.People of all ages")
print("score: ", score)
# Question 9
answer9 = input("Is sex recommended during Covid-19? \na.Yes it is ok as long as your wearing a mask. \nb.No sex isn't recommended and you should keep your social distance \nEnter answer:")
if answer9 == "b" or answer9 == "Sex isn't recommended and you should keep your social distance":
score += 1
print("That is correct")
print("score: ", score)
else:
print("That isn't correct! The correct answer is b.Sex isn't recommend and you should keep your social distance")
print("score: ", score)
# Question 10
answer10 = input("What businesses are considered essential during this Pandemic? \na.Grocery Stores \nb.Pharmacies \nc.Hospitals \nd.All of the above \nEnter answer:")
if answer10 == "d" or answer10 == "All of the above":
score += 1
print("That is the correct answer")
print("score: ", score)
else:
print("Wrong answer! The correct answer is d.All of the above")
print("score: ", score)
if score <=4:
print("Your total score is:", score, "-Better luck Next Time-")
print("Thanks for playing")
print("Remember to Stay Safe and Stay Healthy")
elif score == 5:
print("Your total score is:", score, "-Not bad-")
print("Thanks for playing")
print("Remember to Stay Safe and Stay Healthy")
else:
print("Your total score is:", score, "-Great Job! I see you know a lot about the Covid-19 Pandemic")
print("Thanks for playing")
print("Remember to Stay Safe and Stay Healthy") |
7be371b7b74b5aa52ade9070139e0fe9ff06c773 | RaulGnzlzAlvrd/clase-python3 | /clase09/soluciones/uses_only.py | 462 | 4.03125 | 4 | def uses_only(word, available):
'''
Comprueba que word use solamente letras en chars
word: String
chars: String
return: boolean
'''
for letter in word:
if not letter in available:
return False
return True
caracteres = input("Ingresa los caracteres deseados:\n")
file_name = "../words.txt"
fin = open(file_name)
for line in fin:
word = line.strip()
if uses_only(word, caracteres):
print(word)
|
21c620da5b65dda157f2bb0e118d92ffeec207c4 | burakbayramli/books | /Introduction_to_numerical_programming_using_Python_and_CPP_Beu/modules/sort.py | 6,998 | 3.625 | 4 | #---------------------------------- sort.py ---------------------------------
# Contains routines for sorting, indexing and ranking numeric sequences.
# Part of the numxlib numerics library. Author: Titus Beu, 2013
#----------------------------------------------------------------------------
#============================================================================
def BubbleSort0(x, n):
#----------------------------------------------------------------------------
# Ascending sort of array x[1..n] by bubble sort
#----------------------------------------------------------------------------
for ipass in range(1,n): # loop of passes
for i in range(1,n-ipass+1): # loop over unsorted sublists
if (x[i] > x[i+1]): # compare neighbors
xi = x[i]; x[i] = x[i+1]; x[i+1] = xi # swap neighbors
#============================================================================
def BubbleSort1(x, n):
#----------------------------------------------------------------------------
# Ascending sort of array x[1..n] by modified bubble sort
#----------------------------------------------------------------------------
for ipass in range(1,n): # loop of passes
swap = 0 # initialize swap flag
for i in range(1,n-ipass+1): # loop over unsorted sublists
if (x[i] > x[i+1]): # compare neighbors
xi = x[i]; x[i] = x[i+1]; x[i+1] = xi # swap neighbors
swap = 1 # set swap flag
if (not swap): break # exit loop if no swap occurs
#============================================================================
def BubbleSort(x, n):
#----------------------------------------------------------------------------
# Ascending sort of array x[1..n] by modified bubble sort
#----------------------------------------------------------------------------
ipass = 0 # initialize pass counter
swap = 1 # initialize swap flag to enter loop
while (swap): # perform passes while swaps occur
ipass += 1 # increase pass counter
swap = 0 # initialize swap flag
for i in range(1,n-ipass+1): # loop over unsorted sublists
if (x[i] > x[i+1]): # compare neighbors
xi = x[i]; x[i] = x[i+1]; x[i+1] = xi # swap neighbors
swap = 1 # set swap flag
#============================================================================
def InsertSort(x, n):
#----------------------------------------------------------------------------
# Ascending sort of array x[1..n] by direct insertion
#----------------------------------------------------------------------------
for ipiv in range(2,n+1): # loop over pivots
xpiv = x[ipiv] # save pivot to free its location
i = ipiv - 1 # initialize sublist counter
while ((i > 0) and (x[i] > xpiv)): # scan to the left of pivot
x[i+1] = x[i] # item > pivot: shift to the right
i -= 1
x[i+1] = xpiv # insert pivot into last freed location
#============================================================================
def QuickSort(x, l, n):
#----------------------------------------------------------------------------
# Ascending sort of array x[l..n] by Quicksort
#----------------------------------------------------------------------------
if (l >= n): return
# pivot = x[n]; create "<" and ">=" lists
m = l # upper index in "<"-list
for i in range(l,n): # scan entire list, excepting pivot
if (x[i] < x[n]): # compare current value with pivot
t = x[i]; x[i] = x[m]; x[m] = t # swap < value to end of "<"-list
m += 1 # extend "<"-list: increase upper index
t = x[m]; x[m] = x[n]; x[n] = t # swap pivot between "<" and ">=" lists
QuickSort(x,l,m-1) # sort "<"-list
QuickSort(x,m+1,n) # sort ">="-list
#============================================================================
def Index(x, ind, n):
#----------------------------------------------------------------------------
# Ascending indexing of array x[1..n] in ind[] by insertion sort
#----------------------------------------------------------------------------
for i in range(1,n+1): ind[i] = i # initialize index array
for ipiv in range(2,n+1): # loop over pivots
xpiv = x[ipiv] # save pivot to free its location
i = ipiv - 1 # initialize sublist counter
while ((i > 0) and (x[ind[i]] > xpiv)): # scan to the left of pivot
ind[i+1] = ind[i] # item > pivot: shift to the right
i -= 1
ind[i+1] = ipiv # insert pivot into last freed location
#============================================================================
def Rank(ind, rnk, n):
#----------------------------------------------------------------------------
# Returns the ranks rnk[1..n] for a list indexed in ind[1..n]
#----------------------------------------------------------------------------
for i in range(1,n+1): rnk[ind[i]] = i
#============================================================================
def Index2(x, y, ind, n):
#----------------------------------------------------------------------------
# Ascending indexing of correlated arrays x[1..n] and y[1..n] in ind[] by
# insertion sort using x[] as primary key and y[] as secondary key
#----------------------------------------------------------------------------
for i in range(1,n+1): ind[i] = i # initialize index array
for ipiv in range(2,n+1): # loop over pivots
xpiv = x[ipiv]; ypiv = y[ipiv]
i = ipiv - 1 # initialize sublist counter
while ((i > 0) and # scan to the left of pivot
(x[ind[i]] > xpiv or (x[ind[i]] == xpiv and y[ind[i]] > ypiv))):
ind[i+1] = ind[i] # item > pivot: shift to the right
i -= 1
ind[i+1] = ipiv # insert pivot into last freed location
|
efc5778c00196d8133503756de5699a6a45d55c7 | github653224/GitProjects_SeleniumLearing | /SeleniumLearningFiles/SeleniumLearning01/Test2/26StringIO.py | 929 | 3.625 | 4 | #往内存中读写内容
from io import StringIO
f=StringIO()
f.write("hello ")
f.write("panxueyan")
f.write("!")
print(f.getvalue())
# 要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取: >>>
from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
# BytesIO
# StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。 BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,
# 然后写入一些bytes:
from io import BytesIO
f2=BytesIO()
f2.write("中文".encode("utf-8"))
print(f2.getvalue())
#请注意,写入的不是str,而是经过UTF-8编码的bytes。 和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:
|
9ca1da04db7918d733d01687ff70a25eff11504d | dfworldwang/Python-Elementary-Practice | /Data Structure and Algorithms/python_join.py | 565 | 3.671875 | 4 |
li = ['my', 'name', 'is', 'bob']
# Concatenate the elements of list with blank
print(' '.join(li))
print('..'.join(li))
class Foo():
def __init__(self):
self.name = [{"Susan": ("Boyle", 50, "alive")}, {"Albert": ("Speer", 106, "dead")}]
def __str__(self):
ret_str = ""
for d in self.name:
for k in d:
ret_str += "".join([k, " ", d[k][0], " is ", str(d[k][1]),
" and ", d[k][2], ". "])
return ret_str
foo = Foo()
print(foo)
|
0f4a5a3988386b2b5610035dea167c8a8cbf3261 | harinderbhasin/DataScience | /BhasinMiniProject-XML-Q1.py | 1,173 | 3.71875 | 4 | # Mini Project 4
# Name: Harry Bhasin in collaboration with Peter B.
# Question 1
import pandas as pd
import xml.etree.ElementTree as ET
# import statistics
# from statistics import mean
import numpy as np
# read the player data text file into a python dataframe using panda
playerdata=pd.read_csv('baseball_salaries_2003.txt', sep=":", skiprows=3, names=('Team','Player','Salary','Position'))
# define a function that converts the dataframe to xml and writes to a xml file
def df_to_xml(df, filename=None, mode='w'):
def row_to_xml(row):
xml = [' <playerdata>']
for i, col_name in enumerate(row.index):
xml.append(' <{0}>{1}</{0}>'.format(col_name, row.iloc[i]))
xml.append(' </playerdata>')
return '\n'.join(xml)
res = '<?xml version="1.0" encoding="UTF-8"?>\n<baseball>\n' + '\n'.join(df.apply(row_to_xml, axis=1)) + '\n</baseball>'
if filename is None:
return res
with open(filename, mode) as f:
f.write(res)
# execute the function on the dataframe 'playerdata', with output file 'baseball_salaries_2003.xml'
df_to_xml(playerdata,'baseball_salaries_2003.xml')
|
853f36d2b70faaf0757768ca1467d70ab38d6c91 | pranavmswamy/leetcode | /mathworks/numberOfOperationsToMakeConnectedNetwork.py | 1,255 | 3.78125 | 4 | class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
# find number of connected components in the network
# number of connections reqd = number of connected components - 1
# this is a simple graph connected components question
# if the number of connections are less than n-1, then it is not possible to connect all n components. So return false
if len(connections) < n-1:
return -1
# construct adjList
adjList = dict()
# add all comps to adjList
for i in range(n):
adjList[i] = list()
for u,v in connections:
adjList[u].append(v)
adjList[v].append(u)
def dfs(computer, visited, adjList):
visited.add(computer)
for child in adjList[computer]:
if child not in visited:
dfs(child, visited, adjList)
count = 0
visited = set()
for computer in adjList:
if computer not in visited:
count += 1 # found a disconnected comp
dfs(computer, visited, adjList)
return count-1
|
b883570f1fceebf8d5c89ae53b7aacfbe2531871 | yuryanliang/Python-Leetcoode | /100 medium/8/383 ransom-note.py | 1,080 | 3.90625 | 4 | """
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
"""
class Sol:
def canConstruct(self, ransomNote, magazine):
from collections import defaultdict
lookup = defaultdict(list)
for c in magazine:
if c in lookup:
lookup[c]+=1
else:
lookup[c]=1
for c in ransomNote:
if c in lookup:
lookup[c]-=1
if lookup[c]<0:
return False
else:
return False
return True
if __name__ == '__main__':
note="aa"
mag = "aab"
print(Sol().canConstruct(note, mag))
|
722c9fef00cc8c68bda1a32eb5964413311f1a2d | smtorres/python-washu-2014 | /Assignment01/school.py | 1,042 | 4.21875 | 4 | from collections import OrderedDict
class School():
def __init__(self, school_name):
self.school_name = school_name
self.db = {}
# Function that adds values and keys to a dictionary. Keys are school grades and each can take as value the name of a kid belonging to that grade.
# It returns a dictionary with the name of the keys
def add(self, name, grade):
if grade in self.db:
self.db[grade].add(name)
else:
self.db[grade] = {name}
# Function that takes as input Grade and delivers the names of the kids that belong to that group.
def grade(self, grade):
if grade not in self.db.keys():
return None
else:
return self.db.get(grade)
print self.db.keys
# Function that sorts and converts the values of the dictionary from sets to tuples.
def sort(self):
new_dic = self.db
for i in range(0, len(new_dic)):
Key = new_dic.keys()[i]
Value = new_dic.values()[i]
Value = list(Value)
Value = tuple(Value)
new_dic[Key] = Value
print new_dic.values
return new_dic
|
f0db90784e791d0e90c3d5f10d987f90c3563910 | bhawan0407/Python | /Pandas/starter.py | 868 | 3.578125 | 4 | import pandas as pd
pd.show_versions() # show pandas as well as dependencies versions
pd.show_versions(as_json=True)
print (pd.__version__)
# dataframes is a 2D array
# series is a 1D array of indexed data
# pandas support both index and label based indexing
# accessing a single series
# df['column_name'] or df["column_name"] or df.column_name
# dot notation won't work if there is a space in the column name
# accessing multiple series
# df[['column_name1', 'column_name2']]
# type(DataFrame) Output : pandas.core.frame.DataFrame
# type(DataFrame.SeriesName) Output : pandas.core.series.Series
df = pd.read_csv('olympics.csv', skiprows=4) # skip the first 4 rows
print (df.head())
print(df['City'])
print(type(df['City'])) # series
print(type(df[['City', 'Edition', 'Athlete']])) # dataFrame
print(df[['City', 'Edition', 'Athlete']].head())
|
65e3cdfebedc3bd4a70114131f2f7ccb9d704857 | Gourav-Sedhai/Basic-Practice | /together2.py | 410 | 3.8125 | 4 | def func(phrases):
vars = ("how", "where", "what", "why")
capitalized = phrases.capitalize()
if phrases.startswith(vars):
return "{}?".format(capitalized)
else:
return "{}.".format(capitalized)
result = []
while True:
user = input("Say Something: ")
if user == "\end":
break
else:
result.append(func(user))
print(" ".join(result))
|
c0455a8b735f02255a4ebcb43b0b250729211443 | SamJamaloff/hackerrankdailychallenges | /day_11/main.py | 617 | 3.515625 | 4 | if __name__ == '__main__':
def get_sum(matrix, row, col):
sum = 0
sum += matrix[row][col]
sum += matrix[row-1][col-1]
sum += matrix[row-1][col]
sum += matrix[row-1][col+1]
sum += matrix[row+1][col-1]
sum += matrix[row+1][col]
sum += matrix[row+1][col+1]
return sum
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
max_sum = -63
summs = []
for i in range(1, 5):
for j in range(1,5):
summs.append(get_sum(arr, i, j))
print(max(summs))
|
8a233332e946f6f53a55473046cd37e6c7dbcac8 | wjtxlliubin/good-good-study-day-day-up | /leetcode/code/algorithm_code/烧饼.py | 583 | 3.578125 | 4 | def sorter(l, count):
if len(l) == 1:
return count
else:
MAX = -1
MAX_ID = -1
for index, value in enumerate(l):
if value > MAX:
MAX = value
MAX_ID = index
temp_left = l[:MAX_ID + 1]
temp_left.reverse()
count += 1
temp_left.extend(l[MAX_ID + 1:])
temp_left.reverse()
count += 1
# print(temp_left)
# print(temp_left[:-1],count)
return sorter(temp_left[:-1], count)
if __name__ == '__main__':
print(sorter([2, 4, 3, 1], 0))
|
20d0e10a9ff1da68e8a0a696cd2a1868cec433a2 | HelpJamess/Name-Cipher | /cipher.py | 1,039 | 3.65625 | 4 | asciiLower = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
asciiUpper = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
newName = []
def listToStr(lst):
string = ""
for i in lst:
string += i
return string
def cipher(string, shift):
newString = []
for i in string:
if i == i.lower():
index = asciiLower.index(i) + shift
letter = asciiLower[(index % len(asciiLower)) - 1]
newString.append(letter)
if i == i.upper():
index = asciiUpper.index(i) + shift
letter = asciiUpper[(index % len(asciiUpper)) - 1]
newString.append(letter)
encryptedString = listToStr(newString)
return encryptedString
userInName = input("Enter the phrase you want to ") # Jamess
userInShift = int(input("Enter the number of shifts you want the name to go through")) # Guess
cryptName = cipher(userInName, userInShift)
print(cryptName)
|
332b81f8879a3c4a3cac747f284dd478e45da6e2 | dapazjunior/ifpi-ads-algoritmos2020 | /Iteracoes/Fabio_03/f3_q16_fibonacci.py | 271 | 3.8125 | 4 | def main():
n = int(input('Digite um número: '))
lista = [0, 1]
cont = 2
if n == 2:
lista = lista
else:
while cont < n:
lista.append(lista[cont-1] + lista[cont-2])
cont += 1
print (lista)
main() |
da647f7d0e3ed05a0f558bbeff04f6fe02356ef5 | humid1/python_learn | /python_study/高级变量类型/demo_字典.py | 919 | 3.90625 | 4 | people_dict = {"name": "小明"}
# ==== 取值 ====
print(people_dict["name"])
# ==== 增加、修改 ====
people_dict["age"] = 20 # 增加
people_dict["height"] = 172.5
people_dict["age"] = 21 # key存在,就修改
# ==== 删除 ====
people_dict.pop("name") # 清空 key 为 name 的键值对;若key值不存在就会报错
print(people_dict)
# ==== 统计键值对数量 ====
print(len(people_dict))
# ==== 合并字典 ====
temp_dict = {"sex": True, "age": 25}
people_dict.update(temp_dict) # 如果合并的字典包含已经存在的键值对,会覆盖原有的键值对
# 循环遍历字典
for k in people_dict:
print("%s : %s" % (k, people_dict[k]))
# ==== 清空字典 ====
people_dict.clear()
print(people_dict)
# 字典列表集
card_list = [
{"name": "用户1", "phone": "123456"},
{"name": "用户2", "phone": "123456"}
]
for card_info in card_list:
print(card_info) |
a3416e157624c5fb4d421896247861513f82c6c8 | dobricsongor/PYTHON | /Polygons.py | 1,614 | 3.921875 | 4 | class Polygon(object):
def __init__(self, *args):
self.sides = args
def __str__(self):
return f'Polygon has {len(self.sides)} sides'
def display(self):
for side_index, length in enumerate(self.sides, start=1):
print('Side {} with length: {}'.format(side_index, length))
class Triangle(Polygon):
def __init__(self, *args):
super().__init__(*args)
def area(self):
s1, s2, s3 = self.sides
s_p = sum(self.sides) / 2
return f'The area of this triangle is {round(((s_p*(s_p - s1)*(s_p - s2)*(s_p - s3))** 0.5),2)}.'
class PerimeterMixin:
def perimeter(self):
return f'The perimeter of this shape is {sum(self.sides)}.'
class PerimeterOfShape(PerimeterMixin, Polygon):
pass
class Square(Polygon):
def __init__(self, side):
super().__init__(side, side, side, side)
def area(self):
return f'The area of this square is {self.sides[0] ** 2}.'
@classmethod
def from_area(cls, given_area):
side = given_area / 4
#if side%2==0:
return cls(side)
#else:
# print('The given area is not right for a square.')
pol = Polygon(2,4,6,8,4)
print(pol)
pol.display()
tr = Triangle(4,4,6)
print(tr)
tr.display()
print(tr.area())
tr1 = PerimeterOfShape(3,5,7)
print(tr1)
print(tr1.perimeter())
sq = Square(2)
print(sq)
sq.display()
print(sq.area())
sq2 = Square.from_area(16)
print(sq2)
sq2.display()
sq3 = Square.from_area(15)
print(sq3)
sq3.display()
sq4 = PerimeterOfShape(3,5,8,6,9)
print(sq4)
print(sq4.perimeter())
|
26f648b2ab802c0f5ec0b74060b2b4b30e61208f | Rollo-Pollo/CeaserCypherProgram | /Cypher/cypher.py | 1,720 | 4.21875 | 4 | # REVERSE CYPHER
#put words in a file and put the file name where words is
with open('words.txt', 'r') as file:
for line in file:
for word in line.split():
start_word = word
# lines 2-5 search through the file and pick out the word
# These 2 lines reverse each character
reversed_word = ''
i = len(start_word) - 1
# Then the rest of this puts each character back together and prints it out to the console and stores it in reversed file
while i >= 0:
reversed_word = reversed_word + start_word[i]
i = i - 1
print('The reversed word is,',reversed_word)
# writes the reversed word to a file
f = open("reversedFile.txt", "w")
f.write(reversed_word)
f.close()
#_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
# MAIN CEASER CYPHER - Decryption
def encryption(text, shift_num):
encrypt_word = ""
for charac in text:
# cypher throuch characters and shift the letter
if charac.isalpha():
Alph = ord(charac) + shift_num
if Alph > ord('z'):
Alph -= 26
finLet = chr(Alph)
encrypt_word += finLet
return encrypt_word
# put the number you want to shift in the varaible shifted and it will print it out and write it ot the file encrypted word.txt
shifted = 1
print('The Ceaser Cypher encryption of the reversed word is, ',encryption(reversed_word, shifted))
f = open("encryptedWord.txt", "w")
f.write(encryption(reversed_word, shifted))
f.close()
# to decrypt just copy and past the encrypted word in to words.txt and change the shifted variable to the negative number value respectivly
'''Ceaser Cypher reverse cypher, encryption cypher and decryption cypher by Rolland Loy from TCTC''' |
2948619097864159437a6f5d64df4db25a64f575 | tiewangw/Python | /MachingLearning/chapter1/1.1 vector.py | 761 | 4.21875 | 4 | # 创建一个向量(vector)
import numpy as np
# 创建一个行向量
vector_row = np.array([1,2,3,4,5,6])
# 创建一个列向量
vector_rcolumn = np.array([ [1],
[2],
[3]])
print(vector_row)
# [1 2 3]
print("----------------------")
print(vector_rcolumn)
# [[1]
# [2]
# [3]]
print("----------------------")
# 选择向量的第3个元素
print(vector_row[2])
print("----------------------")
# 选择向量的所有元素
print(vector_row[:])
print("----------------------")
# 选择从第1个到第3个
print(vector_row[:3])
print("----------------------")
# 选择第3个之后所有
print(vector_row[3:])
print("----------------------")
# 选择最后一个
print(vector_row[-1]) |
e200573fe5c9ac5266e5f16453d3468fe1e103f0 | ZhaoFelix/Python3_Tutorial | /02.py | 1,099 | 4.125 | 4 | # coding=utf-8
# 类
class Student(object):
#定义类属性
name = 'Felix'
age = 23
#变量名两个下划线开头,定义私有属性,这样在类外部无法直接进行访问,类的私有方法也无法访问
__sex = 0
#定义构造方法
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.__sex = sex
#类方法
def get_sex(self):
return self.__sex
def set_sex(self,sex):
self.__sex = sex
#调用
if __name__ == '__main__':
student = Student('Felix',12,1) #实例化v成员变量
print(student.age,student.name)
#单继承
class TopStudent(Student):
top_id = 1024
def __init__(self,name,age,sex,top_id):
#调用父类的构造方法
super(TopStudent,self).__init__(name,age,sex)
self.top_id = top_id
#重写父类方法
# def set_sex(self,sex):
# self.__sex = sex+1
# print('重写父类的方法')
#调用
if __name__ == '__main__':
topStudent = TopStudent('Felix1',45,0,2048)
print(topStudent.set_sex(1))
|
7f951c3c21502db18123e06933f918683556a2ce | Vigyrious/python_fundamentals | /Lists_Advanced-Exercise/Moving-Target.py | 1,466 | 3.65625 | 4 | target = input().split(" ")
targets = []
for num in target:
targets.append(int(num))
def shot(index, amount):
targets[index] -= amount
if targets[index] <= 0:
targets.pop(index)
def add(index, amount):
targets.insert(index, amount)
def strike(targets1, start, end):
del targets1[start: end + 1]
return targets1
def execute(command):
global targets
current = command.split(" ")
if current[0] == "Shoot":
index = int(current[1])
amount = int(current[2])
if 0 <= index < len(targets):
shot(index, amount)
elif current[0] == "Add":
index = int(current[1])
amount = int(current[2])
if 0 <= index < len(targets):
add(index, amount)
else:
print("Invalid placement!")
elif current[0] == "Strike":
index = int(current[1])
amount = int(current[2])
start = index-amount
end = index+amount
if 0 <= start and end < len(targets):
targets = strike(targets, start, end)
else:
print("Strike missed!")
while True:
command = input()
if command == "End":
final = []
for num in targets:
final.append(num)
final.append("|")
final.pop(len(final) - 1)
string = ""
for numerino in final:
string +=str(numerino)
print(string)
break
else:
execute(command) |
25ea185517d7e6db75c2314af720fcf578a1904b | udhayprakash/PythonMaterial | /python3/07_Functions/practical/display_number_pattern.py | 1,103 | 4 | 4 | #!/usr/bin/python
"""
Purpose: For input of two numbers(say (3,2)), to display number as below:
07 09 11
03 05
01
01
03 05
07 09 11
"""
def get_count(m):
if m == 1:
return 1
return m + get_count(m - 1)
def series(_count):
numbers = [1]
while len(numbers) < _count:
numbers.append(numbers[-1] + 2)
return numbers
if __name__ == "__main__":
upSeries, downSeries = 9, 8
maxValue = max(upSeries, downSeries) # 9
count = get_count(maxValue) # 9 + 8 +.. + 1 = 45
numbersList = series(count) # 45 odd numbers
numberSeries = []
for i in range(1, maxValue + 1):
numberSeries.append(numbersList[:i])
del numbersList[:i]
print("FINAL OUTPUT")
maxLen = upSeries # len(numberSeries[::-1][:upSeries][0])
for indx, num in enumerate(numberSeries[::-1]): # numberSeries[::-1][:upSeries])
print(" " * indx, " ".join([str(i).zfill(2) for i in num]))
for num in numberSeries[: downSeries + 1]:
print(" " * indx, " ".join([str(i).zfill(2) for i in num]))
indx -= 1
|
52129d3b1b427f4c7a06d9c4a47743409259b551 | abenetsol/holbertonschool-higher_level_programming | /0x11-python-network_1/7-error_code.py | 387 | 3.546875 | 4 | #!/usr/bin/python3
"""
Takes in a URL, sends a requestt to the URL and displays the value of
the variable X-Request-Id in the response header
"""
if __name__ == "__main__":
import requests
from sys import argv
status = requests.get(argv[1]).status_code
if status >= 400:
print("Error code: {}".format(status))
else:
print(requests.get(argv[1]).text)
|
34c65468a5d296eec44a830480f5740bc680b3cb | kirigaine/Socket-Squares | /game_functions.py | 2,116 | 3.59375 | 4 | import sys
import pygame
def check_events(screen, square):
"""Respond to keypresses and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
print("justquit")
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, square)
elif event.type == pygame.KEYUP:
check_keyup_events(event, square)
def update_screen(screen, squares, player_squares):
"""Update images on the screen and flip to the new screen"""
# Move the player's local square
squares.update()
# Reset screen to black
screen.fill((0,0,0))
# Iterate through player_squares and draw all players
for squa in player_squares:
if squa is not None and squa.player_id != squares.player_id:
squa.screen = screen
squa.update()
squa.draw()
squares.draw()
# Make the most recently drawn screen visible
pygame.display.flip()
def check_keydown_events(event, square):
"""Respond to keypresses"""
if event.key == pygame.K_ESCAPE:
print("escape")
sys.exit()
# Move Up
elif event.key == pygame.K_UP or event.key == pygame.K_w:
square.y_velocity -= 3
# Move Down
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
square.y_velocity += 3
# Move Right
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
square.h_velocity += 3
# Move Left
elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
square.h_velocity -= 3
def check_keyup_events(event, square):
"""Respond to key releases"""
# Stop Move Up
if event.key == pygame.K_UP or event.key == pygame.K_w:
square.y_velocity += 3
# Stop Move Down
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
square.y_velocity -= 3
# Stop Move Right
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
square.h_velocity -= 3
# Stop Move Left
elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
square.h_velocity += 3
|
9ce77f3839329e00497c6b488cb7c7b837c04650 | gedrex/PyLadies | /06/piskvorky/piskvorky.py | 2,651 | 3.515625 | 4 | #!/usr/bin/python3.4
from random import randint, randrange, sample
from glib import input_control
from ai import tah_pocitace
def starter():
"""
starter(None) - losuje nahodne ze 3 cisel. Pokud ho uzivatel uhadne, vraci True, pokud ne, vraci False.
"""
random_number = randrange(1,4)
user_choice = input_control('i', 'Počítač vylosoval náhodně číslo od 1 do 3. Když ho uhodneš, hraješ první. \n Tvoje volba?: ', 1,3)
if user_choice == random_number:
print('Uhodls, začínáš!')
return True
else:
print('Začíná počítač.')
return False
def evaluate(game_table, user_char, pc_char, free_positions):
"""
evaluate(game_table, user_char, pc_char, free_positions)
vyhodnocuje, zda existuje vitez. Vraci True, pokud existuje vitez(3 znaky v rade) -> vraci znak vitezneho hrace, nebo pokud uz nejsou volna pole -> vraci '!'. Jinak vraci False
game_table = retezec herniho pole
user_char = znak hrace
pc_char = znak pocitace
free_positions=[volna pole]
"""
if (user_char*3) in game_table:
return user_char
elif (pc_char*3) in game_table:
return pc_char
elif len(free_positions) < 1:
return '!'
else:
return False
def player_turn(game_table, played_number, player_char, free_positions):
"""
player_turn(game_table, played_number, player_char, free_positions)
Meni pismenka v hracim poli dle tahu hrace nebo pocitace turn('herni pole', cislo zvolene hracem -> int,'hracuv znak', [volna pole] )
"""
#vymaze z volnych poli prave zahranou pozici
del free_positions[free_positions.index(played_number)]
played_number = played_number + 1
if played_number < 1:
return player_char + game_table[0:]
else:
return game_table[:played_number-1] + player_char + game_table[played_number:]
def man_turn(game_table, game_table_char, user_char, free_positions):
"""
man_turn(game_table, game_table_char, user_char, free_positions)
-- man_turn('hraci pole', 'znk volneho hraciho pole', 'znak hrace - cloveka', [volne pozice])
pomoci funkce player_turn vrati hraci pole se zaznamenanym tahem lidskeho hrace
"""
while True:
try:
user_number = int(input('Hraj číslo od 20: '))-1
except ValueError:
print('Hraj číslo od 20, které tam ještě není: ')
else:
if user_number not in free_positions:
print('Číslo je mimo zadané rozmezí nebo uz tam neco je')
else:
return player_turn(game_table, user_number, user_char, free_positions)
|
d8aceae1dd4f7f895ed7e8d82cca6e09f63ac023 | sabastar/Python | /ExamStats.py | 1,541 | 4.375 | 4 | # MINI PROJECT: Create a program to compute stats
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
# Write a function to print out the list of grades, one element at a time
def print_grades(grades_input):
#iterate through list and print each item on its own line
for i in grades_input:
print i
print_grades(grades)
# Create another function to compute the sum of all the test grades - without using SUM function
def grades_sum(grades):
total = 0
for i in grades:
total+= i
return total
print grades_sum(grades)
# Use grades_sum to calculate the AVERAGE test grade
def grades_average(grades_input):
gsum=grades_sum(grades_input)
return grades_sum(grades_input)/float(len(grades_input))
print grades_average(grades)
# Variance - how grades varied against the average (smaller = closer to average)
def grades_variance(scores):
average= grades_average(scores)
variance=0 # rolling sum
for score in scores: #compute its squared difference
variance+= (average-score)**2
return variance/len(scores)
print grades_variance(grades)
# Standard Deviation - square root of the variance, can calculate square root by raising the number to the one-half power
def grades_std_deviation(variance):
return variance **0.5
variance = grades_variance(grades)
print grades_std_deviation(variance)
# Print out the stats
print print_grades(grades)
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades)
print grades_std_deviation(grades_variance(grades))
|
0b8ce43c489daba2fd691bf798458488fbaf1250 | aayushi-droid/Python-Thunder | /Solutions/oddishVsEvenish.py | 625 | 4.03125 | 4 | import sys
from functools import reduce
"""
Probem Task: Create a function that determines whether a number is Oddish or Evenish.
A number is Oddish if the sum of all of its digits is odd, and a number is Evenish if the
sum of all of its digits is even. If a number is Oddish, return "Oddish".
Otherwise, return "Evenish".
Problem Link: https://edabit.com/challenge/r6TSNwkLZ2DgsoKiH
"""
def main(number):
result_map = ["Evenish", "Oddish"]
total = reduce(lambda x, y: x + int(y), str(number), 0)
return result_map[total%2]
if __name__ == "__main__":
print(main(int(sys.argv[1])))
|
c2ec0d7efe726145fa9efcb8c2315ef4e1e64079 | manhtung2111/Homework_write_in_Class_type | /4.py | 330 | 3.796875 | 4 | class triangle:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
s = (self.a + self.b + self.c) / 2
area_count = (s*(s - self.a)*(s - self.b)*(s - self.c)) ** 0.5
print("dien tich hinh tam giac la:",area_count)
num = triangle(3, 4, 5)
num.area() |
2f5fdb8b1d2754e8c1a67ee896170cf011efd139 | dulceadelina/criba | /main.py | 1,407 | 4.03125 | 4 | # Programa que implementa la criba de Erastótenes
# donde define los números primos de 2 hasta n
# Dulce Adelina Zuñiga Ramos
# 20/09/2020 - 21/09/2020
from math import isqrt
# here implements sieve of Eratosthenes and receives n
def sieve(): # criba in english
n = data() # ask for n
while n < 2: # beeing n a positive number
n = data()
criba = [] # 1st step
for i in range(0, n-1): # build a n-length array
criba.append(i+2) # 2nd step: fill from 2 till n
primes = [] # step three: take the first prime number
for i in range(2, isqrt(n)): # iterates from 2 until square root of n
if criba[i-2] != 0: # if the number isn't marked
primes.append(criba[i-2]) # it takes as prime
for j in range(0, n-1): # iterate criba list
if criba[j] % i == 0: # if it's multiple of a prime number
criba[j] = 0 # mark with zero
for c in criba: # the rest are primes
if c != 0:
primes.append(c)
for i in range(0, len(primes)):
if i % 10 == 0:
print('')
print(primes[i], end='\t')
# function that asks for the input, in this case: n
def data():
n = int(input("Ingrese n: "))
return n
if __name__ == '__main__':
sieve()
print('')
|
c904b236955c6ba88cf9d0533acf38f52898a722 | koilhyuk/Algorithm | /src/baekjoon/bronze/haknum_1_2754.py | 348 | 3.625 | 4 | score = input()
result =0
if score[:1] == "A":
result+=4
elif score[:1] == "B":
result+=3
elif score[:1] == "C":
result+=2
elif score[:1] == "D":
result+=1
else:
result+=0.0
if score[1:] =="+":
result+=0.3
elif score[1:] =="0":
result+=0.0
elif score[1:] =="-":
result-=0.3
else:
result+=0.0
print(result)
|
65263231684173318bd0f685269efcf3307dd924 | arslan21/pythonworld-tasks | /pythonworld_test_square.py | 745 | 3.859375 | 4 | # расчет площади, периметра и диаганали по стороне квадрата
import math
def square(a):
per = a * 4
sq = math.pow(a, 2)
dia = math.hypot(a, a)
return(per, sq, dia)
import unittest
class SquareTestCase(unittest.TestCase):
def test_square(self):
for a in range(10):
with self.subTest(a=a):
self.assertCountEqual(
# Избегаем проблемы с числами с плавающей точкой
list(map(lambda x: round(x, 7), square(a))),
list(map(lambda x: round(x, 7), [4*a, a**2, a*math.sqrt(2)]))
)
if __name__ == "__main__":
unittest.main()
|
d0fa4e17039d48cb0800608ba79d3f1ec817531a | KristjanVeensalu/Omis_Python_EN | /Week 1/firstFIle.py | 1,505 | 4.21875 | 4 | #This is a comment
'''print("Hello world!")
print(5)
print(5+5)
print("Testing if this works" + "5")
print(10*2-15)'''
'''MyFirstVariable = 10
print(MyFirstVariable)
MySecondVariable = "This is my variable"
print(MySecondVariable)
MySecondVariable = 20
print(MySecondVariable)'''
'''
firstSide = 10
print(firstSide*firstSide)
triangleSide= 20
height = 15
print("The plane of this triangle is:")
print(triangleSide*height/2)
if height<20:
print("That height is small")
if height>500:
print("That is very high")
UserInput=int(input("What is your input? "))
if UserInput<20:
print("That is a small input")
if UserInput>20:
print("That is a big input")'''
FirstBooleanVariable = True
if FirstBooleanVariable:
print("Our boolean works!")
'''Write a piece of code, that asks for user input. If that Input,divided by 4
and multiplied by 10, is still smaller than 1000. Then print out the value of the
remaining variable number'''
'''Find out if this number is divisible by 4 but not by 100'''
UserSecondInput = int(input("Enter your number "))
if UserSecondInput % 4 == 0:
print("Is divisible by 4!")
if UserSecondInput % 100 != 0:
print("This is the value!")
'''
Write a program that asks the user which geometrical shape they wish to calculate with. (Triangle, square, rectangle)
After the user has responded, depending on the shape, ask for the length of all required sides to calculate the area and
circumference of said shape. Return those values.''' |
c236a321425fe774f79315332f875ab2ded96f27 | darekj28/free-algos | /4_graphs/edge.py | 702 | 3.5625 | 4 |
class Edge:
# initializes an edge between vertices v and w with a certain edge-weight
def __init__(self, v, w, weight):
self._v = v
self._w = w
self._weight = weight
# returns the weight of this edge
def weight(self):
return self._weight
# returns either vertex in this edge
def either(self):
return self._v
# returns the other vertex in this edge
def other(self, v):
if v == self._v:
return self._w
else:
return self._v
# compares to another edge's weight
def __cmp__(self, other_edge):
return self.weight() > other_edge.weight()
def __repr__(self):
return str((self._v, self._w, self._weight)) |
7086d5af6707d1d130361de588ebe98fd7b2c713 | aaronshang/TDDDemo | /pythonNotes/readTextFile.py | 303 | 3.578125 | 4 | #!/usr/bin/python
#set filename
fname = '/Users/teso/Desktop/make.txt'
#attempt to open file for reading
try:
fobj=open(fname,'r')
except IOError,e:
print '***file open error:',e
else:
#display content to the screen
for eachline in fobj:
print eachline,
//finally close file
fobj.close() |
1a397059ea44c3a0b11c1362e5a029ba0fc94ba0 | Tolianych/Main | /Python/EPAM2/WordLetterCounter/WordLetterCounter.py | 703 | 3.703125 | 4 | '''
Created on Jan 20, 2015
@author: s.botyan
'''
text_file = open("something.txt")
text = text_file.read()
list_strings = text.splitlines()
count_dict = {}
for string in list_strings:
list_words = string.split(" ")
for word in list_words:
# filtering all symbols except alphabet
letters_count = len(filter(lambda x: x.isalpha(), word))
if letters_count == 0:
break
# number of occurrences of letters_count into the dictionary
qty = count_dict.get(letters_count, 0) + 1
pair_length_count = {letters_count: qty}
count_dict.update(pair_length_count)
for pair in count_dict:
print "%s - %s" % (pair, count_dict[pair])
|
df8815674ea43ed5f815a4084fe372438765328f | akshaypawar4325/Python | /6.Dictionary_Mandar_sir_technique.py | 181 | 3.921875 | 4 | D1={1:['MANDAR',{'HINDI':56,'ENG':70}]}
print(D1)
d2=D1[1][1]
print(d2)
marks=[]
for key in d2:
marks.append(d2[key])
print(marks)
highest=max(marks)
print(highest)
|
f0c0eafa0f7da1f6bd8975b3ec91805d8c8bea28 | harmanbirdi/python | /1app/tree.py | 2,826 | 4.03125 | 4 | #!/usr/bin/env python
#
# Description : Print the directory tree of a given directory using any scripting language
# (i.e. anything *except* for a Bash script or a plain shell command).
# More Info : Asked by Nour for 1app phone screen interview
# __author__ : Harman Birdi
# Date : Sep 16, 2016
#
import os
import sys
from colors import Colors
from optparse import OptionParser
class Tree:
"""
Tree class to print out a directory structure. It also prints out the contents of
text (.txt) files by default unless a different extension is provided and file is
of ASCII type.
"""
depth = 1 # The depth of the tree
def __init__(self):
pass
def process_tree(self, dname, extn='txt', func=None):
"""
This method processes the directory recursively and prints out all files that
match extension type of files.
:param dname:
:param extn:
:param func:
An optional function can be passed in for processing a file that can utilize the following
keyword parameters.
full_path: Full path to the file
depth: The tree depth at which this file was found
extn: Extension of the file, in case matches need to be done against a particular type of file
separator: Spacing needed to preserve padded output, if needed
:return:
"""
dirlist = os.listdir(dname)
separator = ' '
if dirlist:
for fle in dirlist:
full_path = os.path.join(dname, fle)
if fle.startswith('.'): # Ignore hidden files and directories
continue
elif os.path.isdir(full_path):
print separator * Tree.depth,
print Colors.HEADER + "%s/" % fle + Colors.ENDC
Tree.depth += 1
self.process_tree(full_path, extn, func)
elif os.path.isfile(full_path):
print separator * Tree.depth,
print Colors.OKBLUE + "%s" % fle + Colors.ENDC
if func is not None:
func(full_path=full_path, depth=Tree.depth, extn=extn, separator=separator)
Tree.depth -= 1
return
# Main starts here
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-d", "--dir", dest="dirname", help="Directory name for tree", metavar="DIR")
(options, args) = parser.parse_args()
if options.dirname is None:
err = Colors.FAIL + ' Dirname argument cannot be empty.\n'
err += ' Use -h flag for additional help.\n' + Colors.ENDC
sys.stderr.write(err)
exit(1)
dirname = options.dirname
tree = Tree()
tree.process_tree(dirname)
|
519be51464b3b72af181b386a6f0ec760d315252 | M1c17/ICS_and_Programming_Using_Python | /Week2_Simple_Programs/Lecture_2/Ex-isInString-recursive.py | 1,388 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 4 12:02:14 2019
@author: MASTER
"""
# DETERMINE IF A CHAR IS IN A STR
# use bisection search
# string is sorted in alphabetical order
# base case: empty str
# base case: len 1
# Base case: test the midcha of aStr against the cha you're looking
# for same = True
# slice string to have the midcha before recursive
# recursive case: elif test cha < midcha if so consider the lower half
#of the str
# recursive case: else otherwise consider the upper half of the str
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Base case when the str is empty
if aStr == '':
return False
# Base case when len is of length 1
if len(aStr) == 1 :
return aStr == char
# Base case when the test cha = midchar
midIndex = len(aStr)//2
midchar = aStr[midIndex]
if char == midchar:
return True
# Recursive case: If the test character is smaller than the middle
# character, recursively search on the first half of aStr
elif char < midchar:
return isIn(char, aStr[:midIndex -1])
#Recursive case: else consider the last half of aStr
else:
return isIn(char, aStr[midIndex + 1:])
print(isIn('c','abc'))
|
f919de5bfb2253436cf3c0d7dcfe6c3556e5838c | Spraynard/Card-Game-Suite | /Modules/Cards/Card.py | 1,965 | 3.703125 | 4 | def cardRankToNum(rank, variant = None):
if not variant:
if rank == "Ace":
return 14
elif rank == "King":
return 13
elif rank == "Queen":
return 12
elif rank == "Jack":
return 11
else:
return int(rank)
elif variant == "blackjack":
if (rank == "Jack" or rank == "Queen" or rank == "King"):
return 10
else:
return int(rank)
def cardSuitRank(suit):
if suit == "Diamonds":
return 0
elif suit == "Hearts":
return 1
elif suit == "Clubs":
return 2
elif suit == "Spades":
return 3
class Card(object):
""" Card class, which gives all the behavior of the card object. Takes in a rank (e.g. 2 - Ace) and a
suit (e.g. "Spades", "Clubs") and makes a card object off of that with those values
"""
def __init__(self, rank = None, suit = None, variant = None):
self.rank = str(rank)
self.suit = suit
self.variant = variant
self.acceptDict = {
'suits' : ["Clubs", "Spades", "Diamonds", "Hearts"],
'ranks' : ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
}
def __eq__(self, other):
if not self or not other:
return None
return (self.rank == other.rank) and (self.suit == other.suit)
def isSameRank(self, other):
return self.rank == other.rank
def __lt__(self, other):
c1 = cardSuitRank(self.suit), cardRankToNum(self.rank)
c2 = cardSuitRank(other.suit), cardRankToNum(other.rank)
return c1 < c2
def __gt__(self, other):
c1 = cardSuitRank(self.suit), cardRankToNum(self.rank)
c2 = cardSuitRank(other.suit), cardRankToNum(other.rank)
return c1 > c2
def __repr__(self):
return "Card(" + str(self.rank) + ", " + str(self.suit) + ")"
def __str__(self):
return self.rank + " of " + self.suit
def cardSuitToNum(suit):
pass
def getAcceptDict(self):
return self.acceptDict
def getRank(self):
return self.rank
def acceptableRank(self):
return self.getRank() in self.getAcceptDict()['ranks']
def getSuit(self):
return self.suit |
8768267d8f35dc3333325a24b5ed0522e1a55609 | vacuum136/CppND-Capstone | /unit2_pp/scripts/unit2_exercise.py | 2,874 | 3.859375 | 4 | #! /usr/bin/env python
"""
Dijkstra's algorithm path planning exercise
Author: Roberto Zegers R.
Copyright: Copyright (c) 2020, Roberto Zegers R.
License: BSD-3-Clause
Date: Nov 30, 2020
Usage: roslaunch unit2_pp unit2_exercise.launch
"""
import rospy
def find_neighbors(index, width, height, costmap, orthogonal_step_cost):
"""
Identifies neighbor nodes inspecting the 8 adjacent neighbors
Checks if neighbor is inside the map boundaries and if is not an obstacle according to a threshold
Returns a list with valid neighbour nodes as [index, step_cost] pairs
"""
neighbors = []
# length of diagonal = length of one side by the square root of 2 (1.41421)
diagonal_step_cost = orthogonal_step_cost * 1.41421
# threshold value used to reject neighbor nodes as they are considered as obstacles [1-254]
lethal_cost = 1
upper = index - width
if upper > 0:
if costmap[upper] < lethal_cost:
step_cost = orthogonal_step_cost + costmap[upper]/255
neighbors.append([upper, step_cost])
left = index - 1
if left % width > 0:
if costmap[left] < lethal_cost:
step_cost = orthogonal_step_cost + costmap[left]/255
neighbors.append([left, step_cost])
upper_left = index - width - 1
if upper_left > 0 and upper_left % width > 0:
if costmap[upper_left] < lethal_cost:
step_cost = diagonal_step_cost + costmap[upper_left]/255
neighbors.append([index - width - 1, step_cost])
upper_right = index - width + 1
if upper_right > 0 and (upper_right) % width != (width - 1):
if costmap[upper_right] < lethal_cost:
step_cost = diagonal_step_cost + costmap[upper_right]/255
neighbors.append([upper_right, step_cost])
right = index + 1
if right % width != (width + 1):
if costmap[right] < lethal_cost:
step_cost = orthogonal_step_cost + costmap[right]/255
neighbors.append([right, step_cost])
lower_left = index + width - 1
if lower_left < height * width and lower_left % width != 0:
if costmap[lower_left] < lethal_cost:
step_cost = diagonal_step_cost + costmap[lower_left]/255
neighbors.append([lower_left, step_cost])
lower = index + width
if lower <= height * width:
if costmap[lower] < lethal_cost:
step_cost = orthogonal_step_cost + costmap[lower]/255
neighbors.append([lower, step_cost])
lower_right = index + width + 1
if (lower_right) <= height * width and lower_right % width != (width - 1):
if costmap[lower_right] < lethal_cost:
step_cost = diagonal_step_cost + costmap[lower_right]/255
neighbors.append([lower_right, step_cost])
return neighbors
def dijkstra(start_index, goal_index, width, height, costmap, resolution, origin, grid_viz = None):
'''
Performs Dijkstra's shortes path algorithm search on a costmap with a given start and goal node
'''
#### To-do: complete all exercises below ####
pass
|
f75b5b23f4f3c5210fa5026d993f5c2cc4c4462d | lenniecottrell/Python-Projects | /End_of_course_Challenges/Database_and_Python_Challenge.py | 886 | 3.65625 | 4 | import sqlite3
from sqlite3 import *
rosterValues = (('Jean-Baptiste Zorg', 'Human', 122), ('Korben Dallas', 'Meat Popsicle', 100), ('Ak\'not', 'Mangalore', -5))
with sqlite3.connect(':memory:') as connection:
conn = connection.cursor()
conn.execute("CREATE TABLE IF NOT EXISTS Roster(Name TEXT, Species TEXT, IQ TEXT)")
conn.executemany("INSERT INTO Roster VALUES (?,?,?)", rosterValues)
connection.commit()
## conn.execute("SELECT * FROM Roster")
## for row in conn.fetchall():
## print(row)
conn.execute("UPDATE Roster SET Species=? WHERE Name=?", ('Human', 'Korben Dallas'))
## conn.execute("SELECT * FROM Roster")
## for row in conn.fetchall():
## print(row)
conn.execute("SELECT Name, IQ FROM Roster WHERE Species = 'Human'")
while True:
row = conn.fetchone()
if row is None:
break
print(row)
|
41777bdaf9e9f942d3b50f13fd9c7f47c289c943 | ink-water/ink | /git_test/test03.py | 1,970 | 3.53125 | 4 | import pymysql
class Database:
def __init__(self):
self.db = pymysql.connect(password="123456", database="client", user="root", charset="utf8")
self.cur = self.db.cursor()
def register(self):
print("按回车键退出注册界面")
while True:
name = input("请输入用户名:")
if not name:
break
password = input("请输入密码:")
if not password:
break
try:
self.cur.execute("insert into user_info(uname,password) values(%s,%s)", [name, password])
self.db.commit()
print("用户" + name + "注册成功")
break
except:
print("用户名重复,请重新输入")
self.db.rollback()
def login_in(self):
print("按回车键退出登录界面")
while True:
name = input("请输入用户名:")
if not name:
break
password = input("请输入密码:")
if not password:
break
try:
self.cur.execute("select * from user_info where uname=%s and password=%s", [name, password])
except Exception as e:
print(e)
# print(cur)
if self.cur.fetchone():
print("欢迎" + name + "回来")
else:
print("用户名或者密码错误,请重新输入")
def choose(self):
while True:
item = input("登录请按1,注册请按2,其余任意键退出")
if item == "1":
self.login_in()
elif item == "2":
self.register()
else:
break
def main(self):
self.choose()
self.cur.close()
self.db.close()
if __name__ == '__main__':
database = Database()
database.main()
|
519706178836f17c408507ff1cc16e67e8a9ac5b | kirankumar2/BridgeLabz | /new/week1/Alogrith/primanagra.py | 571 | 3.765625 | 4 | from collections import Counter
num = []
def findPrime(n1, n2) :
for x in range(n1, n2) :
if x > 1 :
for n in range(2, x) :
if (x % n) == 0 :
break
else :
print(x)
num.append(x)
start = 0
end = 1000
findPrime(start, end)
def findAnagram(s1):
# Counter() returns a dictionary data
for i in range(len(s1)) :
if Counter(i) == Counter(i + 1) :
print("! anagram")
else :
print(": are not anagram")
findAnagram(num)
|
d9b74105e328ebeabc983824d11c70a8ce02280c | sethdeane16/projecteuler | /037.py | 968 | 3.703125 | 4 | import resources.pef as pef
import time
"""
https://projecteuler.net/problem=37
4.08533501625061
"""
def main():
total = 0
num_found = 0
primes = pef.prime_sieve(999999)
for i in primes[4:]:
count = 0
# determine amount to remove from each end
for d in range(len(str(i))):
# check if the shortened numbers are prime
if pef.is_prime(int(str(i)[d::])) and pef.is_prime(int(str(i)[0:d+1])):
count += 1
# if removing from both ends gave expected result
if count == len(str(i)):
# print(str(i) + " IS A TRUNCATABLE PRIME")
num_found += 1
total += i
# a known stopping condition is when we find 11 such primes
if num_found == 11:
break
return total
if __name__ == "__main__":
start_time = time.time()
answer = main()
end_time = time.time()
pef.answer(answer, end_time - start_time)
|
e72be975da543ee3a16bb030a7ff0bcd0e65415d | brjoaogabriel/disparador_email | /functions/abrevia_sobrenomes.py | 758 | 3.578125 | 4 | from log_paste.log_funções import PrintarLogFunção;
#Para cada nome que estiver dentro de sobrenomes, abrevia.
#Exemplo: "João Gabriel Maciel" se torna "João Gabriel M."
Caminho = "disparador_email.functions.abrevia_sobrenomes.py";
def AbreviarSobrenomes(NomeCompleto, Sobrenomes):
try:
Nome: str;
for Nome in NomeCompleto:
if Nome in Sobrenomes and len(Nome) >= 3:
Nome = upper(Nome[:1]) + ".";
for Palavra in Nome:
Nomes += Palavra;
Palavra = None;
Nome = None;
PrintarLogFunção(True, Caminho, "Função AbreviarSobrenomes");
return Nomes;
except:
PrintarLogFunção(False, Caminho, "Função AbreviarSobrenomes");
return f"ERRO - {Caminho}"; |
a4ff8e9ed2dafbbc8c81b044322378f3a86d0af5 | dgpllc/leetcode-python | /learnpythonthehardway/range-module-715.py | 4,879 | 3.875 | 4 | # A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following
# interfaces in an efficient manner.
#
# addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that
# interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the
# interval [left, right) that are not already tracked.
# queryRange(int left, int right) Returns true if and only if every real number in the interval [left,
# right) is currently being tracked.
# removeRange(int left, int right) Stops tracking every real number currently being tracked in the interval [left,
# right).
# Example 1:
# addRange(10, 20): null
# removeRange(14, 16): null
# queryRange(10, 14): true (Every number in [10, 14) is being tracked)
# queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)
# queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation)
# Note:
#
# A half open interval [left, right) denotes all real numbers left <= x < right.
# 0 < left < right < 10^9 in all calls to addRange, queryRange, removeRange.
# The total number of calls to addRange in a single test case is at most 1000.
# The total number of calls to queryRange in a single test case is at most 5000.
# The total number of calls to removeRange in a single test case is at most 1000.
import bisect
class RangeModule(object):
def __init__(self):
self._ranges = []
def addRange(self, left, right):
"""
:type left: int
:type right: int
:rtype: void
"""
arr = []
indx = bisect.bisect(self._ranges, (left, right))
i = indx
if indx and left <= self._ranges[indx - 1][1]:
left = self._ranges[indx - 1][0]
arr += self._ranges[:indx - 1]
if right <= self._ranges[indx - 1][1]:
right = self._ranges[indx - 1][1]
else:
arr += self._ranges[:indx]
while i < len(self._ranges) and right >= self._ranges[i][0]:
right = max(right, self._ranges[i][1])
i += 1
arr += [(left, right)] + self._ranges[i:]
self._ranges = arr
def queryRange(self, left, right):
"""
:type left: int
:type right: int
:rtype: bool
"""
for start, end in self._ranges:
if left >= start and right <= end:
return True
return False
def removeRange(self, left, right):
"""
:type left: int
:type right: int
:rtype: void
"""
arr = []
if not len(self._ranges):
return
indx = bisect.bisect(self._ranges, (left, right))
i = indx
if indx == len(self._ranges) and left > self._ranges[-1][1]:
return
if indx == 0 and right <= self._ranges[0][0]:
return
if indx and left < self._ranges[indx - 1][1]:
arr += self._ranges[:indx - 1]
arr += (self._ranges[indx - 1][0], left),
if right < self._ranges[indx - 1][1]:
arr += (right, self._ranges[indx - 1][1]),
else:
arr += self._ranges[:indx]
while i < len(self._ranges) and right > self._ranges[i][0]:
i += 1
if i == len(self._ranges):
if right < self._ranges[i - 1][1]:
arr.append((right, self._ranges[i - 1][1]))
self._ranges = arr
return
# [(1, 4), (8, 9), (17, 21), (23, 46), (47, 50), (51, 63), (95, 98)]
# remove(26, 64)
# [(1, 4), (8, 9), (17, 21), (23, 26), (64, 63), (95, 98)]
if i > indx and right < self._ranges[i - 1][1]:
arr += [(right, self._ranges[i - 1][1])]
arr += self._ranges[i:]
self._ranges = arr
# Your RangeModule object will be instantiated and called as such:
# obj = RangeModule()
# obj.addRange(left,right)
# param_2 = obj.queryRange(left,right)
# obj.removeRange(left,right)
if __name__ == '__main__':
rm = RangeModule()
rm.addRange(5, 9)
# rm.addRange(17, 21)
print rm._ranges
# rm.addRange(17, 21)
# print rm._ranges
rm.removeRange(6, 7)
print rm._ranges
# rm.removeRange(62, 96)
rm.removeRange(34, 83)
print rm._ranges
# rm.removeRange(2, 4)
#
# rm.addRange(6, 8)
# print rm._ranges
#
# rm.removeRange(7, 8)
# print rm._ranges
#
# rm.removeRange(8, 9)
# print rm._ranges
#
# rm.addRange(8, 9)
# print rm._ranges
#
# rm.removeRange(1, 3)
# print rm._ranges
#
# rm.addRange(1, 8)
# print rm._ranges
#
# print rm.queryRange(2, 4)
#
# print rm.queryRange(2, 9)
#
# print rm.queryRange(4, 6)
|
0dc1664c45ef391b95b1496d64c82a5024f0696e | MiroVatov/Python-SoftUni | /Python Fundamentals 2020 - 2021/Final Exams Practice/01. String Manipulator.py | 1,276 | 3.84375 | 4 | initial_string = input()
while True:
command = input()
if command == 'End':
break
token = command.split()
action = token[0]
if action == 'Translate':
char = token[1]
replacement = token[2]
if char in initial_string:
initial_string = initial_string.replace(char, replacement)
print(initial_string)
elif action == 'Includes':
text = token[1]
if text in initial_string:
print('True')
else:
print('False')
elif action == 'Start':
text = token[1]
if initial_string.startswith(text):
print('True')
else:
print('False')
elif action == 'Lowercase':
initial_string = initial_string.lower()
print(initial_string)
elif action == 'FindIndex':
char = token[1]
last_index_of_char = initial_string.rindex(char)
print(last_index_of_char)
elif action == 'Remove':
start_index = int(token[1])
count = int(token[2])
first_part = initial_string[:start_index]
final_part = initial_string[start_index+count::]
initial_string = first_part + final_part
print(initial_string) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.