blob_id
stringlengths 40
40
| repo_name
stringlengths 5
119
| path
stringlengths 2
424
| length_bytes
int64 36
888k
| score
float64 3.5
5.22
| int_score
int64 4
5
| text
stringlengths 27
888k
|
---|---|---|---|---|---|---|
d7c8393176e4c9bb51dfec73e9c3097e39b7af8c | SuperTrampAI/Chapters | /Chapter4process.py | 1,615 | 3.671875 | 4 | # __author__ = '[email protected]'
# __fileName__='Chapters Chapter4-process'
# __create_data__='2020/1/5 18:47'
# 各类语句
# if语句
x = 1#int(input("Please enter an integer:"))
if x<0:
x=0
print("Negative changed to zero")
elif x ==0:
print("Zero")
elif x == 1:
print("One")
else:
print("More")
y= 'y' #input("输入姓名:")
if y=='x':
print("该用户存在:"+y)
elif y=='y':
print("该用户存在,欢迎VIP:"+y)
else:
print("查证你的用户再操作")
# for循环
text=['cat','window','defenestrate']
for t in text:
print(t,len(t),end='==')
for t in text[:]: # 如果text[:]写成text,程序无法停止
if len(t)>6:
text.insert(0,t)
print()
print(text)
# 遍历一个数字序列
for i in range(10):
print(i,end=",")
# range() 多参数用法:
# range(5,10) 从5开始到10截止
# range(1,20,3) 从1开始到20截止,以三步进
# enumerate()
print()
print(list(range(10)))
for n in range(2,10):
for x in range(2,n):
if n%x==0:
print(n,'equals',x,'*',n//x)
break
else:
print(n,'is a prime number')
for num in range(0,10):
if num%2==0:
print("取余为零:",num)
continue
else:
print("取余非零:",num)
#pass 语句 该语句什么也不做。在语法上需要一个语句,但程序需要什么动作也不做时,可以使用
# 通常用于创建最小的类 另一个使用场景:在你编写新代码时,可以作为一个函数或条件子句体的占位符
# 可以让你保持更抽象的层次上进行思考
#while True:
# pass
a=add
|
b811a7cd39743581b839c6331a965e641023d611 | Wuhuaxing2017/spider_notes | /day04/code/5-xpath-book.py | 1,157 | 3.53125 | 4 | from lxml import etree
books = '''
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2008</year>
<price>30.00</price>
</book>
<book category="children" lang="zh">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
'''
books_tree = etree.HTML(books)
books = books_tree.xpath('//book[price<=30][year + 3 = 2008]')
print(books)
# 将查询到的book中的所有属性选出来
ret = books[0].xpath('.//@*')
print(ret) |
39f80532a18709f22a7006949e08f5eb4c89d1ab | Tomoka64/interview_preparation | /array_interview_questions/array_pair_sum/pair_sum.py | 951 | 3.609375 | 4 | from nose.tools import assert_equal
# my answer
def my_pair_sum(list, target):
if len(list) < 2:
return
ret = set()
for i in range(len(list)):
j = i + 1
while j < len(list):
if (list[i]+ list[j] == target):
if not (list[i], list[j]) in ret:
ret.add( ( min(list[i], list[j]), max(list[i], list[j]) ) )
j += 1
return len(ret)
# @Code-Hex これレベル高くね?↓
def pair_sum(arr,k):
counter = 0
lookup = set()
for num in arr:
if k-num in lookup:
counter+=1
else:
lookup.add(num)
return counter
class TestPair(object):
def test(self,sol):
assert_equal(sol([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6)
assert_equal(sol([1,2,3,1],3),1)
assert_equal(sol([1,3,2,2],4),2)
print('ALL TEST CASES PASSED')
t = TestPair()
t.test(pair_sum)
t.test(my_pair_sum)
|
69c14bd40a360e9bdd8518ba1859776687ba84d9 | ryhanlon/legendary-invention | /labs_Fundaments/dice.py | 763 | 4.28125 | 4 | """
This is a file written by Rebecca Hanlon.
Asks for the number of die and the number of sides then prints the result.
"""
import random
def roll_dice(dice, sides):
"""
Uses uses random to roll the die
:param dice: interger
:param sides: interger
:return: print the results
"""
for i in range(0, dice):
roll = random.randint(1, sides)
print(f"{dice} die with {sides} sides rolls: {roll}")
def ask_questions():
"""
Ask the user for how many of die and sides
:return: calls the roll_dice(dice, sides) function
"""
dice = int(input("How many die do you want? >> "))
sides = int(input("How many sides (3 sides or more) do you want? >> "))
roll_dice(dice, sides)
ask_questions()
|
6c8baaa84cad8a3c4b3f8620150182d535f43e69 | itsmonicalara/Coding | /HackerRank/30 Days of Coding/10Binary.py | 541 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def num_to_binary(num):
binary_list = []
current = 0
longest = 0
while int(num) > 0:
remainder = num % 2
num = num / 2
binary_list.insert(0, int(remainder))
for ele in binary_list:
if ele == 1:
current += 1
else:
longest = max(current, longest)
current = 0
print(max(current, longest))
if __name__ == '__main__':
n = int(input().strip())
num_to_binary(n)
|
3d8b6325ffb0d38486b2402c14320c3f2c40c26b | cotncndy/leetcode-python | /learnpythonthehardway/jump-game-ii.py | 902 | 3.796875 | 4 | # Time: O(n)
# Space: O(1)
#
# Given an array of non-negative integers, you are initially positioned at the first index of the array.
#
# Each element in the array represents your maximum jump length at that position.
#
# Your goal is to reach the last index in the minimum number of jumps.
#
# For example:
# Given array A = [2,3,1,1,4]
#
# The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
#
# not pass on leetcode because of time limit
class Solution:
# @param A, a list of integers
# @return an integer
def jump(self, A):
jump_count, last, cur = 0, 0, 0
for i in xrange(len(A)):
if i > last:
last, jump_count = cur, jump_count + 1
cur = max(cur, i + A[i])
return jump_count
if __name__ == '__main__':
print Solution().jump([2, 3, 1, 1, 4])
|
961f6907971736dff5d90d037130ed85c5380eb4 | rabahbedirina/UdacityPython | /Which Prize.py | 405 | 3.609375 | 4 | import random as rd
points = rd.randrange(1, 200)
if points <= 50:
result = "Woden Rabbit"
elif points <= 150:
result = "No Prize"
elif points <= 180:
result = "Wafer thin mint"
else:
result = "Penguin"
if result == "No Prize":
print("Oh dear, no prize this time.")
else:
print("Congratulations! \n Your Points {1} You won a {0}!".format(
result, points))
|
350b6dbf7e3e993365efdaf28015ad88c70a10d8 | matthewsgerling/Python_Class_Work | /ParamAndReturn/moreFunctions/validateInputsFunctions.py | 227 | 3.609375 | 4 | def scoreInput(name, score=0, invalidmessage='Invalid test score, try again!'):
while 0 >= int(score) >= 100:
score = input(invalidmessage)
return print(name, ': ', score)
if __name__ == '__main__':
pass
|
0698c804e5c160b939aabdd3b314414da8a6878e | R-Billington/practice-projects | /games-of-chance/games.py | 3,912 | 3.796875 | 4 | import random
money = 100
#Write your game of chance functions here
#Flips coin and returns winnings or losses
def coin_flip(guess, bet):
print('Flipping a coin...\n')
one_or_two = random.randint(1, 2)
if one_or_two == 1:
coin = 'Heads'
elif one_or_two == 2:
coin = 'Tails'
print(f'You called {guess} and bet £{str(bet)}...\n')
print(f'The coin landed on {coin}.\n')
if guess == coin:
print(f'You won £{str(bet)}!\n')
return bet
else:
print(f'You lost £{str(bet)}.\n')
return -bet
#Rolls two dice and lets player guess if total is odd or even
def cho_han(guess, bet):
print('Rolling two dice...\n')
roll_one = random.randint(1, 6)
print(f'The first dice rolled a {str(roll_one)}\n')
roll_two = random.randint(1, 6)
print(f'The second dice rolled a {str(roll_two)}\n')
total = roll_one + roll_two
if total % 2 == 0:
result = 'Even'
else:
result = 'Odd'
print(f'You guessed {guess} and bet £{str(bet)}...\n')
print(f'The dice totaled {str(total)}, an {result} number!\n')
if guess == result:
print(f'You won £{str(bet)}!\n')
return bet
else:
print(f'You lost £{str(bet)}.\n')
return -bet
#Simulates two cards being drawn from a deck, highest wins
def two_card_draw(bet):
print('Drawing two cards...\n')
print(f'You bet £{str(bet)}...\n')
deck = []
for i in range(2, 15):
deck.append(i)
deck.append(i)
deck.append(i)
deck.append(i)
player_card_num = deck[random.randint(0, 51)]
deck.remove(player_card_num)
opponent_card_num = deck[random.randint(0, 50)]
player_card = card_number_to_name(player_card_num)
opponent_card = card_number_to_name(opponent_card_num)
print(f'You drew a(n) {str(player_card)}\n')
print(f'Your opponent drew a(n) {str(opponent_card)}\n')
if player_card_num == opponent_card_num:
print('It\'s a draw!\n')
return 0
elif player_card_num > opponent_card_num:
print(f'You won £{str(bet)}!\n')
return bet
else:
print(f'You lost £{str(bet)}.\n')
return -bet
#Converts number to picture card name for card draw game
def card_number_to_name(card_number):
if card_number == 14:
return 'Ace'
elif card_number == 11:
return 'Jack'
elif card_number == 12:
return 'Queen'
elif card_number == 13:
return 'King'
else:
return card_number
#Roulette - guess a number or odd/even and returns winnings/losses
def roulette(guess, bet):
print('Spinning the roulette wheel...\n')
result = random.randint(0, 36)
if result % 2 == 0:
odd_or_even = 'Even'
else:
odd_or_even = 'Odd'
print('The wheel is spinning...\n')
print(f'It landed on a {str(result)}!\n')
if guess == 'Odd' or guess == 'Even':
print(f'You guessed {guess} and bet £{str(bet)}...\n')
if guess == odd_or_even:
print(f'You won £{str(bet)}!\n')
return bet
else:
print(f'You lost £{str(bet)}.\n')
return -bet
else:
print(f'You guessed {str(guess)} and bet £{str(bet)}...\n')
if guess == result:
print(f'You won £{str(bet * 35)}!\n')
return bet * 35
else:
print(f'You lost £{str(bet)}.\n')
return -bet
#Call your game of chance functions here
money += coin_flip('Heads', 10)
print(f'£{money} left\n')
money += cho_han('Odd', 20)
print(f'£{money} left\n')
money += two_card_draw(15)
print(f'£{money} left\n')
money += roulette(7, 10)
print(f'£{money} left\n')
money += roulette('Odd', 30)
print(f'£{money} left\n')
|
e41bfc8fc802efdad88cc126c592b611760c0b1e | DanielMGuedes/Exercicios_Python_Prof_Guanabara | /Aulas_Python/Python/Exercícios/Exe020-random-shuffle - Ordem aleatória.py | 630 | 3.921875 | 4 | '''import random
a1=str(input('Digite o nome numero 1: '))
a2=str(input('Digite o nome numero 2: '))
a3=str(input('Digite o nome numero 3: '))
a4=str(input('Digite o nome numero 4: '))
lista = [a1,a2,a3,a4]
random.shuffle (lista)
print('A ordem de apresentação será')
print(lista)'''
# importando apenas a função do pacote math
from random import shuffle
a1=str(input('Digite o nome do aluno 1: '))
a2=str(input('Digite o nome do aluno 2: '))
a3=str(input('Digite o nome do aluno 3: '))
a4=str(input('Digite o nome do aluno 4: '))
lista = [a1,a2,a3,a4]
shuffle (lista)
print('A ordem de apresentação será')
print(lista)
|
dcabc87d0d0bcbb43ad48e057e0b63bbb111ddb8 | sarma5233/pythonpract | /functions.py | 1,011 | 3.890625 | 4 | """def first(a):
def second(b):
return a+b
return second
adv = first(10)
print(adv(12))
"""
def Total_sum(nod,k):
s = 0
while(k > 0):
r = k % 10
s += (r**nod) # a**b is a raised to power b
k //= 10
return s # returns the calculated sum
def Number_of_digits(num): # function to calculate number of digits in a number
c = 0
while (num>0):
c+=1
num//=10
return c
def isArmstrong(n):
k = n
nod = Number_of_digits (k) # calling a Number_of_digits function
sum_of_digits = Total_sum (nod,k) # calling Total_sum function from another function isArmstrong()
if (sum_of_digits == n):
return True
return False
a = int(input("Enter the lower range :"))
b = int(input("Enter the higher range :"))
print ("The Armstrong numbers in the given range",a, "and",b,"are")
for i in range(a,b+1):
if(isArmstrong(i)):
print (i) |
a15d203fea9a36b76d64b0cf6fe0ff6c6c7f3b8b | ibardi/PythonCourse | /session01/helloex1.py | 1,616 | 4.5 | 4 | prnt ('Hello, Word')
# The error: "NameError: name 'prnt' is not defined" is returned, as prnt is an undefined in terms of Python, as such the program does not understand what I am asking of it.
#1a Lack of One Parenthesis
print ("Hello, World"
#ANSWER: Same as #1b, Python warns about the lack of the parentheses and returns a syntax error.
#1b Lack of Both parenthesis
print "Hello, World"
#ANSWER: Returns "SyntaxError: Missing parentheses in call to 'print". Here python returns a syntax error where it explicitly points out the issues = missing the parentheses.
#2a Lack of One quotation mark
print ("Hello, World)
#ANSWER: Returns "SyntaxError: EOL while scanning string literal". This is because the string is incomplete. The quotation mark at the end would designate the end of the string; however, python cannot find it, and so it doesn't have the ability to print the string.
#2b Lack of both quotations marks
print (Hello, World)
#ANSWER: Here Python tries to find "Hello" as a defined parameter. It doesn't recognize it as a string (text), but rather thinks of it as a predefined value which it should be supposed to be able to reference.
#3 Adding + in front of a number?
print (2++2)
#ANSWER: Python successfully prints "4" as a result. The logic being "2" and "positive 2" are is still equal to 4.
#4 Leading Zeros?
print (02+40)
#ANSWER: Python returns a "SyntaxError: invalid token", as "02" should be represented as "2" and so it doesn't understand the token.
#5 Two Values with No operators between
print (20 43)
#ANSWER: It returns a "SyntaxError: invalid Syntax". It won't work. |
e67aed685f33204e9807d983b9d886a4e5edd901 | satyagraha5/CodeJam_Python | /2015/Ominous_Omino/Ominous_Omino.py | 4,339 | 3.671875 | 4 |
'''
An N-omino is a two-dimensional shape formed by joining N unit cells fully along their edges in some way.
More formally, a 1-omino is a 1x1 unit square, and an N-omino is an (N-1)omino
with one or more of its edges joined to an adjacent 1x1 unit square. For the purpose of this problem,
we consider two N-ominoes to be the same if one can be transformed into the other via reflection
and/or rotation. For example, these are the five possible 4-ominoes
Richard and Gabriel are going to play a game with the following rules,
for some predetermined values of X, R, and C:
1. Richard will choose any one of the possible X-ominoes.
2. Gabriel must use at least one copy of that X-omino, along with arbitrarily
many copies of any X-ominoes (which can include the one Richard chose),
to completely fill in an R-by-C grid, with no overlaps and no spillover.
That is, every cell must be covered by exactly one of the X cells making up an X-omino,
and no X-omino can extend outside the grid. Gabriel is allowed to rotate or reflect
as many of the X-ominoes as he wants, including the one Richard chose.
If Gabriel can completely fill in the grid, he wins; otherwise, Richard wins.
Given particular values X, R, and C, can Richard choose an X-omino that will ensure that he wins,
or is Gabriel guaranteed to win no matter what Richard chooses?
'''
class TESTCASE():
def __init__(self,X,R,C):
self.X = int(X)
self.R = int(R)
self.C = int(C)
def __repr__(self):
fmt_string=""
return fmt_string.format()
def solve(self):
return self.Richard_versus_Gabriel()
def Richard_versus_Gabriel(self):
if self.first_filter() is False: # (R*C)%X != 0
return "RICHARD"
elif self.second_filter() is False: # X >= 7
return "RICHARD"
if self.fill_X_omino(self.X) is False:
return "RICHARD"
else:
return "GABRIEL"
def first_filter(self):
if (self.R * self.C)%self.X is not 0:
return False
return True
def second_filter(self):
if self.X >= 7:
return False
return True
def fill_X_omino(self,X):
long_side = max(self.R, self.C)
short_side = min(self.R, self.C)
if X <= 2:
return True #GABRIEL
elif X == 3:
if short_side == 1:
return False #RICHARD
else:
return True #GABRIEL
elif X == 4:
if short_side <= 2:
return False #RICHARD
else:
return True #GABRIEL
elif X == 5:
if short_side <= 2:
return False #RICHARD
elif short_side == 3:
if long_side > 5:
return True #GABRIEL
else: #long_side == 5
return False #RICHARD
else:
return True #GABRIEL
else: # X == 6
if short_side <= 3:
return False #RICHARD
else:
return True #GABRIEL
def data_preprocessing(input_file):
testcases=['index_start_from_1']
with open(input_file,'r') as f:
num_of_testcase=int(f.readline())
for n_th_testcase in range(1,num_of_testcase+1):
X, R, C = f.readline().rstrip('\n').split(" ")
testcases.append(TESTCASE(X,R,C))
return testcases
def model(testcase):
answer = testcase.solve()
return answer
def view(output_file,answers):
fmt_string="Case #{0}: {1}\n"
with open(output_file,'w') as f:
for n_th, answer in enumerate(answers[1:],1):
f.write(fmt_string.format(n_th,answer))
def controller():
#Conditions
suspect = "large-practice"
difficulty = 'D'
input_file = '{}-{}.in'.format(difficulty,suspect)
output_file = '{}-{}.out'.format(difficulty,suspect)
#Answer list
answers = ['index_start_from_1']
#Data Preprocessing
testcases = data_preprocessing(input_file)
for n_th, n_th_testcase in enumerate(testcases[1:],1):
#Model
answers.append(model(testcase = n_th_testcase))
#View
view(output_file = output_file,answers = answers)
if __name__=="__main__":
controller()
|
71e94121b2cca5746ad9b5caf281483c04b328a4 | Washira/HelloWorld | /PracticeOfString2.py | 470 | 3.8125 | 4 | '''
Input: รับสตริงหนึ่งบรรทัด
Process: ตรวจว่าสตริงนี้เป็น palindrome(ซึ่งคือสตริงที่กลับลำดับแล้วคือสตริงเดิม) หรือไม่
Output: ถ้าเป็น ก็แสดง Y ถ้าไม่เป็น ก็แสดง N /**
'''
a= input().strip()
if a == a[::-1]:
print("Y")
else:
print("N")
|
2fa9e5cc629eac2a0217e62bbd75277a02497ccc | zijing0926/Pythonds | /Trees and Tree Algorithms/ParseTree.py | 1,834 | 3.59375 | 4 | ##application of tree data structure
##use stack to track the parent and children of a tree
from pythonds.basic import Stack
from pythonds.trees import BinaryTree
def buildParseTree(fpexp):
####tokenize the expression to follow the rules:
fplist=fpexp.split()
pStack=Stack()
eTree=BinaryTree('')
pStack.push(eTree)
currentTree=eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree=currentTree.getLeftChild()
elif i in ['+', '-', '*', '/']:
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree=currentTree.getRightChild()
elif i == ')':
currentTree=pStack.pop()
elif i not in ['+', '-', '*', '/',')']:
try:
currentTree.setRootVal(int(i))
parent=pStack.pop()
currentTree=parent
except ValueError:
raise ValueError("token '{}' is not a valid interger'.format(i))
return eTree
###use operator to calculate/evaluate the parsed tree
import operator
def evaluate(parseTree):
opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}
##calculate the operation results as long as there are left and right child
left=parseTree.getLeftChild()
right=parseTree.getRightChild()
if left and right:
##get the operation
fn=opers[parseTree.getRootVal()]
return fn(evaluate(left),evaluate(right))
else:
return parseTree.getRootVal()
|
b47cf69ecc9ed790ff47fc100f8e57491e0da8e2 | chiragcj96/Algorithm-Implementation | /Delete N Nodes After M Nodes LL/solution.py | 832 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteNodes(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
current = head
i = 1
j = 0
while current:
print(current.val, i, j)
if i == m:
node = current.next
while j < n and node:
node = node.next
j += 1
j = 0
current.next = node
current = node
i = 1
elif current:
current = current.next
i += 1
return head |
18d6c0a34fac60755612b6e9c8df072d331fbdc8 | thetonyluce/tony-python-core | /week_03/labs/11_inheritance/11_01_subclasses.py | 3,086 | 4.09375 | 4 | '''
Build on 10_03_freeform_classes from the section on Classes, Objects and
Methods.
Create subclasses of two of the existing classes. Create a subclass of
one of those so that the hierarchy is at least three levels.
Build these classes out like we did in 10_03_freeform_classes.
If you cannot think of a way to build on your previous exercise,
you can start from scratch here.
We encourage you to be creative and try to think of an example of
your own for this exercise but if you are stuck, some ideas include:
- A Vehicle superclass, with Truck and Motorcycle subclasses.
- A Restaurant superclass, with Gourmet and FastFood subclasses.
'''
class Person:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def Name(self):
return self.firstname + " " + self.lastname
class Kiddo(Person):
def __init__(self, firstname, lastname, age):
Person.__init__(self, firstname, lastname)
self.age = age
def GetKiddo(self):
return self.Name() + ", " + self.age
# def say_age:
# the_simpsons = {
# Homer : "You tried and you failed miserably. The lesson is - never try.",
# Marge : "Honey you should listen to your heart - not the voices in your head.",
# Bart : "If you don't watch the violence, you'll never get desensitized."
class Employee(Person):
def __init__(self, firstname, lastname, staffID):
Person.__init__(self, firstname, lastname)
self.staffnumber = staffID
def GetEmployee(self):
return self.Name() + ", " + self.staffnumber
class Friend(Person):
homer_friends = set[Barney Gumble, Moe Syslak, Apu]
marge_friends = set[Edna, Patty, Luann]
bart_friends = set[Milhouse, Nelson, Martin]
lisa_friends = set[Allison, Ralph, Bleeding Gums Murphy]
friends = {Homer : [homer_friends], Marge : marge_friends, Bart : bart_friends, Lisa : lisa_friends }
def __init__(self, firstname, lastname, Friend):
Person.__init__(self, firstname, lastname)
self.Friend = Friend
def GetFriend(self):
if self.friend in homer_friends:
return self.friend() + "is a friend of Homer!""
elif self.friend in marge_friends:
return self.friend() + "is a friend of Marge!"
elif self.friend in bart_friends:
return self.friend() + "is a friend of Bart!"
elif self.friend in lisa_friends:
return self.friend() + "is a friend of Bart!"
else:
return "Not sure who this is."
class Boss(Employee):
def __init__(self, firstname, lastname, staffID, bosstype):
Employee.__init__(self, firstname, lastname, staffID)
self.bosstype = bosstype
def GetBoss(self):
return self.GetEmployee() + ", " + self.bosstype
p = Person("Marge", "Simpson")
e = Employee("Homer", "Simpson", "1007")
b = Boss("Mr", "Burns", "01", "Evil")
k = Kiddo("Lisa", "Simpson", "11")
f = Friend("Marge S")
print(p.Name())
print(e.GetEmployee())
print(b.GetBoss())
print(k.GetKiddo())
print(k.GetFriend())
|
df4ebab80b84b79485dc5aa5e9f9eed9d7bcdd25 | ciastooo/ulamSpiral | /ulamSpiral.py | 1,908 | 4.25 | 4 | from PIL import Image
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n % 2 == 0: return False
if n < 9: return True
if n % 3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
size = input("Enter size of image:")
while 1:
try:
size = int(size)
break
except ValueError:
print("Entered size is not a number")
size = input("Enter size of image:")
img = Image.new('RGB', (size, size), (255,255,255))
x = size//2
y = x
i = 1 # current integer that we are checking
step = 1 # how many steps utill we "rotate" our writing direction (since we're writing in spiral)
direction = 0 # in which direction we are currently moving (0 = right, 1 = up, 2 = left, 3 = down)
max_i_10p = size*size*0.1
progress=0
current_progress=0
while True: # we're drawing pixels untill we're out of image bounds
if i > progress:
print("Current picture progress: ", current_progress, "%", sep='')
progress += max_i_10p
current_progress += 10
for repeat in range(0,2):
steps_left = step
while steps_left > 0:
if x < 0 or x >= size or y < 0 or y >= size:
break
if(is_prime(i)):
img.putpixel((x, y), (0,0,0))
i = i + 1
if direction == 0:
x += 1
elif direction == 1:
y -= 1
elif direction == 2:
x -= 1
elif direction == 3:
y += 1
steps_left = steps_left - 1
direction += 1
if direction == 4:
direction = 0
if x < 0 or x >= size or y < 0 or y >= size:
break
step = step + 1
print("Done, spiral saved as \"spiral" + str(size) + ".png\"")
img.save('spiral' + str(size) + '.png') |
75df37601e8819adfd6f2ea1c8e6662ee5246007 | poiler22/brightCozmo | /qw.py | 562 | 3.921875 | 4 | import sys
import os
from tkinter import Tk, Label, Button
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
root.destroy()
os.execl(python, python, * sys.argv)
sys.executable
os.execl(sys.executable, sys.executable, *sys.argv)
root = Tk()
Label(root, text="Hello World!").pack()
Button(root, text="Restart", command=restart_program).pack()
root.mainloop() |
55c56256d278bd592fbfed459e8d113c8b61fb25 | timkaing/interview-prep | /leetcode/804/unique-morse-code-words.py | 818 | 3.953125 | 4 | '''
given a list of words (list of strings)
find the # of transformations ()
convert the words into morse code
- array of strings, map them
- create full morse by iterating each char of the word (for loop)
- convert letter to matching morse value
-
[a, a, a, a, a, b, c, c, d, d]
a, b, c, d
'''
def uniqueMorseRepresentations(words):
morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
result = set()
for word in words:
val = ""
for letter in word:
val += morse[ord(letter)-ord('a')]
result.add(val)
return len(result)
wordlist = ["gin", "zen", "gig", "msg"]
print(uniqueMorseRepresentations(wordlist)) |
155359354b2395e4c1b887ad8cb8c9312cb3f0fc | FisicaComputacionalPrimavera2018/ArraysAndVectorOperations | /vectoroperationsUpdated.py | 1,620 | 4.28125 | 4 | import math
#### FUNCTIONS
# The name of the function is "norm"
# Input: array x
# Output: the norm of x
def norm(x):
tmp = 0
for v in x:
tmp += v*v
norm_x = math.sqrt(tmp)
return norm_x
def vectorSum(x, y):
#z = x + y This doesn't work for arrays!
# First we check if the dimensions of x and y
# are the same
if len(x) != len(y):
return "ERROR"
# Now, we know the dimensions are the same
# We create an empty (zeros) vector z, which as the
# same dimensions as x and y
z = [0]*len(x)
# Next step, calculate the components of z
for i in range(0, len(z)):
z[i] = x[i] + y[i]
#z = [ x[0]+y[0], x[1]+y[1], x[2]+y[2] ]
return z # return the sum
def scalarProduct(x, y):
if len(x) != len(y):
return "ERROR"
r = 0
for i in range(0, len(x)):
r = x[i]*y[i]
return r
def angle(x, y):
return math.acos(scalarProduct(x,y) / (norm(x)*norm(y)))
# Define some three-dimensional vectors
x = [5, 3, 5]
y = [5.5, 6, 8]
z = [2, 0, 6.6]
# norm
print norm(x)
# sum
print vectorSum(x, y)
# scalar product
print scalarProduct(x, y)
# angle (homework)
norm_x = norm(x)
norm_y = norm(y)
n = scalarProduct(x,y)
#print math.acos(n/(norm_x*norm_y))
# shorter way:
#print math.acos(scalarProduct(x,y) / (norm(x)*norm(y)))
# even shorter
angle1 = angle(x, y)
print angle1
#print angle(x, y)
# convert to degrees
#print math.degrees(angle(x, y))
# angle of vector A between x,y,z axis
A = [5, 6, 11]
alpha_1 = angle(A, [1, 0, 0])
alpha_2 = angle(A, [0, 1, 0])
alpha_3 = angle(A, [0, 0, 1])
print alpha_1, alpha_2, alpha_3
# vector product (homework)
|
305c98278c1c886ba6b63d2a553e99db65c9cf39 | martin-martin/nlpython | /exercises/anagrams/anagrams.py | 1,071 | 4.5 | 4 | from itertools import permutations
def find_anagrams(word, word_list):
"""Finds all valid anagrams for a given word.
Args:
word (str): the word we want to find anagrams for
word_list (list): a list of valid words in the english language
Returns:
set: a set of valid anagrams of the given word
"""
# warn for the length of execution
# = cheap conversational hack-around... :P
if len(word) > 7:
print("choose a shorter word (or wait...)")
elif len(word) > 6:
print("this might take a while...")
# long thing that does what it shalls - but inefficiently!!
anagrams = {''.join(w) for w in permutations(word, len(word))
if ''.join(w) in word_list}
return anagrams
# fetching our list of acceptable words
with open('words.txt', 'r') as fin:
word_list = fin.readlines()
word_list = [w.rstrip() for w in word_list]
if __name__ == '__main__':
while True:
word = input("Enter a word to find its anagrams: ")
print(find_anagrams(word, word_list))
|
d1878a07d800312a3cfdc673ea03a59eea62efa4 | absoluteabutaj/Guvi | /KinderArrange.py | 304 | 3.625 | 4 | # Created on 03-Sep-2016
# @author: AbuTaj
n = int(input('Enter N'))
n2 = 2 * n
for i in range(1, n2):
print('Day', i)
for j in range(0, 1):
if(i != j):
if i + 1 > 9 or j + 1 > 9 or i > 9 or j > 9:
i = 0
j = 0
print(i, i + 1, j, j + 1)
|
4300f9feaa302bb003027151d0c92b712a182964 | vjstark/Python_Basics | /python_mini_projects/fileprogs/fileprog1.py | 1,656 | 3.890625 | 4 | import os
while True:
try:
op= int(input('1:Create File, 2:Delete File, 3:Read File, 4:Write File, 5:Exit : '))
#Create File
if op==1:
fn= input('Enter file name to be created: ')
if(not os.path.exists(fn)):
f = open(fn,'a')
print('File created.')
else:
print('File already exists.')
#Delete File
elif op==2:
fn= input('Enter file name to be deleted: ')
if(os.path.exists(fn)):
os.remove(fn)
print(fn +' was deleted.')
else:
print('File does not exist.')
#Read File
elif op==3:
fn= input('Enter file name to read: ')
if(os.path.isfile(fn)):
f = open(fn)
data = f.read()
print(data)
f.close()
else:
print('File does not exist.')
#Write File
elif op==4:
fn = input('Enter file name: ')
if(os.path.isfile(fn)):
f=open(fn,'a')
print('Enter data, pree q to quit. ')
data = input()
while data!='q':
f.write(data+'\n')
data=input()
f.close()
else:
print('File does not exist')
# try:
# fn = input('Enter file name: ')
# if(os.path.isfile(fn)):
# f = open(fn,'a')
# while True:
# op1= int(input('1:Write Line,2: Quit : '))
# if op1 == 1:
# data = input('Enter data to write: ')
# f.write(data+'\n')
# elif op1 == 2:
# f.close()
# break
# else:
# print('Invalid Option')
# else:
# print('File does not exist')
# except ValueError:
# print('You need to enter integers only')
#exit the program
elif op==5:
break
#invalid input
else:
print('Invalid Option')
except ValueError:
print('You need to enter integers only')
|
0ad3ad3891dee0a91f99e381ac012ddda111d385 | jimleroux/enphaseai | /enphaseAI/problem1.py | 2,424 | 4.28125 | 4 | from typing import Tuple
def find_lines_from_points(
p0: Tuple[float, float],
p1: Tuple[float, float]
) -> Tuple[float, float]:
"""
Function calculating the line passing throught a pair of points.
Args:
p1 (Tuple[float, float]): First point.
p2 (Tuple[float, float]): Second point.
Returns:
Tuple[float, float]: Returns the parameters of the line (a, b)
"""
x0, y0 = p0
x1, y1 = p1
assert isinstance(x0, float), "x0 must be a float"
assert isinstance(y0, float), "y0 must be a float"
assert isinstance(x1, float), "x1 must be a float"
assert isinstance(y1, float), "y1 must be a float"
assert x0 != x1, "Points must be distinct"
# We want to find the parameters that satisfies
# y0 = a * x0 + b and y1 = a * x1 + b
# We can substract both equations and solve for a
a = (y1 - y0) / (x1 - x0)
# Then we can solve for b in one equation, lets say
# b = y0 - a * x0 = y0 - (y1 - y0) / (x1 - x0) * x0
b = y0 - a * x0
return a, b
def find_lines_intersection(
l0: Tuple[float, float],
l1: Tuple[float, float]
) -> Tuple[float, float]:
"""
Function calculating the intersection of 2 lines given their parameters (a, b)
Args:
l1 (Tuple[float, float]): Parameters describing the first line.
l2 (Tuple[float, float]): Parameters describing the second line.
Returns:
Tuple[float, float]: Returns the location of the points (x, y)
"""
a0, b0 = l0
a1, b1 = l1
assert isinstance(a0, float), "a0 must be a float"
assert isinstance(b0, float), "b0 must be a float"
assert isinstance(a1, float), "a1 must be a float"
assert isinstance(b1, float), "b1 must be a float"
assert l0 != l1, "Lines should be distict otherwise there is an infinite number of solutions"
# We look for the point where a0 * x + b0 = a1 * x + b1
# We solve for x
x = - (b1 - b0) / (a1 - a0)
# Plug into one of the equations
y = a0 * x + b0
return x, y
if __name__ == "__main__":
p0 = (-0.5, 5.0)
p1 = (6.7, -18.5)
p2 = (0.5, 5.0)
p3 = (6.7, 18.5)
a0, b0 = find_lines_from_points(p0, p1)
a1, b1 = find_lines_from_points(p2, p3)
l0 = (a0, b0)
l1 = (a1, b1)
x, y = find_lines_intersection(l0, l1)
|
07b711a53bbd3e12e98bb91f858393ee283f2751 | Sposigor/Caminho_do_Python | /exercicios_curso_em_video/Exercicio 40.py | 160 | 3.890625 | 4 | n1=float(input("nota 1"))
n2=float(input("nota 2"))
m=(n1+n2)/2
if m<5:
print("REPROVADO")
elif m>=7:
print("APROVADO")
else:
print("RECUPERAÇÃO") |
407837d46870d714b93e269d66beada90c5ad1b8 | jt-lai/python-100-day-practice | /Day 6/Day_6_Practice_1.py | 447 | 3.71875 | 4 | """
练习1:实现计算求最大公约数和最小公倍数的函数。
Ver: 0.1
Author: JT
Date: 02/08/2020
"""
def gcd(a, b):
# find the greatest common devisor (gcd)
for i in range(1, a + 1):
if a % i == 0 and b % i == 0:
gcd = i
return gcd
def lcm(a, b):
# find the least common multiple (lcm)
lcm = 0
while True:
lcm = a + lcm
if lcm % b == 0:
break
return lcm |
5ce2fdca9d108932784bef12cf85548447f424da | SadManFahIm/HackerRank-Preparation-Kit | /Minimum Time Required.py | 561 | 3.640625 | 4 | def minTime(machines, goal):
# make a modest guess of what the days may be, and use it as a starting point
efficiency = [1.0/x for x in machines]
lower_bound = int(goal / sum(efficiency)) - 1
upper_bound = lower_bound + max(machines) + 1
while lower_bound < upper_bound -1:
days = (lower_bound + upper_bound)//2
produce = sum([days//x for x in machines])
if produce >= goal:
upper_bound = days
elif produce < goal:
lower_bound = days
return upper_bound |
77dc60a6a27ff9d341ec31633df651b2a914c0ff | vecchp/CrackingTheCodingInterview | /chapter2/question2_5.py | 428 | 3.859375 | 4 |
# Question 2.5
# Time O(n)
# Space O(1)
def sum_small_to_big(list_1: list, list_2: list):
order = 1
total = 0
for a, b in zip(list_1, list_2):
total += (a + b) * order
order *= 10
return total
# Time O(n)
# Spac O(1)
def sum_big_to_small(list_1: list, list_2: list):
total = 0
order = 10
for a, b in zip(list_1, list_2):
total = total * order + a + b
return total
|
9aca81a214b4e5c218c50db00cdea312755277fb | wcsBurneyCoder/lintCode-python | /A+B问题.py | 404 | 3.640625 | 4 | #coding:utf-8
'''
A + B 问题
给出两个整数 a 和 b, 求他们的和,不使用+号
'''
def aplusb(a, b):
# write your code here
INT_RANGE = 0xFFFFFFFF
while b != 0:
a, b = a ^ b, (a & b) << 1
a &= INT_RANGE
return a if a >> 31 <= 0 else a ^ ~INT_RANGE
if __name__ == '__main__':
print (aplusb(5, 6))
print (aplusb(100, -100))
print (aplusb(200000, 3000000))
|
51b16ec6a02a7e0570448aeeb83ad30c49b1a6c1 | sushovan86/PythonProjects | /SplitJoinSpreadsheet/main.py | 1,197 | 3.8125 | 4 | import os
import sys
from pandas import read_excel
from process_split import *
def validate_column(df, column):
if column not in df.columns:
print("ERROR!!! Column {} is not available in the spreadsheet. "
"Please provide correct column name"
.format(column))
exit(-1)
def main():
args = sys.argv
if len(args) != 2:
print("ERROR!!! Please provide file path as first argument")
exit(-1)
else:
abspath = os.path.abspath(args[1])
filename = os.path.splitext(abspath)[0]
ext = os.path.splitext(abspath)[1]
if ext.lower() not in ['.xls', '.xlsx']:
print("ERROR!!! Not an excel file")
exit(-1)
column = input('Enter column to split: ')
choice = input('Enter split choice (S = Sheet / F = File): ').upper()
df = read_excel(abspath)
validate_column(df, column)
if choice == 'F':
process_split_file(df, column, filename, ext)
elif choice == 'S':
process_split_sheet(df, column, filename, ext)
else:
print("ERROR!!! Invalid choice")
if __name__ == '__main__':
main()
|
b2c1bcd125b9e98751182981c8c0a421906deaff | jeff283/flask-login-app | /databs.py | 240 | 3.796875 | 4 | import sqlite3
def store():
global conn
global c
conn = sqlite3.connect("database.db")
c = conn.cursor()
#creating a table
c.execute("""CREATE TABLE IF NOT EXISTS login (
username TEXT,
password TEXT
)
""")
store() |
3c018a2cbc3498fc8942b889e37b265751975c89 | ArunPrasad017/python-play | /coding-exercise/Day76-SortArrayByParity.py | 695 | 3.953125 | 4 | """
905. Sort Array By Parity
Given an array A of non-negative integers, return an array consisting of all the even elements of A,
followed by all the odd elements of A.
You may return any answer array that satisfies this condition
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
"""
def sortArrayParity(lst):
if lst is None:
return lst
i, j = 0, len(lst) - 1
while i < j:
if lst[i] % 2 > lst[j] % 2:
lst[i], lst[j] = lst[j], lst[i]
if lst[i] % 2 == 0:
i += 1
if lst[j] % 2 == 1:
j -= 1
return lst
lst = [3, 1, 2, 4]
print(sortArrayParity(lst))
|
ff71cc7cf701c685073879cc644a51cea3fb0dff | doitfool/leetcode | /ReverseLinked List.py | 637 | 3.75 | 4 | # coding: utf-8
"""
Reverse a singly linked list.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
data = []
temp = head
while temp is not None:
data.append(temp.val)
temp = temp.next
i = 1
temp = head
while temp is not None:
temp.val = data[len(data)-i]
temp = temp.next
i += 1
return head
|
91cfa0dd749027b89a99e73d72a70165af3f614b | PRKKILLER/Algorithm_Practice | /LeetCode/0067-Add binary/main.py | 1,255 | 3.953125 | 4 | """
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
"""
class Solution:
# bit-by-bit computation
# space complexity: O(max(M, N))
def addBinary(self, a: str, b: str) -> str:
n = max(len(a), len(b))
# 向左填充0,让 a,b长度相同,右对齐,方便相加
if len(a) < n:
a = a.zfill(n)
else:
b = b.zfill(n)
res = []
carry = 0
for i in range(n-1, -1, -1):
if a[i] == '1':
carry += 1
if b[i] == '1':
carry += 1
if carry == 0 or carry == 2:
res.append('0')
else:
res.append('1')
carry //= 2
if carry:
res.append('1')
return ''.join(res[::-1]) # reverse
# bit manipulation. Add two numbers without using add operator
def addBinary(self, a: str, b: str) -> str:
a, b = int(a, 2), int(b, 2)
while b:
ans = a ^ b # answser without carry
carry = (a & b) << 1
a, b = ans, carry
return bin(a)[2:]
|
66170dfbe9761acc0424b763dcb6390d0ecf667f | mattvenn/python-workshop | /demos/turtle/fill.py | 264 | 3.5 | 4 | #import all from turtle library
from turtle import *
pencolor('red')
fillcolor( 'yellow')
speed(5)
#start a fill
begin_fill()
loops = 0
while loops < 20:
forward(200)
left(170)
loops = loops + 1
#end the fill
end_fill()
done()
|
299f10acfd68ad45221a2d1f84b996a42f96fc54 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/sum-of-matrices-reverse-rows.py | 1,600 | 4 | 4 | Sum of Matrices - Reverse Rows
The program must accept two integer matrices M1 and M2 are of equal size RxC as the input. In M1 and M2, The program must reverse the integers in the odd positions of the odd rows and the integers in the even positions of the even rows. Then the program must print the sum of M1 and M2 as the output.
Example Input/Output 1:
Input:
5 5
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
9 3 5 6 9
4 2 8 7 6
8 6 5 9 2
4 6 2 8 1
1 6 3 4 5
Output:
14 5 8 10 10
6 12 12 5 12
9 10 10 15 11
8 15 8 11 9
14 12 10 12 6
Example Input/Output 2:
Input:
2 6
50 81 56 50 58 56
68 16 17 56 84 49
20 88 36 20 81 36
83 44 16 26 86 92
Output:
139 169 92 70 70 92
151 141 33 82 170 60
def rev(x,a,b):
c=[]
for i in range(a):
p=[];f=[];d=[]
if i%2==0:
for j in range(b):
if j%2==0:
p.append(x[i][j])
f.append(j)
p=p[::-1]
l=0
for h in range(b):
if l<len(p) and h==f[l]:
d.append(p[l])
l+=1
else:
d.append(x[i][h])
c.append(d)
else:
for j in range(b):
if j%2!=0:
p.append(x[i][j])
f.append(j)
p=p[::-1];l=0
for h in range(b):
if l<len(p) and h==f[l]:
d.append(p[l])
l+=1
else:
d.append(x[i][h])
c.append(d)
return c
a,b=map(int,input().split())
l=[input().split() for i in range(a)]
y=[input().split() for i in range(a)]
m=rev(l,a,b);n=rev(y,a,b)
for i in range(a):
for j in range(b):
print(int(m[i][j])+int(n[i][j]),end=' ')
print()
|
591862c704f531f9984e76d6c76c69ae631aeecb | rec/test | /python/calc.py | 1,010 | 4 | 4 | OPS = {
'add': (lambda x, y: x + y, '+'),
'sub': (lambda x, y: x - y, '-'),
'mul': (lambda x, y: x * y, '*'),
'div': (lambda x, y: x + y, '/'),
'quit': (None, 'quit'),
}
def main():
print('Welcome to attocalc')
while True:
op, symbol = _get_op()
if symbol == 'quit':
print('/attocalc')
return
num1 = _get_float('What is the first number? ')
num2 = _get_float('What is the second? ')
result = op(num1, num2)
print(f'{num1} {symbol} {num2} = {result}')
def _get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print('not a float - try again')
def _get_op():
while True:
op_name = input('What would you like to do? ').strip()
try:
return OPS[op_name.lower()]
except KeyError:
print('Invalid command', op_name, 'Valid commands are:', *OPS)
if __name__ == '__main__':
main()
|
13cdaddbaa0db76a4d31b9e2109948ac8654a791 | vckelly/Thinkful | /fizzbuzz.py | 322 | 3.828125 | 4 | #!/usr/bin/env python
fizz = range(1, 101)
buzz = ""
print "Fizz buzz counting up to 100"
for i in fizz:
if (i % 3) == 0:
buzz += "fizz"
if (i % 5) == 0:
buzz += "buzz"
elif not (i % 5) == 0 and not (i % 3) == 0:
buzz += str(i)
buzz += ", "
print buzz[:-2]
|
6057f2bbd745f706a82e5c1bd48a645497c8520c | Oyelowo/GEO-PYTHON-2017 | /ass3/untitled0.py | 1,496 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 22 08:54:32 2017
@author: oyeda
"""
word = 'lowo'
print word[0]
print word[1]
print word[2]
print word[3]
word2 = "mayor"
for char in word2: print (char)
length = 10
for letter in 'geomatics': length = length + 1
print length
for letter in 'dayom': print (letter)
print (letter)
for value in range(8): print(value)
mylist = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
print (mylist)
for i in range(6): mylist[i]=mylist[i]+i
print(mylist)
for i in range(6): mylist[i]=mylist[i]+i
print(mylist)
mylist.append(19.0)
mylist.append(49)
for i in range(len(mylist)): mylist[i]= mylist[i]+i
print(mylist)
for i in range(len(mylist)): mylist[i]=mylist[i]+i
print(mylist)
help(range)
for y in range(2, 9, 3): print(y)
words = 'ice pellets'
for i in range(len(words)): print(words[i])
yesterday = 14
today = 10
tomorrow = 13
if yesterday <= today:
print('A')
elif today != tomorrow:
print('B')
elif yesterday > tomorrow:
print('C')
elif today == today:
print('D')
if (1 > 0) and (-1 > 0):
print('Both parts are true')
else:
print('One part is not true')
if (1 < 0) or (-1 < 0):
print('At least one test is true')
In [11]: weather = 'Rain'
In [12]: wind = 'Windy'
In [13]: if (weather == 'Rain') and (wind == 'Windy'):
....: print('Just stay home')
....: elif weather == 'Rain':
....: print('Wear a raincoat')
....: else:
....: print('No raincoat needed')
|
e5b8d8fb1bc6e4fadfc93ef81cd2ffa40790c83c | Amit32624/Python | /Python_codes/DemoSet.py | 537 | 4.03125 | 4 | '''
Created on 12-Jun-2017
@author: mohan.chinnaiah
'''
set1={1,2,3,4,5,6,7}
set2={4,5,6,7,8,9,10}
print(set1);
print(set2);
print(set1.union(set2));
print(set1.intersection(set2));
print(set1.difference(set2));
print(set2.difference(set1));
engineers = {'John', 'Jane', 'Jack', 'Janice'}
programmers = {'Jack', 'Sam', 'Susan', 'Janice'}
managers = {'Jane', 'Jack', 'Susan', 'Zack'}
'''union'''
employees=engineers | programmers | managers
print(employees)
'''intersection'''
eng_man=engineers & managers
print(eng_man) |
45f3db7264fe2fef85daab923d7b506235df533f | fonyango/MayOfCode | /day_08.py | 793 | 4.3125 | 4 | # --- DAY EIGHT ---
'''
1. Write a Python program that can take a positive integer greater than 2 as
input and write out the number of times one must repeatedly divide this
number by 2 before getting a value less than 2.
'''
def divide_by_two(x):
'''
Determines the number of times one must repeatedly divide a positive integer greater
than 2 by 2 before getting a value less than 2
param x: a positive integer greater than 2
return : number of times x is divided by 2 before getting a value less than 2
'''
counter = 0 # initialize a counter
while x > 2:
x = x / 2
counter +=1
return counter
# test if the function is working
print(divide_by_two(8))
print(divide_by_two(32))
print(divide_by_two(49))
print(divide_by_two(1000))
|
6edf0f3ae6369659f8671947753628107eb50428 | wxzoro1/MyPractise | /python/liaoscode/datetime.py | 1,317 | 3.53125 | 4 | from datetime import datetime,timedelta,timezone
now = datetime.now()
print(now)
print(type(now))
dt = datetime(2015,4,19,12,11,11)
print(dt)
#timestamp
dt = datetime(2018,2,21,23,11,22)
a = dt.timestamp()
print(a)
print(datetime.fromtimestamp(a))#本地时间
print(datetime.utcfromtimestamp(a))#UTC时间
#str转datetime
cday = datetime.strptime('2015-6-1 18:59:00', '%Y-%m-%d %H:%M:%S')#固定的
print(cday)
#datetime转str
print(now.strftime('%a, %b %d %H:%M'))
#datatime加减
print(now + timedelta(hours = 10))
print(now - timedelta(days = 1))
print(now + timedelta(days = 1, hours = 10))
#本地时间转UTC
tz_utc_8 = timezone(timedelta(hours = 8))#创建+8时区
print(now)
dt = now.replace(tzinfo = tz_utc_8)#强制为+8时区 若运行成功则说明猜测时区正确
print(dt)
#时区转换
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)#强制时区为0
print(utc_dt)
#将转换时间为北京
beijing_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print(beijing_dt)
#东京
tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt)
#北京转东京
tokyo_dt2 = beijing_dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt2)
#要知道datetime时区 然后强制 作为基准
#时区转换不必从utc 0 开始 从北京直接可转东京,(强制后即可)
|
1f14a9d4a7c20a45a91538116da25c8823de0035 | daxm/duplicate_letter_word_counter | /main.py | 570 | 3.78125 | 4 | import nltk
def main():
with_duplicates = 0
without_duplicates = 0
for word in nltk.corpus.words.words():
if len(word) == len(set(word)):
without_duplicates += 1
else:
with_duplicates += 1
total = with_duplicates + without_duplicates
print(f"Total words: {total}")
print(f"With Duplicates: {with_duplicates}: {with_duplicates/total*100:.2f}%")
print(f"Without Duplicates: {without_duplicates}: {without_duplicates/total*100:.2f}%")
if __name__ == '__main__':
nltk.download('words')
main()
|
4bad152502d49dd3375f14aa0913e02ebd1defac | pmana/breakout | /graphics.py | 1,263 | 3.59375 | 4 | import curses
from math import floor
class CursesGraphics:
def __init__(self, screen, max_x, max_y):
self.screen, self.max_x, self.max_y = screen, max_x, max_y
def begin_frame(self):
for row in range(0, self.max_y):
self.draw(0, row, ' ' * self.max_x)
def end_frame(self):
self.screen.refresh()
def draw(self, x, y, string, color=1):
x = floor(x)
y = floor(y)
assert(x + len(string) <= self.max_x)
assert(y <= self.max_y)
curses_color = curses.color_pair(color)
flip_y = self.max_y - 1 - y
if self.will_draw_last_cell(x, y, string):
# curses cannot directly output to the last cell
all_but_first = string[1:]
self.screen.addstr(flip_y, x, all_but_first, curses_color)
self.screen.insstr(flip_y, x, string[0], curses_color)
else:
self.screen.addstr(flip_y, x, string, curses_color)
def will_draw_last_cell(self, x, y, string):
return y == 0 and x + len(string) == self.max_x
def display_message(self, message, color):
center_x = self.max_x // 2 - (len(message) // 2)
center_y = self.max_y // 2
self.draw(center_x, center_y, message, color)
|
6e11d8a5a05ad5cb94461ada917d27189e7f79d5 | ianzapolsky/practice | /misc/guess/game.py | 730 | 4.03125 | 4 | # game.py
# A simple number guessing game
# By Ian Zapolsky (12/08/13)
import random
def select_random_number():
random_integer = random.randint(1, 100);
return random_integer
def interpret_guess(random_integer):
print 'please enter a guess: '
guess = int(raw_input())
if random_integer > guess:
print 'too low'
return False
elif random_integer < guess:
print 'too high'
return False
else:
return True
if __name__ == '__main__':
print 'welcome to the guessing game\n'
num_to_guess = select_random_number()
guesses = 1
while not interpret_guess(num_to_guess):
guesses += 1
print 'you guessed the number in '+str(guesses)+' guesses'
|
5f575c64f51fe99f4ecb56c1e04ab72715284f2f | alansong95/leetcode | /169_majority_element.py | 948 | 3.53125 | 4 | # hash table
# time: O(n)
# space: O(n)
# class Solution(object):
# def majorityElement(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# ht = {}
# for num in nums:
# if num not in ht:
# ht[num] = 1
# else:
# ht[num] += 1
# for num in ht:
# if ht[num] > len(nums) // 2:
# return num
# hash table in 2 lines
# time: O(n)
# space: O(n)
# import collections
# class Solution(object):
# def majorityElement(self, nums):
# counts = collections.Counter(nums)
# return max(counts, key=counts.get)
# sorting
# time: O(nlogn)
# space: O(1)
class Solution(object):
def majorityElement(self, nums):
nums = sorted(nums)
return nums[len(nums)//2]
solution = Solution()
print(solution.majorityElement([3,2,3]))
print(solution.majorityElement([2,2,1,1,1,2,2]))
|
1dff45d9904e92bc5396644f1ea960b29836ab0b | Omni-HuB/CO_M21_Assignment-main | /SimpleSimulator/registerFile.py | 959 | 3.65625 | 4 | #!/usr/bin/python
#Function to convert decimal to 8bit binary
def dto16b(decimal):
bnr = bin(decimal).replace('0b','')
x = bnr[::-1] #this reverses an array
while len(x) < 16:
x += '0'
return x[::-1]
class registerFile:
registers = [0, 0, 0, 0, 0, 0, 0, 0]
def dump(self):
for reg in self.registers:
print(dto16b(reg), end=" ")
print()
return
def getValue(self, reg_no):
return self.registers[int(reg_no, 2)]
def getFlag(self):
return self.registers[7];
def resetFlag(self):
self.registers[7] = 0;
def setVFlag(self):
self.registers[7] = 8;
def setLFlag(self):
self.registers[7] = 4;
def setGFlag(self):
self.registers[7] = 2;
def setEFlag(self):
self.registers[7] = 1;
def setR0(self, value):
self.registers[0] = value;
def setR1(self, value):
self.registers[1] = value;
def setValue(self, reg_no, value):
self.registers[int(reg_no,2)] = value;
return;
|
997ec859787340d6914a8d59efe0963ddc7d4dc9 | gabrieleliasdev/python-mentoring | /ex12.py | 920 | 4.09375 | 4 | def bot_cafe():
print("Welcome Cafeteria")
tipo = tipo_do_cafe()
print(tipo)
tamanho = tamanho_do_cafe()
print(f'Tudo bem, o {tipo} {tamanho}')
def tipo_do_cafe():
res = input("Qual o tipo do café que você deseja?\n[a] Expresso \n[b] Mocha \n[c] Capuccino\n")
if res == 'a':
return 'Expresso'
elif res == 'b':
return 'Mocha'
elif res == 'c':
return 'Capuccino'
else:
print_mensagem()
tipo_do_cafe()
def tamanho_do_cafe():
res = input("Qual é o tamanho do café que você deseja?\n[a] Pequeno \n[b] Médio \n[c] Grande\n")
if res == 'a':
return 'Pequeno'
elif res == 'b':
return 'Médio'
elif res == 'c':
return 'Grande'
else:
print_mensagem()
tamanho_do_cafe()
def print_mensagem():
print("Me desculpe. Não compreende o que você disse. Por favor, entre com a letra correta.")
bot_cafe()
|
ca8ae7f452dd9709a247f13aea839f30d7465156 | bjherger/algorithms_and_data_structures | /algorithms/stack/reference_implementation.py | 3,978 | 4 | 4 | import logging
class Stack(object):
"""
A Stack implementation, with the following attributes
- Array implementation
- First in, last out
- New elements added to end of list
- Elements removed from end of list
API roughly based on https://docs.oracle.com/javase/7/docs/api/java/util/Queue.html
"""
def __init__(self, iterable_input=None):
"""
Initialize and return an instance of the data structure.
:param iterable_input: Add elements from iterable to the data structure. If iterable is ordered, elements will be in
that order
"""
self.array = list()
if iterable_input is not None:
logging.info(f'Creating data structure from iteratble: {iterable_input}')
for element in iterable_input:
logging.info(f'Adding element {element} to data structure')
self.add(element)
def size(self):
"""
Returns the number of elements in the data structure
:return: Number of elements in the data structure
:rtype: int
"""
return len(self.array)
def add(self, element):
"""
Add the specified element to the end of the data structure
:param element:
:type element: object
:return: None
:rtype: None
"""
logging.info(f'Adding element: {element} to data structure, with array: {self.array}')
self.array.append(element)
logging.info(f'Added element: {element} to data structure, with array: {self.array}')
return None
def remove(self):
"""
Remove the first element from the data structure, and return it. If the data structure is empty, then this will
raise a ValueError.
:raises: ValueError
:return: The first object in the data structure, if there is one
:rtype: object
"""
# Return ValueError if no elements
if len(self.array) <= 0:
raise ValueError('No elements in data structure to remove')
# Pull and last element in array
element = self.array.pop()
# Return pulled element
return element
def remove_element(self, element=None):
"""
Remove the specified element from the data structure. If the specified element is not in the data structure
(or the data structure is empty), then this will raise a ValueError.
:param element: The element to be removed
:type element: object
:raises: ValueError
:return: None
:rtype: None
"""
# Return ValueError if no elements
if len(self.array) <= 0:
raise ValueError('No elements in data structure to remove')
# Reverse array, so that last added copy of element is removed
self.array = list(reversed(self.array))
# Find index of element, and re-phrase error if not found
try:
element_index = self.array.index(element)
except ValueError:
raise ValueError('Element not in data structure')
# Pull and remove element at found index
self.array.pop(element_index)
# Reverse array again, to reset natural order
self.array = list(reversed(self.array))
# Return None
return None
def peak(self):
"""
Return the first item in the data structure, without removing it
:return: The first item in the data structure
:rtype: object
:raises: ValueError
"""
# Return ValueError if no elements
if len(self.array) <= 0:
raise ValueError('No elements in data structure to remove')
return self.array[-1]
def contains(self, element):
"""
Determine if the element is in the data structure.
:return: Whether the element is in the data structure.
:rtype: bool
"""
return element in self.array
|
aecfad6539042c2265409c156c5f82a06e6f3be8 | adstr123/ds-a-in-python-goodrich | /chapter-1/r2_is_even.py | 402 | 4.34375 | 4 | def is_even(k):
"""
Takes an integer and returns True if it is even
:param int k: the number to evaluate
:return boolean: based on condition evaluation
"""
# bitwise &
# if last bit is 1, number is odd
if k & 1:
return False
else:
return True
"""
Time: O(1)
- Always one calculation that takes place
Space: O(1)
- Always needs 1 unit for input & 1 unit for return value
"""
|
052983dac6f8688c1f76b394dd8406adbdbd721f | BO3K404/Hash404 | /sha256.py | 409 | 3.53125 | 4 | #!/usr/bin/env python
#_*_ coding: utf8 _*_
import hashlib
def main():
hashpass = str(raw_input("HASH: "))
passfile = open("dictionary.txt",'r')
for p in passfile.readlines():
n = p.strip("\n")
n = hashlib.sha256(n).hexdigest()
if n == hashpass:
print("Password: {} HASH: {}".format(p,n))
break
if __name__ == '__main__':
main()
|
3e0086aaf41e5edfe750235ed0ca5912a7aa20f8 | ZahraRoushan/MachineLearning1 | /Algorithm_Section/dynamic_programming/binomial_coefficient.py | 318 | 3.53125 | 4 | def binomial(n, k, dp={}):
assert (n >= 0 and k >= 0), "lotfan riazi yad begir"
if k == 0 or n == k:
return 1
if (n, k) not in dp:
result = binomial(n-1, k) + binomial(n-1, k-1)
dp[(n, k)] = result
return result
else:
return dp[(n, k)]
print(binomial(5, 4))
|
6d75efdbb0e4c38c323f47a3efb491ed64ce12ee | htrahddis-hub/DSA-Together-HacktoberFest | /strings/Easy/hash_table.py | 828 | 4.09375 | 4 | # Used Hashing concept in Finding Duplicates in an array
# Hastables are basically Dictionaries in Python
# Below is the implementation of HashTables (Referred Code Basics YT channel)
class HashTable:
def __init__(self):
self.MAX = 100
self.arr = [None for i in range(self.MAX)]
def get_hash(self, key):
hash = 0
for char in key:
hash += ord(char)
return hash % self.MAX
def __getitem__(self, index):
h = self.get_hash(index)
return self.arr[h]
def __setitem__(self, key, val):
h = self.get_hash(key)
self.arr[h] = val
def __delitem__(self, key):
h = self.get_hash(key)
self.arr[h] = None
t = HashTable()
t["march 6"] = 310
t["march 7"] = 420
print(t["march 7"]) |
7f4dd5696527e529307d5d69d57459075827e43d | wjdgh7587/programmingstudy | /Python_Ruby/Container_Loop/3.py | 227 | 3.796875 | 4 | input_id = input("Puy your id\n")
members = ['naver', 'google', 'daum']
for member in members:
if member == input_id:
print('Hello!, '+member)
import sys #system out
sys.exit()
print('Who are you?')
|
29464973876d22a5cf2a8c717055744651c1deda | hugo-paiva/curso_Python_em_Video | /Exercícios Resolvidos/aula16.py | 247 | 3.921875 | 4 | '''lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim')
for contador in range(0, len(lanche)):
print(f'Eu vou comer {lanche[contador]}!')
print('Nossa comi pra caramba!')'''
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = b + a
print(c)
print(c.index(5, 1)) |
f9cf8c5cc0eed8209b5a13b051b1760e2de04196 | smnbnt/MIT6.00.1x | /Quiz/Problem4.py | 409 | 3.890625 | 4 | def myLogIter(x, b):
'''
x: a positive integer
b: a positive integer; b >= 2
returns: log_b(x), or, the logarithm of x relative to a base b.
'''
power = 0
log_b = 0
while 1:
log_b = b**power
if log_b == x:
break
elif log_b > x:
power -= 1
break
else:
power += 1
return power
|
2d55ff969783be59ba474d5e2a28b4756ff14201 | mayankgb2/Python-Programs | /fortunecookiegame.py | 816 | 3.625 | 4 | #https://www.facebook.com/100028679802914/posts/449717249327598/
# Subscribed by Nikita Desale
import random
print("Your Good Name Please:)__")
n=input()
print(n+" Your fortune cookie says")
fortune = random.randint(1,8)
if fortune == 1:
print("Good things happen just wait and have Patience")
elif fortune == 2:
print("Oho, A lovely day you have today")
elif fortune == 3:
print("The early bird gets the worm.")
elif fortune == 4:
print("Your intuitions will make yiur day!")
elif fortune == 5:
print("Now is the time to try something new!")
elif fortune == 6:
print("Today it is up to you to create a peacefulness you long for")
elif fortune == 7:
print("You will be hungry again in one hour.")
elif fortune == 8:
print("Fortune cookies rarely share fortunes.")
print("\nHave a nice day")
|
38d9ebd1469ba9106d4907c5002bac12d358ca7f | AchimGoral/DI_Bootcamp | /DI_Bootcamp/Week_5/Day_2/exercise_3_from_1_dogs.py | 1,056 | 3.546875 | 4 | import exercise_1_dogs as ex
import random as rd
class PetDog(ex.Dog):
def __init__(self, name, age, weight):
super().__init__(name, age, weight)
self.trained = False
def train(self):
self.bark()
return self.trained = True
def play(self, *dog_names):
dogs = ', '.join(dog_names.name)
print(f"the dogs: {dogs} play together")
return dog_names.trained = False
def do_a_trick(self, *dog_names):
number = rd.randint(0, 3)
if self.trained = True:
if number == 0:
print(f"{dog_names.name} does a barrel roll")
dog_names.trained = False
elif number == 1:
print(f"{dog_names.name} stands on their back legs")
dog_names.trained = False
elif number == 2:
print(f"{dog_names.name} shakes your hand")
dog_names.trained = False
else:
print(f"{dog_names.name} plays dead")
dog_names.trained = False |
0ff5a476c7d1249e26904debb90dc92126988936 | waltercardona/taller_Carlos_Python | /Taller_1.py | 4,394 | 4.21875 | 4 |
#TALLER UNO
# PUNTO/1
# Dados los valores ingresados por el usuario
# (base, altura) mostar en pantalla el area de un triangula
"""base=int(input("ingrese el base del triangulo\n"))
altura=int(input("ingrese la altura del triangulo\n"))
area = base * altura / 2
print("el area es del triangulo es :",area)"""
# PUNTO/2
# Convertir la cantidad de dolares
# ingresados por el usaurio
# a pesos colombianos y mostrar en pantalla el resultado
"""dolares=int(input("ingrese la cantidad de dolares\n"))
valor_pesos=int(input("valor en pesos Colombianos\n"))
resultado=dolares*valor_pesos
print("el valor es:",resultado)"""
# PUNTO/3
# convertir los grados centigrados ingresados
# por un usaurio a grados fahreinhait y mostrar el resultado
# en pantalla
"""grados_centigrados=float(input("ingrese los centigrados:\n"))
grados_fahrenheit= (grados_centigrados*(9/5))+32
print(grados_centigrados ,"Grados centigrados: Los grados centigrados convertidos a grados fahrenheit es :",grados_fahrenheit , "grados fahrenheit")"""
# PUNTO/4
# mostrar en pantalla la cantidad de segundos que tiene un lustro
"""años=int(5)
dias=int(365)
horas=int(24)
minutos=int(60)
segundos=int(60)
dia_biciesto =int(86400)
lustro=(segundos*minutos*horas*dias*años) + dia_biciesto
print("la cantidad de segundos que tiene un lustro es:",lustro, " millones de segundos")"""
# PUNTO/5
#calcular la cantidad de segundos que le toma viajar la luz del sol a marte y mos trarlo en pantalla
"""distancia_sol_marte=227940000 # millones de kilometros
velocidad_luz=300000 # m/s
total_segundos=int(distancia_sol_marte/velocidad_luz)
minutos = 60
total_minutos =int(total_segundos/minutos)
print("la cantidad de segundos que se demora en viajar la luz del sol a marte es de:",total_segundos, " segundos")
print("la cantidad de minutos que se demora en viajar la luz del sol a marte es de :",total_minutos, "minutos")"""
# PUNTO/6
# calcular el numero de vueltas que da una llanta en 1km, dado que el diametro es de 50cm,
# mostrar el resulktado en pantalla
"""centimetros=100000
diametro_llanta=int(50)
total_vueltas=centimetros/diametro_llanta
print("la cantidad de vuelta que dio la llanta es:",total_vueltas, "vueltas")"""
# PUNTO/7
# calcular y mostrar en pantalla la longitud de la sombra de un edificio de 20 metros
# de altura cuando el angulo que forma los rayos del sol con el suelo es de 22º
"""import math
altura=20
angulo=float(math.radians(22))
angulo1=math.radians(angulo)
sombra=altura/math.tan(22)
print(sombra)"""
# PUNTO/8
# mostrar en pantalla True o false si la edad ingresada por dos usaurios es la misma
"""edad_1=int(input("ingrese edad uno:\n"))
edad_2=int(input("ingrese edad dos:\n"))
igual=edad_1==edad_2
print(igual)"""
# PUNTO/9
# mostrar en pantalla la cantidad de meses trascurridos desde la fecha de nacimienro de un usaurio
"""from datetime import date
def cantidad_meses (fecha_nacimiento):
fecha_actual = date.today()
resultado = fecha_actual.year - fecha_nacimiento.year
meses = resultado * 12
return meses
fecha_nacimiento_walter = date(1986,10,10)
meses = cantidad_meses(fecha_nacimiento_walter)
print(" la cantidad de meses de walter es de :", meses, "meses")"""
# PUNTO/9
# profe esta es la forma de conseguir los dias desde mi fecha de nacimiento
from datetime import date
anio = int(input("Ingrese Año de nacimiento\n"))
mes = int(input("Ingrese mes de nacimiento\n"))
dia = int(input("Ingrese dia de nacimiento\n"))
fecha_de_nacimiento = date(anio,mes,dia)
hoy= date.today()
meses = (hoy.year - anio) *12 + (hoy.month - mes)
print("lacantidad de meses trascurridos desde su fecha de nacimiento son de :", meses)
# mostrar en pantalla el promedio de un alumno que ha cursado 5 materias
# (español, matematicas, programacion, economia, ingles)
"""español=float(input("nota de Español:\n"))
matematicas=float(input("nota de Matematicas:\n"))
economia=float(input("nota de Economia:\n"))
programacion=float(input("nota de Programacion:\n"))
ingles=float(input("nota de Ingles:\n"))
promedio= (español + matematicas + economia + programacion + ingles)/5
print("tu promedio es",promedio)"""
|
75d0c24092b9a9ea8d3d5355026a5210186a7da5 | nasa/bingo | /bingo/variation/add_random_individuals.py | 2,465 | 3.90625 | 4 | """variation that adds random individual(s)
This module wraps a variation in order to supply random individual(s) to the
offspring after the variation is carried out.
"""
import numpy as np
from .variation import Variation
class AddRandomIndividuals(Variation):
"""A variation object that takes in an implementation of variation that
adds a random individual to the population before performing variation.
Parameters
----------
variation : variation
variation object that performs the variation among individuals
chromosome_generator : Generator
Generator for random individual
num_rand_indvs : int
The number of random individuals to generate per call
"""
def __init__(self, variation, chromosome_generator, num_rand_indvs=1):
super().__init__(variation.crossover_types, variation.mutation_types)
self._variation = variation
self._chromosome_generator = chromosome_generator
self._num_rand_indvs = num_rand_indvs
def __call__(self, population, number_offspring):
"""Generates a number of random individuals and adds them to the
population then performs variation on the new population.
Parameters
----------
population : list of chromosomes
The population on which to perform variation
number_offspring : int
number of offspring to produce.
Returns
-------
list of chromosomes :
The offspring of the original population and the
new random individuals
"""
children = self._variation(population, number_offspring)
self.mutation_offspring_type = self._variation.mutation_offspring_type
self.crossover_offspring_type = self._variation.crossover_offspring_type
self.offspring_parents = self._variation.offspring_parents
return self._generate_new_pop(children)
def _generate_new_pop(self, population):
for _ in range(self._num_rand_indvs):
random_indv = self._chromosome_generator()
population.append(random_indv)
self.offspring_parents.extend([[]] * self._num_rand_indvs)
self.crossover_offspring_type = np.hstack(
(self.crossover_offspring_type, np.zeros(self._num_rand_indvs)))
self.mutation_offspring_type = np.hstack(
(self.mutation_offspring_type, np.zeros(self._num_rand_indvs)))
return population
|
8b7086f5616dd49627e8b548740fdf0ac6d909f4 | kdheejb7/baekjoon-Algorithm | /백준/4344_평균은넘겠지.py | 231 | 3.671875 | 4 | for _ in range(int(input())):
scoreList = list(map(int,input().split()))
average = sum(scoreList[1:])/scoreList[0]
print("%0.3f"%round(len([i for i in scoreList[1:] if i > average])/scoreList[0]*100, 3),'%',sep='')
|
a11062d58ce22784e3bf291f30eb2a575cb9e5a7 | apollopower/interview-prep | /python/python_questions/reverse_string_in_place.py | 278 | 3.9375 | 4 | def reverse_string_in_place(str_list):
left = 0
right = len(str_list) - 1
while left < right:
str_list[left], str_list[right] = str_list[right], str_list[left]
left += 1
right -= 1
return str_list
print(reverse_string_in_place(['j','o','n','a','s'])) |
142e95c36e206295330edb8c3e321394ce59f8cf | balupabbi/Practice | /Apple/DataStuff/NestedToFlatten.py | 1,476 | 4.03125 | 4 | """
https://www.geeksforgeeks.org/python-convert-nested-dictionary-into-flattened-dictionary/
Given a nested dictionary, the task is to convert this dictionary into a flattened
dictionary where the key is separated by ‘_’ in case of the nested key to be started.
"""
def helper(nd,out):
for k,v in nd.items():
if isinstance(v,dict):
out = helper(v,out)
else:
out.append(v)
return out
def nested_to_list(nd):
out = []
for k, v in nd.items():
item = []
item.append(k)
if isinstance(v,dict):
item = helper(v,item)
out.append(item)
return out
def flattenNaive(nd,separator):
out = {}
for k, v in nd.items():
if isinstance(v,dict):
res = flattenNaive(v,separator)
for k2, v2 in res.items():
inside_key = k2
value = v2
out[k + separator + inside_key] = value
else:
out[k] = v
return out
if __name__ == '__main__':
input = {'geeks': {'Geeks': {'for': 7}}, 'Geeks': {'for': {'geeks': 4, 'for': 1}}, 'for': {'geeks': {'Geeks': 3}}}
print(flattenNaive(input, separator='_'))
# nd = {
# 1: {'header':'H1', 'body': 'B1', 'footer': 'F1'},
# 2: {'header':'H2', 'body': 'B2', 'table': {'r1':'100','r2':'200','r3':{'rr1':'1000'}}, 'footer': 'F2'}
# }
#
# print(nested_to_list(nd))
#print(output)
|
26d3e8f6cc5171b6ba04955243cdaedb82477d20 | guotian001/DataStructure-python- | /chapt4_tree_second/BinarySearchTree.py | 3,328 | 4.15625 | 4 | # encoding:utf-8
'''
二叉搜索树,BST
左子树都小于结点的值,右子树都大于结点的值
'''
class BinTreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
# 递归查找
def find_recursion(tree, X):
if tree==None:
return None
if X > tree.data:
return find_recursion(tree.right, X) # 尾递归
elif X < tree.data:
return find_recursion(tree.left, X) # 尾递归
else:
return tree
# 迭代查找
def find_iteration(tree, X):
while tree:
if X > tree.data:
tree = tree.right
elif X < tree.data:
tree = tree.left
else:
return tree
return None # 查找失败
# 查找最大最小元素
'''
最大元素一定在最右分支的端结点上(最右叶结点)
最小元素一定在最左分支的端结点上(最左叶节点)
'''
def findMin(tree):
if not tree:
return None
# 如果存在左结点,则递归到左分支上
elif tree.left:
return findMin(tree.left)
# 否则就返回
else:
return tree
def findMax(tree):
while tree:
if tree.right:
tree = tree.right
else:
return tree
return None
# 精简后的代码
# if tree:
# while tree.right:
# tree = tree.right
# return tree
# 递归插入
def insert(tree, X):
# 递归出口
if not tree:
tree = BinTreeNode(X) # tree改变不能改变函数体外的值,因此需要返回出去,重新赋值一次
else:
if X > tree.data:
tree.right = insert(tree.right, X)
elif X < tree.data:
tree.left = insert(tree.left, X)
# 相等则不用插入
return tree # 最后将tree返回, 也不为过
# 删除元素,递归
# 先找到待删除节点 三种情况
# 1. 无子节点,直接删除,即node= None即可
# 2. 有一个结点
# 有左: 把左结点替上,node = node.left
# 有右: 把右结点替上 node = node.right
# 3. 有左右结点
# 选一个结点替代该结点,左子树的最大结点或者右子树的最小结点(为了替代后仍是二叉搜索树),然后再子树中再删除该结点(递归)
def delete(tree, X):
# 递归出口
if not tree:
print '待删除结点未找到'
else:
if X > tree.data:
tree.right = delete(tree.right, X)
elif X < tree.data:
tree.left = delete(tree.left, X)
else: # 找到
if not tree.left: # 存在右结点或者不存在子节点
tree = tree.right
elif not tree.right:
tree = tree.left
else: # 左右结点都存在
# 从右子树找
temp = findMin(tree.right)
tree.data = temp.data
tree.right = delete(tree.right, temp.data)
return tree # 重新赋值一次是最保险的,不用担心值传递引起的问题。反正重新赋值一次是肯定能可以的
def init():
tree = None
tree = insert(tree, 'Jan')
tree = insert(tree, 'Feb')
tree = insert(tree, 'Mar')
return tree
tree = init()
print tree
|
541a528536eb20c8b2d638a4196643c6a65094d2 | ShathyaPeriaswamy/Python-Programming | /Beginner Level/set1g.py | 121 | 3.71875 | 4 | i=raw_input()
t=int(i)
if(t>0):
for n in range (t):
print 'Hello'
elif(t==0):
print " "
else:
print "invalid input"
|
5889c678834bd2f7465fda691d1c1d27739e4c9e | girscr/Pygame_Scene | /functions_practice.py | 697 | 4.40625 | 4 | import math
def distance (x1, y1, x2, y2):
'''calculates the distance between the
two points given'''
dist = math.sqrt((x1-x2)**2 + (y1-y2)**2)
return dist
def in_circle(center_x, center_y, radius, other_x, other_y):
'''determines whether a given point lies
within the circle'''
#get the distance between the center and given point
new_dist = distance(center_x, center_y, other_x, other_y)
#compare the distance with the radius
if new_dist > radius:
print ('The given point is outside the circle')
elif new_dist == radius:
print ('The given point is on the circle')
else:
print('The given point is inside the circle')
|
79aa61b5c6701d3d07db2f38837f10bf493dded2 | giuliasteck/MC102 | /lab05/lab05.py | 1,060 | 3.796875 | 4 | """
Nome: Giulia Steck
RA: 173458
"""
lista =[]
N = int(input())
for i in range(N):
entrada = input()
lista.append(entrada)
hashtag = 0
emoticon = 0
for i in (lista):
a = i.isdigit()
b = i.isalpha()
#printar números positivos e palavras
if a == True:
print(i)
elif b == True:
print(i)
#printar números negativos
elif i[0] == '-':
checarNumero = i[1:]
cN = checarNumero.isdigit()
if cN == True:
print(i)
else:
emoticon += 1
#checar hashtags e emoticons
elif i[0] == '#':
checarPalavra = i[1:]
cP = checarPalavra.isalpha()
if cP == True:
hashtag += 1
elif cP == False:
emoticon += 1
else:
emoticon += 1
if hashtag > 1:
print (hashtag,'hashtags foram removidas.')
elif hashtag == 1:
print (hashtag,'hashtag foi removida.')
if emoticon > 1:
print (emoticon,'emoticons foram removidos.')
elif emoticon == 1:
print (emoticon,'emoticon foi removido.')
|
20a132c2d9f613633de5b081c29985446b507bd2 | JamieCass/pynotes | /card_test.py | 4,266 | 4.28125 | 4 | import unittest
from cards_final import Card, Deck
class CardTests(unittest.TestCase):
def setUp(self):
self.card = Card('A', 'Spades')
def test_init(self):
"""Each card should have a suit and a value"""
self.assertEqual(self.card.suit, 'Spades')
self.assertEqual(self.card.value, 'A')
def test_repr(self):
"""Should return a f string with the VALUE folowed by the SUIT"""
self.assertEqual(repr(self.card),'A of Spades')
class DeckTests(unittest.TestCase):
def setUp(self):
self.deck = Deck()
def test_init(self):
"""init should have a list of 52 cards with values and suits"""
self.assertTrue(isinstance(self.deck.cards, list))
self.assertEqual(self.deck.count(), 52)
def test_repr(self):
"""Should return a f string with how many cards are in the deck"""
self.assertEqual(repr(self.deck), 'Deck of 52 cards')
def test_count(self):
"""count should tell how many cards are in the deck, and change everytime cards are dealt"""
self.assertEqual(self.deck.count(), 52)
self.deck.cards.pop() #we take a card away and make sure count will display 1 card less when its called on.
self.assertEqual(self.deck.count(), 51) # now the deck should have 1 less card in than before.
def test_deal_sufficent_cards(self):
"""_deal should deal the amount of cards required, as long as there are enough cards left in the deck"""
cards = self.deck._deal(10) # deal 10 cards
self.assertEqual(len(cards), 10) # check to see if the length of cards dealt matches the the number stated (10)
self.assertEqual(self.deck.count(), 42) # check the deck now has '10' cards less than before
def test_deal_insufficent_cards(self):
"""_deal should only deal however many cards are in the deck"""
cards = self.deck._deal(57) # try and deal 57 cards
self.assertEqual(len(cards), 52) # Check to see if the fresh deck is 52 cards and therefore will only deal 52 cards in the hand.
self.assertEqual(self.deck.count(), 0) # the deck will now have no cards left.
def test_deal_no_cards(self):
"""_deal should come up with an error message if there are not cards in the deck"""
self.deck._deal(self.deck.count())# dealing the count of cards in the deck (the wont be anly left aftet this line.)
with self.assertRaises(ValueError):
self.deck._deal(1) # try and deal 1 more card after we have dealt the rest of the deck. it will raise an error.
def test_deal_card(self):
"""deal card should only deal 1 card at a time"""
card = self.deck.cards[-1] # take a card out of the deck
dealt_card = self.deck.deal_card() # call the _deal function
self.assertEqual(card, dealt_card) # make sure the 'dealt_card' and the 'card' are the same
self.assertEqual(self.deck.count(), 51) # make sure there is 1 less card in the deckafter we have called the _deal function.
def test_deal_hand(self):
"""deal_hand should deal the amount of cards you define, and take them out of the deck of cards"""
cards = self.deck.deal_hand(10) # we just have to use the same code as the test_deal_sufficent_cards test.
self.assertEqual(len(cards), 10)
self.assertEqual(self.deck.count(), 42)
def test_shuffle_low_cards(self):
"""shuffle should bring an error message up if there isnt a full deck to shuffle"""
self.deck.deal_card() # deal 1 card out of the deck
with self.assertRaises(ValueError): # check to see if the ValueError will be triggered (because there isnt a full deck of cards anymore)
self.deck.shuffle() # try and shuffle and it will error.
def test_shuffle_full_deck(self):
"""shuffle should shuffle the cards in the deck."""
cards = self.deck.cards[:] # make a fresh deck of cards
self.deck.shuffle() # shuffle the deck of cards
self.assertNotEqual(cards, self.deck.cards) # check to see if the cards deck is not the same as the shuffled deck!
self.assertEqual(self.deck.count(), 52) # also make sure the deck of cards is 52!
if __name__ == "__main__":
unittest.main()
|
c16da698b0c305d54136236a706b6211c699bf5c | Krishnaanurag01/PythonPRACTICE | /bubbleSORT.py | 529 | 3.71875 | 4 | l=[int(x) for x in input().split()]
# for i in range(len(data)):
# for j in range(len(data)-1):
# if data[j+1]<data[j]:
# data[j+1],data[j]=data[j],data[j+1]
# print(data)
def swap(a,b):
a,b=b,a
return a,b
# ans=[[swap(data[j+1],data[j]) for j in range(len(data)-1) if data[j+1]<data[j] ] for i in range(len(data))]
def bubblesort(l):
[l.append(l.pop(0) if i == len(l) - 1 or l[0] < l[1] else l.pop(1)) for j in range(0, len(l)) for i in range(0, len(l))]
return l
print(bubblesort(l)) |
c4c4cc5bea0b7687d2388b77dcb160aeaa98426f | rksaxena/leetcode_solutions | /longest_univalue_path.py | 1,361 | 4.125 | 4 |
__author__ = Rohit Kamal Saxena
__email__ = [email protected]
"""
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
self.max = 0
self.findLen(root)
return self.max
def findLen(self, root):
if root is None:
return 0
left_len = self.findLen(root.left)
right_len = self.findLen(root.right)
max_left = 0
max_right = 0
if root.left and root.left.val == root.val:
max_left = left_len + 1
if root.right and root.right.val == root.val:
# include right node
max_right = right_len + 1
self.max = max(self.max, max_left + max_right)
return max(max_left, max_right)
|
399c075fac99fdd022b771679d55b633ddb8feb2 | abisha22/S1-A-Abisha-Accamma-vinod | /Programming Lab/27-01-21/prgm7abc.py | 982 | 3.96875 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> list1=[12,3,4,56,7,8,9,19,34,87]
>>> list2=[10,4,67,89,4,77,29,5,7,8]
>>> len1=len(list1)
>>> len2=len(list2)
>>> if len1==len2:
print('Both list have equal length')
else:
print('Both list doesnot have equal length')
Both list have equal length
>>> list1=[12,3,4,56,7,8,9,19,34,87]
>>> list2=[10,4,67,89,4,77,29,5,7,8]
>>> total1=sum(list1)
>>> total2=sum(list2)
>>> if total1==total2:
print('Both list have equal sum')
else:
print('Both list doesnot have equal sum')
Both list doesnot have equal sum
>>> list1=[12,3,4,56,7,8,9,19,34,87]
>>> list2=[10,4,67,89,4,77,29,5,7,8]
>>> for value in list1:
if value in list2:
common=1
>>> if common==1:
print("There are common element")
else:
print("There is no common element")
There are common element
>>> |
63ad1db21c2012e1a76ea8470a50a4ed10ab1f96 | Mud-Phud/my-python-scripts | /DataCamp tutorial on matplotlib/datacamp-subplot matplotlib.py | 567 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 23:59:03 2020
@author: robert
DataCamp using subplot()
"""
import numpy as np
import matplotlib.pyplot as plt
# generate some data...
t = np.array(range(14))
temperature = t*6/14+27+np.random.normal(0,1,14) # linear growth in time plus random
dewpoint = 10*(35-temperature)**(-0.5)
plt.subplot(2,1,1)
plt.plot(t,temperature,'r')
plt.xlabel('Day')
plt.title('Temperature')
plt.subplot(2,1,2)
plt.plot(t,dewpoint,'b')
plt.xlabel('Day')
plt.title('Dewpoint')
plt.tight_layout()
plt.show() |
b3092e6bc3f609eaf90f19a2023dd6975a5f9346 | Robostorm/Aquabot-Bluetooth-Receiver | /pygameController.py | 3,956 | 3.515625 | 4 | import pygame
import config
pygame.init()
# Initialize the joysticks.
pygame.joystick.init()
class struct: pass
inputs = struct()
# -------- Main Program Loop -----------
def getInputs():
#
# EVENT PROCESSING STEP
#
# Possible joystick actions: JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN,
# JOYBUTTONUP, JOYHATMOTION
for event in pygame.event.get(): # User did something.
if event.type == pygame.QUIT: # If user clicked close.
done = True # Flag that we are done so we exit this loop.
# Get count of joysticks.
joystick_count = pygame.joystick.get_count()
if joystick_count > 1:
config.telemetry["controller"] = "Error: more than one controller is connected"
print(config.telemetry)
quit()
elif joystick_count < 1:
config.telemetry["controller"] = "Error: no controller connected"
print(config.telemetry)
quit()
joystick = pygame.joystick.Joystick(0)
joystick.init()
try:
jid = joystick.get_instance_id()
except AttributeError:
# get_instance_id() is an SDL2 method
jid = joystick.get_id()
# Get the name from the OS for the controller/joystick.
name = joystick.get_name()
try:
guid = joystick.get_guid()
except AttributeError:
# get_guid() is an SDL2 method
pass
#else:
#textPrint.tprint(screen, "GUID: {}".format(guid))
# Usually axis run in pairs, up/down for one, and left/right for the other.
axes = joystick.get_numaxes()
inputs.left_stick_x = round(joystick.get_axis(0), 2)
inputs.left_stick_y = round(joystick.get_axis(1), 2)
inputs.left_trigger = round(joystick.get_axis(2), 2)
inputs.right_stick_x = round(joystick.get_axis(3), 2)
inputs.right_stick_y = round(joystick.get_axis(4), 2)
inputs.right_trigger = round(joystick.get_axis(5), 2)
inputs.buttons = joystick.get_numbuttons()
if name == "Sony Computer Entertainment Wireless Controller":
inputs.a = joystick.get_button(0)
inputs.b = joystick.get_button(1)
inputs.x = joystick.get_button(3)
inputs.y = joystick.get_button(2)
inputs.left_bumper = joystick.get_button(4)
inputs.right_bumper = joystick.get_button(5)
inputs.view = joystick.get_button(8)
inputs.menu = joystick.get_button(9)
inputs.guide = joystick.get_button(10)
inputs.left_stick_button = joystick.get_button(11)
inputs.right_stick_button = joystick.get_button(12)
config.telemetry["controller"] = "PlayStation Controller"
elif name == "Microsoft X-Box One S pad":
inputs.a = joystick.get_button(0)
inputs.b = joystick.get_button(1)
inputs.x = joystick.get_button(2)
inputs.y = joystick.get_button(3)
inputs.left_bumper = joystick.get_button(4)
inputs.right_bumper = joystick.get_button(5)
inputs.view = joystick.get_button(6)
inputs.menu = joystick.get_button(7)
inputs.guide = joystick.get_button(8)
inputs.right_stick_button = joystick.get_button(9)
inputs.left_stick_button = joystick.get_button(10)
config.telemetry["controller"] = "Xbox Controller"
else:
config.telemetry["controller"] = "Unknown Controller"
hats = joystick.get_numhats()
inputs.dpad_left = 0
inputs.dpad_right = 0
inputs.dpad_down = 0
inputs.dpad_up = 0
# Hat position. All or nothing for direction, not a float like get_axis(). Position is a tuple of int values (x, y).
inputs.dpad = joystick.get_hat(0)
# Split the single dpad touple into 4 variables representing each button on the dpad
if inputs.dpad[0] == -1:
inputs.dpad_left = 1
elif inputs.dpad[0] == 1:
inputs.dpad_right = 1
elif inputs.dpad[1] == -1:
inputs.dpad_down = 1
elif inputs.dpad[1] == 1:
inputs.dpad_up = 1
|
96d69cfa49ac04e275a53d72bf651bc305f34dba | SergeyKodochigov/Python | /1 lab/12.py | 107 | 3.609375 | 4 | a = (input('Введите слово'))
g = a[::-1]
if a == g:
print("yes")
else:
print("no")
|
c34ea3d52e81320078ddd0b6874600533cc1837b | loucerac/pybel | /src/pybel/struct/filters/node_filters.py | 3,266 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""Filter functions for nodes in BEL graphs.
A node predicate is a function that takes two arguments: a :class:`BELGraph` and a node. It returns a boolean
representing whether the node passed the given test.
This module contains a set of default functions for filtering lists of nodes and building node predicates.
A general use for a node predicate is to use the built-in :func:`filter` in code like
:code:`filter(your_node_predicate, graph)`
"""
from typing import Iterable, Set
from .typing import NodePredicate, NodePredicates
from ..graph import BELGraph
from ...dsl import BaseEntity
__all__ = [
'invert_node_predicate',
'concatenate_node_predicates',
'filter_nodes',
'get_nodes',
'count_passed_node_filter',
]
def invert_node_predicate(node_predicate: NodePredicate) -> NodePredicate: # noqa: D202
"""Build a node predicate that is the inverse of the given node predicate."""
def inverse_predicate(graph: BELGraph, node: BaseEntity) -> bool:
"""Return the inverse of the enclosed node predicate applied to the graph and node."""
return not node_predicate(graph, node)
return inverse_predicate
def concatenate_node_predicates(node_predicates: NodePredicates) -> NodePredicate:
"""Concatenate multiple node predicates to a new predicate that requires all predicates to be met.
Example usage:
>>> from pybel.dsl import protein, gene
>>> from pybel.struct.filters.node_predicates import not_pathology, node_exclusion_predicate_builder
>>> app_protein = protein(name='APP', namespace='HGNC')
>>> app_gene = gene(name='APP', namespace='HGNC')
>>> app_predicate = node_exclusion_predicate_builder([app_protein, app_gene])
>>> my_predicate = concatenate_node_predicates([not_pathology, app_predicate])
"""
# If a predicate outside a list is given, just return it
if not isinstance(node_predicates, Iterable):
return node_predicates
node_predicates = tuple(node_predicates)
# If only one predicate is given, don't bother wrapping it
if 1 == len(node_predicates):
return node_predicates[0]
def concatenated_node_predicate(graph: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a nodes that pass all enclosed predicates."""
return all(
node_predicate(graph, node)
for node_predicate in node_predicates
)
return concatenated_node_predicate
def filter_nodes(graph: BELGraph, node_predicates: NodePredicates) -> Iterable[BaseEntity]:
"""Apply a set of predicates to the nodes iterator of a BEL graph."""
concatenated_predicate = concatenate_node_predicates(node_predicates=node_predicates)
for node in graph:
if concatenated_predicate(graph, node):
yield node
def get_nodes(graph: BELGraph, node_predicates: NodePredicates) -> Set[BaseEntity]:
"""Get the set of all nodes that pass the predicates."""
return set(filter_nodes(graph, node_predicates=node_predicates))
def count_passed_node_filter(graph: BELGraph, node_predicates: NodePredicates) -> int:
"""Count how many nodes pass a given set of node predicates."""
return sum(1 for _ in filter_nodes(graph, node_predicates=node_predicates))
|
e6ae882498cfc5094d964d1ee2a06cf270d49012 | rakitaj/daily-programmer | /hackerrank/problemsolving.py | 2,790 | 3.734375 | 4 | from typing import Sequence, List, Tuple
import re
import itertools
import sys
import time
def simple_sum_array(count: int, numbers: Sequence[int]) -> int:
return sum(numbers)
def compare_the_triplets(alice: Tuple[int, int, int], bob: Tuple[int, int, int]) -> Tuple[int, int]:
alice_score = 0
bob_score = 0
for index, element in enumerate(alice):
if alice[index] > bob[index]:
alice_score += 1
elif bob[index] > alice[index]:
bob_score += 1
else:
pass
return (alice_score, bob_score)
def diagonal_difference(matrix: List[List[int]]) -> int:
diagonal_forward = 0
diagonal_backward = 0
for i in range(0, len(matrix)):
diagonal_forward += matrix[i][i]
j = len(matrix) - 1 - i
diagonal_backward += matrix[j][i]
return abs(diagonal_forward - diagonal_backward)
def plus_minus(numbers: List[int]) -> Tuple[float, float, float]:
size = len(numbers)
positive_count = 0
negative_count = 0
zero_count = 0
for n in numbers:
if n > 0:
positive_count += 1
elif n < 0:
negative_count += 1
else:
zero_count += 1
return (positive_count/size, negative_count/size, zero_count/size)
def staircase(count: int) -> str:
result = ""
for i in range(1, count + 1):
spaces = " " * (count - i)
hashes = "#" * i
result += f"{spaces}{hashes}\n"
return result
def mini_max_sum(numbers: List[int]) -> Tuple[int, int]:
combinations = itertools.combinations(numbers, 4)
max_sum = 0
min_sum = sys.maxsize
for combination in combinations:
total = sum(combination)
if total > max_sum:
max_sum = total
if total < min_sum:
min_sum = total
return (min_sum, max_sum)
def permute(data):
if len(data) <= 1:
return [data]
res = []
for i, c in enumerate(data):
for r in permute(data[:i]+data[i+1:]):
res.append([c]+r)
return res
def birthday_cake_candles(candle_heights: List[int]) -> int:
max_height = max(candle_heights)
candles_of_that_height = filter(lambda x: x == max_height, candle_heights)
return len(list(candles_of_that_height))
def time_conversion(time_12h: str) -> str:
pattern_am_12 = re.compile("12:..:..AM")
pattern_pm_12 = re.compile("12:..:..PM")
pattern_am = re.compile("..:..:..AM")
pattern_pm = re.compile("..:..:..PM")
if pattern_am_12.match(time_12h):
return "00" + time_12h[2:-2]
elif pattern_am.match(time_12h) or pattern_pm_12.match(time_12h):
return time_12h[:-2]
else:
hours = int(time_12h.split(":")[0])
hours = (hours + 12) % 24
return str(hours) + time_12h[2:-2]
|
77cbca8a0a18712a896957221d605529d386909a | rmgard/py_deep_dive_2 | /2.6_sequence_types.py | 1,842 | 4.34375 | 4 | l = [1, 2, 3]
t = (1, 2, 3)
s = 'python'
""" the above are all sequence types which are indexable and iterable.
We can reference elements inside the sequence by their indeces
l[0] = 1
t[1] = 2
s[2] = 't'
"""
""" We can also loop or iterate over them:
"""
for c in s:
print (c)
####################################################################
# Sets are also iterable
# They are not sequence types, so they don't support indexing
# something such as set1[1] would return an error
set1 = {10, 20, 30}
for e in set1:
print(e)
set2 = {'x', 10, 'a', 'A'}
for e in set2:
print(e)
""" A list is mutable, so we can reassign elements. Thus,
l[0] = 100
------> l == [100, 2, 3] is true
tuples are immutable, so we could not say:
t[0] = 100
In other words, the memory address of the object can't be changed.
We can alter things with a mutable object within them...
"""
t2 = ([1, 2], 3,4 )
"""
t[0] = [1, 2, 3] will not work.
But, this will work:"""
t2[0][0] = 100
""" most sequence types handle the 'in' and 'not in' operators
"""
'a' in ['a', 'b', 100] # True
100 in range(200) # True
len('python'), len([1, 2, 3]), len({10, 20, 30}), len({'a': 1, 'b':2})
l = [100, 90, 20]
min(l)
max(l)
#min() and max() can't be used on complex numbers... Strings can be supported with inequalities.
# CAT
(1,2,3) + (4,5,6)
list('abc') +['d', 'e', 'f']
'***'.join(['1', '2', '3'])
','.join(['1', '2', '3'])
''.join(['1', '2', '3'])
###################################################################
# enumerate
s = "gnu's not unix"
list(enumerate(s))
s.index('n')
s.index('n', 2)
s.index('n', 1)
s.index('n', 7)
##################################################################
# slicing
s = 'python'
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
s[1:4]
list(enumerate(s))
l[0:5]
s[4:1000]
s[:4]
s[4:]
s[:]
s[5:0:-1]
s[::-1]
|
f023097fe36838da339a4272b1872808bdb41e07 | acep-uaf/MiGRIDS | /MiGRIDS/Model/Operational/getIntListIndex.py | 2,522 | 3.8125 | 4 | # Project: GBS Tool
# Author: Jeremy VanderMeer, [email protected]
# Date: March 1, 2018
# License: MIT License (see LICENSE file of this package for more information)
# get the index of an interger value in a list of continuous sequential intergers
# using integer list indexing is much faster than np.searchsorted
# List is an interger list, with no missing values, with stepsize intervals between values
# value is the value being searched for
# stepsize is the size of the step between values in List
def getIntListIndex(value, List, stepsize = 1):
valueInt = int(value/stepsize)*stepsize # convert to interger
if valueInt < List[0]: # if below range, assigne first value
idx = 0
elif valueInt > List[-1]: # if above range, assigne last value
idx = len(List)-1
else: # otherwise, find index
idx = List.index(valueInt)
return idx
def getIntDictKey(value, valDict, minKeyInDict, maxKeyInDict, stepsize = 1):
'''
Index lookup from continuous sequential dictionary of integers. In order to use something like the List variable that
is the input to getIntListIndex the following conversion (performed outside of loops) can be used
valDict = dict(zip(List, range(len(List))). It is also useful to precalculate the min and max value in the Dict
(technically the min and max key) at that time to avoid repeated calls to min and max functions, which is costly, as
this function is most often called in a loop across a time-series.
:param value: [float] value to find the index for
:param valDict: [dict] integer values for which an index is to be looked up for are the keys to this dict. Indices
are returned by valDict[valueInt].
:param minValInDict: [int] minimum key in the dictionary. If the input value is lower, the default key assigned is 0
:param maxValInDict: [int] maximum key in the dictionary. If the input value is higher, the default key assigned is largest available.
:param stepsize: [float] the size of the step between keys in dictionary
:return idx: an integer value corresponding to the key in the input dictionary, associated with the looked up value
'''
valueInt = int(value / stepsize) * stepsize # convert to interger
maxIdx = len(valDict) - 1
if valueInt < minKeyInDict: # if below range, assigne first value
idx = 0
elif valueInt > maxKeyInDict: # if above range, assigne last value
idx = maxIdx
else: # otherwise, find index
idx = valDict[valueInt]
return idx |
33e2592ffe14019a73116155e76b05db79ec9495 | Ferveloper/python-exercises | /KC_EJ25.py | 486 | 3.75 | 4 | #-*- coding: utf-8 -*
import random
random = random.randint(1, 100)
for i in range(1, 6):
guess = input('Escribe un número: ')
if (guess != random and i != 5):
print('Intenta con un número %s (te quedan %s oportunidad%s)' %('menor' if guess > random else 'mayor', 5 - i, 'es' if i != 4 else ''))
else:
break
if guess == random:
print('¡Bien, lo has adivinado :D! Era el %s' %(random))
else:
print('Lo siento, has perdido. Era el %s' %(random)) |
2be00c4384f631f71afd881d78e0478dd55c3609 | sheetaljantikar/python-codes | /hash_new.py | 1,512 | 3.546875 | 4 | class hashmap():
def __init__(self,size):
self.size=size
self.map=[None]*size
def get_hash(self,key):
hash=0
for char in str(key):
hash+=ord(char)
return hash%self.size
def add(self,key,value):
hash_value=self.get_hash(key)
l=[key,value]
if self.map[hash_value]==None:
self.map[hash_value]=list(l)
return True
else:
for pair in self.map[hash_value]:
if pair[0]==key:
pair[1]=value
return True
self.map[hash_value].append(l)
return True
def get(self,key):
hash_value=self.get_hash(key)
if self.map[hash_value] is not None:
for pair in self.map[hash_value]:
if pair[0]==key:
return pair[1]
return None
def delete(self,key):
hash_value=self.get_hash(key)
if self.map[hash_value] is None:
return False
for i in range(0,len(self.map[hash_value])):
if self.map[hash_value][i][0]==key:
self.map[hash_value].pop(i)
return True
def print(self):
for item in self.map:
if item is not None:
print(str(item))
a=hashmap(5)
a.add('sheetal','5865555')
a.add('shreyu','9999')
a.add('sangeeta','370')
a.print()
a.get('sangeeta')
|
7d388b1a977ea1a5681d6d3f6d520ae67eff55d8 | calciumhs/calciumAAA | /yufang/pythonnn/matrix.py | 544 | 3.578125 | 4 | a=[]
b=[]
c=[[0,0,0],[0,0,0],[0,0,0]]
for j in range(3):
a1=[eval(i) for i in input().split()]
a.append(a1)
for j in range(3):
b1=[eval(i) for i in input().split()]
b.append(b1)
def matrixMultiPly(a, b):
for i in range(3):
c[i][0]=a[i][0]*b[0][0]+a[i][1]*b[1][0]+a[i][2]*b[2][0]
c[i][1]=a[i][0]*b[0][1]+a[i][1]*b[1][1]+a[i][2]*b[2][1]
c[i][2]=a[i][0]*b[0][2]+a[i][1]*b[1][2]+a[i][2]*b[2][2]
return c
c=matrixMultiPly(a, b)
print(c[0])
print(c[1])
print(c[2])
|
debd2e4d31660576bf3b0ae62f9483f1d6367e11 | huangqiank/Algorithm | /leetcode/other/convertitle.py | 700 | 3.609375 | 4 | ##168. Excel表列名称
#给定一个正整数,返回它在 Excel 表中相对应的列名称。
#例如,
# 1 -> A
# 2 -> B
# 3 -> C
# ...
# 26 -> Z
# 27 -> AA
# 28 -> AB
# ...
#示例 1:
#输入: 1
#输出: "A"
##只需要注意1 - A而不是0 - A
##①让除数减一,那么余数自然就少一,原来余 1 的变成余 0,以此类推(详细见下表)。
#核心代码 `let remain = (n - 1) % 26;`
class Solution123411:
def convertToTitle(self, n: int) -> str:
s = ''
while n:
n -= 1
# ASCII码转大写字符 并且左加
s = chr(65 + n % 26) + s
n //= 26
return s
## 2 3 4
##4
##2*2 |
495245b874d5927b7d98fb730bbe391d2fb0909f | Laurensvaldez/PythonCrashCourse | /CH4: working with lists/try_it_yourself_ch4.py | 509 | 3.953125 | 4 | print("4-1 Pizzas")
pizza_list = ["Pepperoni", "Margaritha", "BBQ"]
print (pizza_list)
print("______________________________")
for pizza in pizza_list:
print("I like " + pizza + " pizza!")
print("I really love pizza!")
print("______________________________")
print("4-2 Animals")
animal_list = ["dog", "cat", "rabbit"]
for animal in animal_list:
print("A " + animal + " would make a great pet.")
print("Any of these animals would make a great pet!")
print("______________________________")
|
6487c7c42e1fae422faa19598d7e6f06885832a5 | dangliu/TARI | /pythonscripts/vcf_overlap.py | 1,387 | 3.5 | 4 | #!/usr/bin/python3
usage = """
This script is for comparing the overlapping of two vcf.
It was written by Dang Liu. Last updated: May 29 2018.
usage:
python3 vcf_overlap.py vcf1 vcf2
"""
# modules here
import sys, re
# if input number is incorrect, print the usage
if len(sys.argv) < 3:
print(usage)
sys.exit()
# Read vcf1
vcf1_dit = {}
vcf1 = open(sys.argv[1], 'r')
line1 = vcf1.readline()
while(line1):
if ("#" not in line1):
line1_s = re.split(r'\s+', line1)
chro = line1_s[0]
pos = line1_s[1]
ref = line1_s[3]
if (chro not in vcf1_dit):
vcf1_dit[chro] = {}
vcf1_dit[chro][pos] = ref
else:
vcf1_dit[chro][pos] = ref
line1 = vcf1.readline()
# close barcode file
vcf1.close()
# Read vcf2
overlap = 0
incons = 0
vcf2 = open(sys.argv[2], 'r')
line2 = vcf2.readline()
while(line2):
if ("#" not in line2):
line2_s = re.split(r'\s+', line2)
chro2 = line2_s[0]
pos2 = line2_s[1]
ref2 = line2_s[3]
if (chro2 in vcf1_dit):
if (pos2 in vcf1_dit[chro2]):
if (ref2 == vcf1_dit[chro2][pos2]):
print("Found one overlap!")
overlap += 1
else:
print("There is an inconsistency between REFs! {0}* in vcf1 and {1}* in vcf2.".format(vcf1_dit[chro2][pos2], ref2))
incons += 1
line2 = vcf2.readline()
vcf2.close()
print("All done! There are {0:.0f} overlaps and {1:.0f} inconsistencies.".format(overlap, incons))
# last_v20180529 |
de2ddd34c578de105c909d6ddc66693a12737ca2 | wslxko/LeetCode | /tencentSelect/number18.py | 749 | 4.09375 | 4 | '''
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
def mergeTwoLists(self, l1, l2):
newl1 = l1.split('->')
newl2 = l2.split('->')
newl = sorted(newl1 + newl2)
afterMerge = '->'.join(newl)
return afterMerge
if __name__ == "__main__":
a = Solution()
l1 = '1->2->4'
l2 = '1->3->4'
print(a.mergeTwoLists(l1, l2))
|
5da21450988eafbba0f7be2d7199973f70413b07 | AndrewErmakov/PythonTrainingBasics | /DataStructuresAndAlgorithms/SearchAndSort/Sort/Count&CountingSort&Digital(Bitwise)Sorting/anagrams.py | 1,094 | 3.8125 | 4 | first_word = input()
second_word = input()
def counting_sort(word: str):
count_list = [0] * 36
sorted_sequence = []
for symbol in word:
if 'a' <= symbol <= 'z':
count_list[ord(symbol) - 87] += 1
if symbol.isdigit():
count_list[int(symbol)] += 1
for i in range(36):
if count_list[i] > 0:
if i < 10:
sorted_sequence += ((str(i) + ' ') * count_list[i]).split()
else:
sorted_sequence += ((chr(i + 87) + ' ') * count_list[i]).split()
return sorted_sequence
def are_anagrams(symbols_first_word: list, symbols_second_word: list):
len_symbols_first_word, len_symbols_second_word = len(symbols_first_word), len(symbols_second_word)
if len_symbols_first_word != len_symbols_second_word:
return "NO"
else:
for i in range(len_symbols_first_word):
if symbols_first_word[i] != symbols_second_word[i]:
return "NO"
return "YES"
print(are_anagrams(counting_sort(first_word), counting_sort(second_word)))
|
3f1d83ed56275c24c3e0743f9ee73be8e2d1a0d0 | utabe/aoc | /2019/7/part2ampinput.py | 7,546 | 3.65625 | 4 | # --- Part Two ---
# It's no good - in this configuration, the amplifiers can't generate a large enough output signal to produce the thrust you'll need. The Elves quickly talk you through rewiring the amplifiers into a feedback loop:
#
# O-------O O-------O O-------O O-------O O-------O
# 0 -+->| Amp A |->| Amp B |->| Amp C |->| Amp D |->| Amp E |-.
# | O-------O O-------O O-------O O-------O O-------O |
# | |
# '--------------------------------------------------------+
# |
# v
# (to thrusters)
# Most of the amplifiers are connected as they were before; amplifier A's output is connected to amplifier B's input, and so on. However, the output from amplifier E is now connected into amplifier A's input. This creates the feedback loop: the signal will be sent through the amplifiers many times.
#
# In feedback loop mode, the amplifiers need totally different phase settings: integers from 5 to 9, again each used exactly once. These settings will cause the Amplifier Controller Software to repeatedly take input and produce output many times before halting. Provide each amplifier its phase setting at its first input instruction; all further input/output instructions are for signals.
#
# Don't restart the Amplifier Controller Software on any amplifier during this process. Each one should continue receiving and sending signals until it halts.
#
# All signals sent or received in this process will be between pairs of amplifiers except the very first signal and the very last signal. To start the process, a 0 signal is sent to amplifier A's input exactly once.
#
# Eventually, the software on the amplifiers will halt after they have processed the final loop. When this happens, the last output signal from amplifier E is sent to the thrusters. Your job is to find the largest output signal that can be sent to the thrusters using the new phase settings and feedback loop arrangement.
#
# Here are some example programs:
#
# Max thruster signal 139629729 (from phase setting sequence 9,8,7,6,5):
#
# 3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,
# 27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5
# Max thruster signal 18216 (from phase setting sequence 9,7,8,5,6):
#
# 3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,
# -5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,
# 53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10
# Try every combination of the new phase settings on the amplifier feedback loop. What is the highest signal that can be sent to the thrusters?
import operator
import csv
import itertools
phases = itertools.permutations([0,1,2,3,4])
csvFile = open('input.csv')
inputFile = csv.reader(csvFile)
Intcode = [*map(int,next(inputFile))]
originalIntcode = Intcode.copy()
# Test codes
# Intcode = [1,0,0,0,99]
# Intcode =[2,3,0,3,99]
# Intcode = [2,4,4,5,99,0]
# Intcode = [1,1,1,4,99,5,6,0,99]
# Intcode = [1101,100,-1,4,0]
# Intcode[1] = 12
# Intcode[2] = 2
# Intcode = [3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]
# Intcode = [3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0]
amps = [Intcode.copy() for i in range(5)]
gotPhaseInput = [False] * 5
print(gotPhaseInput)
exit()
currentAmp = 0
l = len(Intcode)
maxAmp = 0
for phase in phases:
firstCodes = {0:0,1:phase[0],2:phase[1],3:phase[2],4:phase[3],5:phase[4]}
ampInput = 0
print(phase )
stillProcessing = True
counter = 0
while stillProcessing:
# for phaseInput in phase:
i=0
input3 = [phaseInput, ampInput]
# Intcode = [3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0]
Intcode = amps[currentAmp]
while i < l:
# for i in range(0,len(Intcode),4):
# print(Intcode,i)
code = Intcode[i]
if code > 99:
code = list(str(code))
modes,code = code[:-2][::-1],code[-2:]
modes = list(map(int,modes))
code = int(''.join(code))
else:
modes= [0,0,0]
modes += [0]
# print(code, modes)
if code == 1:
op = operator.add
first, second, store = Intcode[i+1:i+4]
if modes[0] == 0:
first = Intcode[first]
if modes[1] == 0:
second = Intcode[second]
result = op(first, second)
Intcode[store] = result
i += 4
elif code == 2:
op = operator.mul
first, second, store = Intcode[i+1:i+4]
if modes[0] == 0:
first = Intcode[first]
if modes[1] == 0:
second = Intcode[second]
result = op(first, second)
Intcode[store] = result
i += 4
elif code == 3:
store = Intcode[i+1]
Intcode[store] = input3.pop(0)
print('intcode[store]', Intcode[store])
i += 2
elif code == 4:
output = Intcode[i+1]
if modes[0] == 0:
print(Intcode[output]) # final print statement is the answer
ampInput = Intcode[output]
else:
print(output)
ampInput = output
i += 2
elif code == 5: #jump if true
value = Intcode[i+1]
position = Intcode[i+2]
if modes[0] == 0:
value = Intcode[value]
if modes[1] == 0:
position = Intcode[position]
if value != 0:
i = position
else:
i+=3
elif code == 6: #jump if false
value = Intcode[i+1]
position = Intcode[i+2]
if modes[0] == 0:
value = Intcode[value]
if modes[1] == 0:
position = Intcode[position]
if value == 0:
i = position
else:
i+=3
elif code == 7: #less than
first, second, store = Intcode[i+1:i+4]
if modes[0] == 0:
first = Intcode[first]
if modes[1] == 0:
second = Intcode[second]
if first < second:
result = 1
else:
result = 0
Intcode[store] = result
i += 4
elif code == 8: #equal to
first, second, store = Intcode[i+1:i+4]
if modes[0] == 0:
first = Intcode[first]
if modes[1] == 0:
second = Intcode[second]
if first == second:
result = 1
else:
result = 0
Intcode[store] = result
i += 4
elif code == 99:
stillProcessing = False
break
else:
raise ValueError
if currentAmp == 4:
currentAmp = 0
else:
currentAmp += 1
maxAmp = max(maxAmp, ampInput)
counter +=1
print(maxAmp)
# print(Intcode)
csvFile.close()
|
f34fdda4bc7db8a73bf636beaf0bac696ca7ecdc | scabbycoral/tactile_object_recognition | /code/test_functions.py | 5,663 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import math
"""
This file contains functions to be used as part of the robotic classifier project.
"""
def get_maximum_consecutive_changes(array):
"""
A function which identifies the maximum number of consecutive changes between frames from the tactile data
"""
max_count=0
continuous_count = 0
for i in array:
if i == 1:
continuous_count +=1
else:
if continuous_count > max_count:
max_count = continuous_count
continuous_count = 0
return max_count
def get_maximum_consecutive_stability(array):
"""
A function which identifies the maximum number of consecutive stable frames from the tactile data
Additional consideration is made to ensure only frames between tactile changes are considered
"""
max_count=0
continuous_count = 0
changes = np.nonzero(array == 1)
if len(changes[0]) == 0:
return 0
# Identifies the first and last recorded tactile changes during the experimental procedure
start = changes[0][0]
end = changes[0][-1] + 1
# It only loops through the period of recorded tactile activity
for i in array[start:end]:
if i == 0:
continuous_count +=1
else:
if continuous_count > max_count:
max_count = continuous_count
continuous_count = 0
return max_count
def percentage_change_tolerance(v1,v2,t):
"""
A function which checks whether a change in recorded values is within a predetermined threshold value
Returns a flag as either True or False
"""
perc_change = np.abs((v1 - v2) / v1)
if perc_change <= t:
return True
else:
return False
def cart2pol(x,y):
""""
A function for converting cartesian values into polar co-ordinates.
Polar co-ordinates are returned as an angle/phi (in degrees) and a magnitude (rho)
"""
rho_tracker = []
phi_tracker = []
for i,j in zip(x,y):
rho = np.sqrt((i**2 + j**2))
phi = np.arctan2(j,i)
phi *= 180/math.pi
# print(f"phi: {phi}, rho: {rho}")
rho_tracker.append(rho)
phi_tracker.append(phi)
return (rho_tracker, phi_tracker)
def compare_vectors(phi, index1, index2):
"""
A function which compares the directions of two vectors given by polar co-ordinates.
The two vectors are identified as being in the same (or opposite) directions for x and y.
The returned array indicates which one of 4 possible alignments the two vectors are oriented in.
"""
results = np.zeros(4)
if phi[index2] ==0:
return results
if np.sign(phi[index1]) == np.sign(phi[index2]):
# print("Same direction re: x ")
x = True
else:
# print("Opposite x")
x = False
if (np.abs(phi[index1]) <= 90 and np.abs(phi[index2]) <=90) or (np.abs(phi[index1]) >= 90 and np.abs(phi[index2]) >=90):
# print("Same direction re: y ")
y = True
else:
# print("Opposite y")
y = False
# Check which conditions are satisfied to identify the relevant classification of the two vectors.
if x and y:
results[0]=1
elif x and not y:
results[1]=1
elif not x and y:
results[2] =1
else:
results[3]=1
# print(results)
return results
def compare_all_vectors(phi, mag):
"""
A function which looks at the direction of all shear forces and returns flags which indicate evidence of symmetry or parallel forces.
Information of the direction of shear forces at all taxels is used as input
"""
a = np.abs(phi) <= 90
b = np.sign(phi) == np.sign(1)
c1,c2,c3,c4 = 0,0,0,0
for i,j in zip(a,b):
if i == True and j == True:
c1+=1
elif i == False and j == True:
c2+=1
elif i == False and j == False:
c3+=1
else:
c4+=1
score_array = [c1,c2,c3,c4]
symmetry = False
# Checks for evidence of symmetry based on a roughly equal (and non-zero) number of shear forces pointing in opposite directions
if np.abs(c1-c3)<=3 and (c1 != 0 and c3 != 0):
symmetry = True
elif np.abs(c2-c4)<= 3 and (c2!=0 and c4!= 0):
symmetry = True
# Checks which 2 components are the most dominant across all taxels
principle_component = np.argmax(score_array)
score_array[principle_component]=0
secondary_component = np.argmax(score_array)
components = [principle_component, secondary_component]
components.sort()
parallel_directions = [[0,1],[1,2],[2,3],[0,3]]
# If the two predominant components of the shear forces are adjacent then a flag is raised to indicate evidence of forces working in parallel
if components in parallel_directions:
parallel = True
else:
parallel = False
return symmetry, parallel
def select_desired_features(full_features, desired_features, feature_dict):
"""
A function which reduces a feature set down to only the desired features specified in a list
Features must match with keys stored in the passed dictionary
"""
# print(f"{full_features.shape[1]} attributes available for selection")
feature_index_list = []
for i in desired_features:
feature_index_list.append(feature_dict[i])
new_features = full_features[:,feature_index_list]
# print(f"{new_features.shape[1]} attributes selected for classification")
return new_features |
98b39694fa9c92aaa50befbed18d8601e1dc86cf | codewithgauri/HacktoberFest | /python/plus.py | 138 | 3.875 | 4 | first = input("enter your first number :")
second = input("enter your second number :")
print("your answer is ", int(first) + int(second)) |
d30258e975f98b422c4afa9ad6aea0e6bbb461ba | monakhandat/Sentimental-Analysis-on-Presidential-Election-Twitter-Data | /src/Method3_SentimentAnalysis.py | 10,167 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Reading the json file
# In[1]:
import json
tweets = []
for line in open('tweets.json', 'r'):
tweets.append(json.loads(line))
# ### Checking the data
# In[13]:
tweets[0]
# ### Creating Dataframe by extracting the features that we need
# In[3]:
import pandas as pd
tweets_df = pd.DataFrame(columns=['id','tweet'],index=None)
for tweet in tweets[0:1000]:
data = pd.DataFrame({"id":[tweet['id_str']],"tweet":[tweet['text']]})
tweets_df = tweets_df.append(data, ignore_index = True)
# In[16]:
cnt = 0
for i in range (0,1000000):
if len(tweets[i]['entities']['user_mentions']) > 0:
# print(tweets[i]['text'])
# print(tweets[i]['entities']['user_mentions'])
cnt += 1
print(cnt)
# In[59]:
# obama_cnt = 0
# romney_cnt = 0
# obama_romney_cnt = 0
# for i in range(0,1000000):
# obama = False;
# romney = False;
# for word in tweets[i]['text'].split():
# # print(word)
# if word.lower() in ["obama","barack","barackobama","obamabarack"]:
# obama = True
# if word.lower() in["mitt","romney","mittromney","romneymitt"]:
# romney = True
# if obama == True and romney == False:
# obama_cnt += 1
# elif obama == False and romney == True:
# romney_cnt += 1
# elif obama == True and romney == True:
# obama_romney_cnt += 1
# print(obama_cnt)
# print(romney_cnt)
# print(obama_romney_cnt)
# In[19]:
tweets[0]['text']
# ### Analysing the data and finding the number of Obama and Romney tweets
# In[34]:
obama_cnt = 0
romney_cnt = 0
obama_romney_cnt = 0
import pandas as pd
tweets_df = pd.DataFrame(columns=['id','tweet'],index=None)
for i in range(0,len(tweets)):
if(i % 10000 == 0):
print("i:",i)
obama = False;
romney = False;
for word in tweets[i]['text'].split():
# print(word)
if word.lower() in ["obama","barack","barackobama","obamabarack"]:
obama = True
if word.lower() in["mitt","romney","mittromney","romneymitt"]:
romney = True
if obama == True and romney == False:
data = pd.DataFrame({"id":[tweets[i]['id_str']],"tweet":[tweets[i]['text']]})
tweets_df = tweets_df.append(data, ignore_index = True)
obama_cnt += 1
elif obama == False and romney == True:
data = pd.DataFrame({"id":[tweets[i]['id_str']],"tweet":[tweets[i]['text']]})
tweets_df = tweets_df.append(data, ignore_index = True)
romney_cnt += 1
# elif obama == True and romney == True:
# obama_romney_cnt += 1
print(obama_cnt)
print(romney_cnt)
print(obama_romney_cnt)
# In[35]:
print(len(tweets_df))
# ### Removing the unnecessary data from the tweet like RT symbols, hyperlinks usermention symbols, hashtag symbols, etc
# In[44]:
import re
processed_tweet = []
for i in range (0,len(tweets_df)):
if(i % 10000 == 0):
print("i:",i)
x = tweets_df.iloc[i]['tweet']
# tweets_df.iloc[i]['tweet'] = ' '.join(re.sub("(RT)|(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
temp = ' '.join(re.sub("(RT)|(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
processed_tweet.append(temp)
tweets_df['processed_tweet'] = processed_tweet
# In[45]:
tweets_df.head()
# ### Extract the Adjectives, verbs and adverbs from the tweet
# In[47]:
from nltk.tokenize import word_tokenize
import nltk
tweets_imp_words_df = pd.DataFrame(columns=['id','Adj_Adv_Verb','pos'],index=None)
for i in range (0,len(tweets_df)):
if(i % 10000 == 0):
print("i:",i)
text = word_tokenize(tweets_df.iloc[i]['processed_tweet'])
pos_tagged_words = nltk.pos_tag(text)
tempStr = ''
pos = []
for i in range(0,len(pos_tagged_words)):
if pos_tagged_words[i][1] in ['JJ','JJR','JJS','RB','RBR','RBS','VB','VBD','VBG','VBN','VBP','VBZ']:
tempStr += pos_tagged_words[i][0]+" "
pos.append(pos_tagged_words[i][1])
tempData = pd.DataFrame({"id":[tweets_df.iloc[i]['id']],"Adj_Adv_Verb":[tempStr],"pos":[pos]})
tweets_imp_words_df = tweets_imp_words_df.append(tempData, ignore_index = True)
# In[50]:
tweets_imp_words_df.head()
print(len(tweets_imp_words_df))
# ### Scoring the extracted adjectives, verbs and adverbs
# In[51]:
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import pandas as pd
sid = SentimentIntensityAnalyzer()
individual_score = []
for i in range (0,len(tweets_imp_words_df)):
if(i % 10000 == 0):
print("i:",i)
temp_individual_score = []
for word in tweets_imp_words_df.iloc[i]['Adj_Adv_Verb'].split():
temp_individual_score.append(sid.polarity_scores(word)['compound'])
individual_score.append(temp_individual_score)
tweets_imp_words_df['individual_scores'] = individual_score
# ### Rescoring the adjectives, verbs and adverbs based on the method
# In[52]:
for i in range (0,len(tweets_imp_words_df)):
if(i % 10000 == 0):
print("i:",i)
pos = tweets_imp_words_df.iloc[i]['pos']
for j in range (1,len(tweets_imp_words_df.iloc[i]['individual_scores'])):
if(pos[j] in ['JJ','JJR','JJS'] and pos[j-1] not in ['JJ','JJR','JJS']):
if(tweets_imp_words_df.iloc[i]['individual_scores'][j-1] > 0):
tweets_imp_words_df.iloc[i]['individual_scores'][j-1] *= tweets_imp_words_df.iloc[i]['individual_scores'][j]
elif(tweets_imp_words_df.iloc[i]['individual_scores'][j-1] < 0):
tweets_imp_words_df.iloc[i]['individual_scores'][j] = 5 - tweets_imp_words_df.iloc[i]['individual_scores'][j]
# ### Finding the final score of the tweet
# In[53]:
score = []
for i in range (0,len(tweets_imp_words_df)):
temp_score = 0;
no_of_adj = 0;
pos = tweets_imp_words_df.iloc[i]['pos']
for j in range (0,len(tweets_imp_words_df.iloc[i]['individual_scores'])):
temp_score += tweets_imp_words_df.iloc[i]['individual_scores'][j]
if(pos[j] in ['JJ','JJR','JJS']):
no_of_adj += 1;
if no_of_adj > 0:
temp_score = temp_score/no_of_adj;
score.append(temp_score)
tweets_imp_words_df['score'] = score
# In[60]:
# pos = 0;
# neg = 0;
# neu = 0;
# for i in range (0,len(tweets_imp_words_df)):
# if(i % 10000 == 0):
# print("i:",i)
# if tweets_imp_words_df.iloc[i]['score'] > 0:
# pos += 1
# elif tweets_imp_words_df.iloc[i]['score'] < 0:
# neg += 1
# else:
# neu += 1
# In[61]:
# print(pos)
# print(neg)
# print(neu)
# In[57]:
is_obama = []
is_romney = []
for i in range(0,len(tweets_imp_words_df)):
if(i % 20000 == 0):
print("i:",i)
obama = False;
romney = False;
for word in tweets_df.iloc[i]['tweet'].split():
# print(word)
if word.lower() in ["obama","barack","obamabarack","barackobama"]:
obama = True
if word.lower() in["mitt","romney","mittromney","romneymitt"]:
romney = True
is_obama.append(obama)
is_romney.append(romney)
tweets_imp_words_df['is_obama'] = is_obama
tweets_imp_words_df['is_romney'] = is_romney
# ### Finding the number of positive and negative tweets for Obama and Romney
# In[58]:
obama_pos = 0
obama_neg = 0
obama_neu = 0
romney_pos = 0
romney_neg = 0
romney_neu = 0
for i in range (0, len(tweets_imp_words_df)):
if(i % 20000 == 0):
print("i:",i)
if tweets_imp_words_df.iloc[i]['is_obama'] == True and tweets_imp_words_df.iloc[i]['score'] > 0:
obama_pos += 1
elif tweets_imp_words_df.iloc[i]['is_obama'] == True and tweets_imp_words_df.iloc[i]['score'] < 0:
obama_neg += 1
elif tweets_imp_words_df.iloc[i]['is_obama'] == True and tweets_imp_words_df.iloc[i]['score'] == 0:
obama_neu += 1
elif tweets_imp_words_df.iloc[i]['is_romney'] == True and tweets_imp_words_df.iloc[i]['score'] > 0:
romney_pos += 1
elif tweets_imp_words_df.iloc[i]['is_romney'] == True and tweets_imp_words_df.iloc[i]['score'] < 0:
romney_neg += 1
elif tweets_imp_words_df.iloc[i]['is_romney'] == True and tweets_imp_words_df.iloc[i]['score'] == 0:
romney_neu += 1
print("obama_pos",obama_pos)
print("obama_neg",obama_neg)
print("obama_neu",obama_neu)
print("romney_pos",romney_pos)
print("romney_neg",romney_neg)
print("romney_neu",romney_neu)
# ### Creating the results grapph for comparing all the methods that were executed
# In[55]:
import numpy as np
import matplotlib.pyplot as plt
N = 6
ObamaScore = (51.1, 46.8, 66, 53, 41.1, 57.1)
fig, ax = plt.subplots()
ind = np.arange(N)
width = 0.35
p1 = ax.bar(ind - width/2, ObamaScore, width, color='r', bottom=0)
RomneyScore = (47.2, 53.2, 34, 47, 58.8, 42.9)
p2 = ax.bar(ind + width/2, RomneyScore, width,color='y', bottom=0)
ax.set_title('Vote percentages for Obama and Romney')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('Actual', 'Method1', 'Method2', 'Method3', 'Method4', 'Method5'))
ax.legend((p1[0], p2[0]), ('Obama', 'Romney'))
ax.set_ylabel("Vote percentage")
def autolabel(rects, xpos='center'):
# for labelling the bar graph with its values
xpos = xpos.lower()
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0.5, 'right': 0.00, 'left': 0.95}
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
'{}'.format(height), ha=ha[xpos], va='bottom')
autolabel(p1, "left")
autolabel(p2, "right")
plt.show()
# ### Graph for the analysis of percentage of Obama and Romney tweets
# In[74]:
import matplotlib.pyplot as plt
324805
30092
51443
labels = ['Only Obama Tweets', 'Only Romney Tweets', 'Obama and Romney Tweets', 'Neither Obama nor Romney Tweets']
sizes = [224805/1000000, 130092/1000000, 51443/1000000, (1000000-324805+30092+51443)/1000000]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)
plt.legend(patches, labels, loc="best")
plt.axis('equal')
plt.tight_layout()
plt.show()
# In[ ]:
|
b9767690d8dd129318dc37507a98261a3840ce74 | Naster20/t05_Ruiz.Sanchez | /Verificadores.Ruiz.Sanchez.py | 16,244 | 3.578125 | 4 | #EJERCICIO 1
producto="Leche"
type_producto=type(producto)
producto_es_str=isinstance(producto,str)
producto_es_int=isinstance(producto,int)
print("Variable Producto es :",type_producto)
print("Variable es str :",producto_es_str)
print("Variable es int :",producto_es_int)
#Fin if
#EJERCICIO 2
cliente="Naster"
type_cliente=type(cliente)
cliente_es_int=isinstance(cliente,int)
cliente_es_str=isinstance(cliente,str)
print("Variable Cliente es :",type_producto)
print("Variable es int :",cliente_es_int)
print("Variable es str :",cliente_es_str)
#Fin if
#EJERCICIO 3
precio=85.3
type_precio=type(precio)
precio_es_str=isinstance(precio,str)
precio_es_float=isinstance(precio,float)
print("Variable Precio es :",type_precio)
print("Variable es str :",precio_es_str)
print("Variable es float :",precio_es_float)
#Fin if
#EJERCICIO 4
cant_prod_1=15
type_cant_prod_1=type(cant_prod_1)
cant_prod_1_es_bool=isinstance(cant_prod_1,bool)
cant_prod_1_es_int=isinstance(cant_prod_1,int)
print("Variable Cantidad de Producto 1 es :",type_cant_prod_1)
print("Variable es Bool :",cant_prod_1_es_bool)
print("Variable es Int :",cant_prod_1_es_int)
#Fin if
#EJERCICIO 5
costo_uni_prod1=0.0
type_costo_uni_prod1=type(costo_uni_prod1)
costo_uni_prod1_es_str=isinstance(costo_uni_prod1,str)
costo_uni_prod1_es_float=isinstance(costo_uni_prod1,float)
print("Variable Costo Unitario de Producto 1 es :",type_costo_uni_prod1)
print("Variable es Str :",costo_uni_prod1_es_str)
print("Variable es Float :",costo_uni_prod1_es_float)
#Fin if
#EJERCICIO 6
alumno="Ruiz Sánchez"
type_alumno=type(alumno)
alumno_es_str=isinstance(alumno,str)
alumno_es_float=isinstance(alumno,float)
print("Variable Alumno es :",type_alumno)
print("Variable es Str :",alumno_es_str)
print("Variable es Float :",alumno_es_float)
#Fin if
#EJERCICIO 7
nota1=0.0
type_nota1=type(nota1)
nota1_es_str=isinstance(nota1,str)
nota1_es_float=isinstance(nota1,float)
print("Variable Nota 1 es :",type_nota1)
print("Variable es Str :",nota1_es_str)
print("Variable es Float :",nota1_es_float)
#Fin if
#EJERCICIO 8
prom=14.5
type_prom=type(prom)
prom_es_float=isinstance(prom,float)
prom_es_int=isinstance(prom,int)
print("Variable Promedio es :",type_prom)
print("Variable es Float :",prom_es_float)
print("Variable es Int :",prom_es_int)
#Fin if
#EJERCICIO 9
persona="Claudio Cordova"
type_persona=type(persona)
persona_es_float=isinstance(persona,float)
persona_es_str=isinstance(persona,str)
print("Variable Persona es :",type_persona)
print("Variable es Float :",persona_es_float)
print("Variable es Str :",persona_es_str)
#Fin if
#EJERCICIO 10
otros_gastos_2005=316
type_otros_gastos_2005=type(otros_gastos_2005)
otros_gastos_2005_es_float=isinstance(otros_gastos_2005,float)
otros_gastos_2005_es_int=isinstance(otros_gastos_2005,int)
print("Variable Otros gastos del 2005 es :",type_otros_gastos_2005)
print("Variable es Float :",otros_gastos_2005_es_float)
print("Variable es Int :",otros_gastos_2005_es_int)
#Fin if
#EJERCICIO 11
total_de_otros_gastos=26528
type_total_de_otros_gastos=type(total_de_otros_gastos)
total_de_otros_gastos_es_int=isinstance(total_de_otros_gastos,int)
total_de_otros_gastos_es_bool=isinstance(total_de_otros_gastos,bool)
print("Variable Total de otros gastos es :",type_total_de_otros_gastos)
print("Variable es Int :",total_de_otros_gastos_es_int)
print("Variable es Bool :",total_de_otros_gastos_es_bool)
#Fin if
#EJERCICIO 12
utilidad_bruta_2005=6050
type_utilidad_bruta_2005=type(utilidad_bruta_2005)
utilidad_bruta_2005_es_int=isinstance(utilidad_bruta_2005,int)
utilidad_bruta_2005_es_float=isinstance(utilidad_bruta_2005,float)
print("Variable Utilidad bruta del 2005 es :",type_total_de_otros_gastos)
print("Variable es Int :",utilidad_bruta_2005_es_int)
print("Variable es Float :",utilidad_bruta_2005_es_float)
#Fin if
#EJERCICIO 13
total_de_utilidad_bruta=87543
type_total_de_utilidad_bruta=type(total_de_utilidad_bruta)
total_de_utilidad_bruta_es_float=isinstance(total_de_utilidad_bruta,float)
total_de_utilidad_bruta_es_int=isinstance(total_de_utilidad_bruta,int)
print("Variable Total de utilidad bruta es :",type_total_de_utilidad_bruta)
print("Variable es Float :",total_de_utilidad_bruta_es_float)
print("Variable es Int :",total_de_utilidad_bruta_es_int)
#Fin if
#EJERCICIO 14
flujo_de_operacion_2005=3557
type_flujo_de_operacion_2005=type(flujo_de_operacion_2005)
flujo_de_operacion_2005_es_float=isinstance(flujo_de_operacion_2005,float)
flujo_de_operacion_2005_es_int=isinstance(flujo_de_operacion_2005,int)
print("Variable Flujo de operacion 2005 es :",type_flujo_de_operacion_2005)
print("Variable es Float :",flujo_de_operacion_2005_es_float)
print("Variable es Int :",flujo_de_operacion_2005_es_int)
#Fin if
#EJERCICIO 15
total_flujo_de_operacion=29504
type_total_flujo_de_operacion=type(total_flujo_de_operacion)
total_flujo_de_operacion_es_int=isinstance(total_flujo_de_operacion,int)
total_flujo_de_operacion_es_str=isinstance(total_flujo_de_operacion,str)
print("Variable Total de flujo de operacion es :",type_total_flujo_de_operacion)
print("Variable es Int :",total_flujo_de_operacion_es_int)
print("Variable es Str :",total_flujo_de_operacion_es_str)
#Fin if
#EJERCICIO 16
capital_contable_2005=10357
type_capital_contable_2005=type(capital_contable_2005)
capital_contable_2005_es_int=isinstance(capital_contable_2005,int)
capital_contable_2005_es_str=isinstance(capital_contable_2005,str)
print("Variable Capital contables del 2005 es :",type_capital_contable_2005)
print("Variable es Int :",capital_contable_2005_es_int)
print("Variable es Str :",capital_contable_2005_es_str)
#Fin if
#EJERCICIO 17
total_capital_contable="15089343"
type_total_capital_contable=type(total_capital_contable)
total_capital_contable_es_int=isinstance(total_capital_contable,int)
total_capital_contable_es_str=isinstance(total_capital_contable,str)
print("Variable Total de capital contable es :",type_total_capital_contable)
print("Variable es Int :",total_capital_contable_es_int)
print("Variable es Str :",total_capital_contable_es_str)
#Fin if
#EJERCICIO 18
participacion_controladora_2005=9825
type_participacion_controladora_2005=type(participacion_controladora_2005)
participacion_controladora_2005_es_int=isinstance(participacion_controladora_2005,int)
participacion_controladora_2005_es_str=isinstance(participacion_controladora_2005,str)
print("Variable Participacion controladora es :",type_participacion_controladora_2005)
print("Variable es Int :",participacion_controladora_2005_es_int)
print("Variable es Str :",participacion_controladora_2005_es_str)
#Fin if
#EJERCICIO 19
total_participacion_controladora=35829
type_total_participacion_controladora=type(total_participacion_controladora)
total_participacion_controladora_es_int=isinstance(total_participacion_controladora,int)
total_participacion_controladora_es_str=isinstance(total_participacion_controladora,str)
print("Variable Total de participacion controladora es :",type_total_participacion_controladora)
print("Variable es Int :",total_participacion_controladora_es_int)
print("Variable es Str :",total_participacion_controladora_es_str)
#Fin if
#EJERCICIO 20
hipotenusa=14.7
type_hipotenusa=type(hipotenusa)
hipotenusa_es_float=isinstance(hipotenusa,float)
hipotenusa_es_int=isinstance(hipotenusa,int)
print("Variable Hipotenusa es :",type_hipotenusa)
print("Variable es Float :",hipotenusa_es_float)
print("Variable es Int :",hipotenusa_es_int)
#Fin if
#EJERCICIO 21
pi=3.14159
type_pi=type(pi)
pi_es_float=isinstance(pi,float)
pi_es_int=isinstance(pi,int)
print("Variable PI es :",type_pi)
print("Variable es Float :",pi_es_float)
print("Variable es Int :",pi_es_int)
#Fin if
#EJERCICIO 22
radio=4
type_radio=type(radio)
radio_es_float=isinstance(radio,float)
radio_es_int=isinstance(radio,int)
print("Variable PI es :",type_radio)
print("Variable es Float :",radio_es_float)
print("Variable es Int :",radio_es_int)
#Fin if
#EJERCICIO 23
clave="Find20ruiZ"
type_clave=type(clave)
clave_es_float=isinstance(clave,float)
clave_es_str=isinstance(clave,str)
print("Variable Clave es :",type_clave)
print("Variable es Float :",clave_es_float)
print("Variable es Str :",clave_es_str)
#Fin if
#EJERCICIO 24
apellido="Ruiz Sánchez"
type_apellido=type(apellido)
apellido_es_float=isinstance(apellido,float)
apellido_es_str=isinstance(apellido,str)
print("Variable Apellido es :",type_apellido)
print("Variable es Float :",apellido_es_float)
print("Variable es Str :",apellido_es_str)
#Fin if
#EJERCICIO 25
pago_total=930
type_pago_total=type(pago_total)
pago_total_es_int=isinstance(pago_total,int)
pago_total_es_str=isinstance(pago_total,str)
print("Variable Pago total es :",type_pago_total)
print("Variable es Int :",pago_total_es_int)
print("Variable es Str :",pago_total_es_str)
#Fin if
#EJERCICIO 26
horas_extras=6
type_horas_extras=type(horas_extras)
horas_extras_es_int=isinstance(horas_extras,int)
horas_extras_es_str=isinstance(horas_extras,str)
print("Variable Horas extra es :",type_horas_extras)
print("Variable es Int :",horas_extras_es_int)
print("Variable es Str :",horas_extras_es_str)
#Fin if
#EJERCICIO 27
facultad="FACFyM"
type_facultad=type(facultad)
facultad_es_int=isinstance(facultad,int)
facultad_es_str=isinstance(facultad,str)
print("Variable Facultad es :",type_facultad)
print("Variable es Int :",facultad_es_int)
print("Variable es Str :",facultad_es_str)
#Fin if
#EJERCICIO 28
lugar_nacimiento="Cajamarca-Chota"
type_lugar_nacimiento=type(lugar_nacimiento)
lugar_nacimiento_es_bool=isinstance(lugar_nacimiento,bool)
lugar_nacimiento_es_str=isinstance(lugar_nacimiento,str)
print("Variable Facultad es :",type_lugar_nacimiento)
print("Variable es Bool :",lugar_nacimiento_es_bool)
print("Variable es Str :",lugar_nacimiento_es_str)
#Fin if
#EJERCICIO 29
sexo=True
type_sexo=type(sexo)
sexo_es_bool=isinstance(sexo,bool)
sexo_es_str=isinstance(sexo,str)
print("Variable Sexo es :",type_sexo)
print("Variable es Bool :",sexo_es_bool)
print("Variable es Str :",sexo_es_str)
#Fin if
#EJERCICIO 30
fecha= "30/11/2019"
type_fecha=type(fecha)
fecha_es_bool=isinstance(fecha,bool)
fecha_es_str=isinstance(fecha,str)
print("Variable Fecha es :",type_fecha)
print("Variable es Bool :",fecha_es_bool)
print("Variable es Str :",fecha_es_str)
#Fin if
#EJERCICIO 31
ruc="10701919314"
type_ruc=type(ruc)
ruc_es_str=isinstance(ruc,str)
ruc_es_float=isinstance(ruc,float)
print("Variable RUC es :",type_ruc)
print("Variable es Str :",ruc_es_str)
print("Variable es Float :",ruc_es_float)
#Fin if
#EJERCICIO 32
boleta_de_venta="000139"
type_boleta_de_venta=type(boleta_de_venta)
boleta_de_venta_es_str=isinstance(boleta_de_venta,str)
boleta_de_venta_es_float=isinstance(boleta_de_venta,float)
print("Variable N° de boleta de venta es :",type_boleta_de_venta)
print("Variable es Str :",boleta_de_venta_es_str)
print("Variable es Float :",boleta_de_venta_es_float)
#Fin if
#EJERCICIO 33
declarante="Miguel Angel Gonzalez Yupanqui"
type_declarante=type(declarante)
declarante_es_int=isinstance(declarante,int)
declarante_es_str=isinstance(declarante,str)
print("Variable Declarante es :",type_declarante)
print("Variable es Int :",declarante_es_int)
print("Variable es Str :",declarante_es_str)
#Fin if
#EJERCICIO 34
talla=1.65
type_talla=type(talla)
talla_es_float=isinstance(talla,float)
talla_es_str=isinstance(talla,str)
print("Variable Talla es :",type_talla)
print("Variable es Float :",talla_es_float)
print("Variable es Str :",talla_es_str)
#Fin if
#EJERCICIO 35
peso=83.5
type_peso=type(peso)
peso_es_float=isinstance(peso,float)
peso_es_str=isinstance(peso,str)
print("Variable Peso es :",type_peso)
print("Variable es Float :",peso_es_float)
print("Variable es Str :",peso_es_str)
#Fin if
#EJERCICIO 36
descuento=30
type_descuento=type(descuento)
descuento_es_float=isinstance(descuento,float)
descuento_es_int=isinstance(descuento,int)
print("Variable Descuento es :",type_descuento)
print("Variable es Float :",descuento_es_float)
print("Variable es Int :",descuento_es_int)
#Fin if
#EJERCICIO 37
edad=23
type_edad=type(edad)
edad_es_int=isinstance(edad,int)
edad_es_bool=isinstance(edad,bool)
print("Variable Edad es :",type_edad)
print("Variable es Int :",edad_es_int)
print("Variable es Bool :",edad_es_bool)
#Fin if
#EJERCICIO 38
tercio_superior=True
type_tercio_superior=type(tercio_superior)
tercio_superior_es_float=isinstance(tercio_superior,float)
tercio_superior_es_bool=isinstance(tercio_superior,bool)
print("Variable Tercio superior es :",type_tercio_superior)
print("Variable es Float :",tercio_superior_es_float)
print("Variable es Bool :",tercio_superior_es_bool)
#Fin if
#EJERCICIO 39
bonificacion=320.40
type_bonificacion=type(bonificacion)
bonificacion_es_float=isinstance(bonificacion,float)
bonificacion_es_bool=isinstance(bonificacion,bool)
print("Variable Bonificacion es :",type_bonificacion)
print("Variable es Float :",bonificacion_es_float)
print("Variable es Bool :",bonificacion_es_bool)
#Fin if
#EJERCICIO 40
mes="Noviembre"
type_mes=type(mes)
mes_es_float=isinstance(mes,float)
mes_es_str=isinstance(mes,str)
print("Variable Mes es :",type_mes)
print("Variable es Float :",mes_es_float)
print("Variable es str :",mes_es_str)
#Fin if
#EJERCICIO 41
codigo="020120275-H"
type_codigo=type(codigo)
codigo_es_float=isinstance(codigo,float)
codigo_es_str=isinstance(codigo,str)
print("Variable Codigo es :",type_codigo)
print("Variable es Float :",codigo_es_float)
print("Variable es str :",codigo_es_str)
#Fin if
#EJERCICIO 42
cateto1=3.5
type_cateto1=type(cateto1)
cateto1_es_float=isinstance(cateto1,float)
cateto1_es_str=isinstance(cateto1,str)
print("Variable Cateto 1 es :",type_cateto1)
print("Variable es Float :",cateto1_es_float)
print("Variable es str :",cateto1_es_str)
#Fin if
#EJERCICIO 43
cateto2=2.5
type_cateto2=type(cateto2)
cateto2_es_float=isinstance(cateto2,float)
cateto2_es_str=isinstance(cateto2,str)
print("Variable Cateto 2 es :",type_cateto1)
print("Variable es Float :",cateto2_es_float)
print("Variable es str :",cateto2_es_str)
#Fin if
#EJERCICIO 44
area_circulo="25.2"
type_area_circulo=type(area_circulo)
area_circulo_es_float=isinstance(area_circulo,float)
area_circulo_es_str=isinstance(area_circulo,str)
print("Variable Area circulo es :",type_area_circulo)
print("Variable es Float :",area_circulo_es_float)
print("Variable es str :",area_circulo_es_str)
#Fin if
#EJERCICIO 45
ano=2019
type_ano=type(ano)
ano_es_int=isinstance(ano,int)
ano_es_str=isinstance(ano,str)
print("Variable Año es :",type_ano)
print("Variable es Int :",ano_es_int)
print("Variable es Str :",ano_es_str)
#Fin if
#EJERCICIO 46
precio_horas_extras=5.80
type_precio_horas_extras=type(precio_horas_extras)
precio_horas_extras_es_int=isinstance(precio_horas_extras,int)
precio_horas_extras_es_float=isinstance(precio_horas_extras,float)
print("Variable Precio de horas extra es :",type_precio_horas_extras)
print("Variable es Int :",precio_horas_extras_es_int)
print("Variable es Float :",precio_horas_extras_es_float)
#Fin if
#EJERCICIO 47
indice_de_masa_corporal=30.023
type_indice_de_masa_corporal=type(indice_de_masa_corporal)
indice_de_masa_corporal_es_int=isinstance(indice_de_masa_corporal,int)
indice_de_masa_corporal_es_float=isinstance(indice_de_masa_corporal,float)
print("Variable Indice de masa corporal :",type_indice_de_masa_corporal)
print("Variable es Int :",indice_de_masa_corporal_es_int)
print("Variable es Float :",indice_de_masa_corporal_es_float)
#Fin if
#EJERCICIO 48
dni="48427829"
type_dni=type(dni)
dni_es_int=isinstance(dni,int)
dni_es_str=isinstance(dni,str)
print("Variable DNI es :",type_dni)
print("Variable es Int :",dni_es_int)
print("Variable es Str :",dni_es_str)
#Fin if
#EJERCICIO 49
departamento="Lambayeque"
type_departamento=type(departamento)
departamento_es_int=isinstance(departamento,int)
departamento_es_str=isinstance(departamento,str)
print("Variable Departamento es :",type_departamento)
print("Variable es Int :",departamento_es_int)
print("Variable es Str :",departamento_es_str)
#Fin if
#EJERCICIO 50
imprenta="KARIBET"
type_imprenta=type(imprenta)
imprenta_es_int=isinstance(imprenta,int)
imprenta_es_str=isinstance(imprenta,str)
print("Variable Imprenta es :",type_imprenta)
print("Variable es Int :",imprenta_es_int)
print("Variable es Str :",imprenta_es_str)
#Fin if
|
735b2f4409de2b85052d4d11846e22be0b2009d3 | hectorlopezmonroy/HackerRank | /Programming Languages/Python/Strings/Capitalize!/Solution.py | 956 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# You are asked to ensure that the first and last names of people begin with a
# capital letter in their passports. For example, 'alison heck' should be
# capitalized correctly as 'Alison Heck'.
#
# alison heck -> Alison Heck
#
# Given a full name, your task is to capitalize the name appropriately.
#
# Input Format
#
# A single line of input containing the full name, 'S'.
#
# Constraints
#
# 0 < len(S) < 1000
#
# The string consists of alphanumeric characters and spaces.
#
# Note: In a word only the first character is capitalized. Example: '12abc' when
# capitalized remains '12abc'.
#
# Output Format
#
# Print the capitalized string, 'S'.
#
# Sample Input
#
# chris alan
#
# Sample Output
#
# Chris Alan
#!/bin/python3
import math
import os
import random
import re
import sys
import string
def solve(s):
res = string.capwords(s, ' ')
return res
if __name__ == '__main__':
s = input()
result = solve(s)
print(result)
|
9cb0ba028e64cbe14a213c4481cb6a09be2a9bef | AniruddhaSadhukhan/Dynamic-Programming | /C_Longest Common Subsequence/11_Min number of insertion to make the string palindrome.py | 1,216 | 3.6875 | 4 | # Given a string str, the task is to find the minimum number of characters
# to be inserted to convert it to palindrome.
# ab: Number of insertions required is 1 i.e. bab
# aa: Number of insertions required is 0 i.e. aa
# abcd: Number of insertions required is 3 i.e. dcbabcd
# abcda: Number of insertions required is 2 i.e. adcbcda
# abcde: Number of insertions required is 4 i.e. edcbabcde
# Logic:
# Min # of insertion = Min # of deletion
# = String Length - Length of Longest Palindromic Subsequence
def LCS(X, Y, n, m):
if M[n][m] != None:
return M[n][m]
elif n == 0 or m == 0:
M[n][m] = 0
elif X[n-1] == Y[m-1]:
M[n][m] = LCS(X, Y, n-1, m-1) + 1
else:
M[n][m] = max(
LCS(X, Y, n-1, m),
LCS(X, Y, n, m-1)
)
return M[n][m]
def make2DMemory(n, W):
global M
M = [[None for i in range(W+1)] for j in range(n+1)]
def LPS(X):
Y = X[::-1]
n = len(X)
make2DMemory(n, n)
return(LCS(X, Y, n, n))
T = int(input())
for _ in range(T):
X = input().strip()
Y = X[::-1]
n = len(X)
make2DMemory(n, n)
print(n - LPS(X))
# 6
# ab
# aa
# abcd
# abcda
# abcde
# aebcbda
|
c408e0d09d777fe723d4c9c547c4db56022ac4a3 | SidPatra/ProgrammingPractice | /ttt_n_dimension_starter.py | 2,147 | 4.03125 | 4 | # YOUR NAME:
# YOUR PSU EMAIL ADDRESS:
# END OF HEADER INFORMATION
# -----------------------------------------------
# PLACE ANY NEEDED IMPORT STATEMENTS HERE:
# END OF IMPORT STATEMENTS
# -----------------------------------------------
# DEFINE YOUR FUNCTIONS (NOT INCLUDING MAIN) IN THIS SECTION
# YOU WILL NEED MOST OR ALL OF THE FUNCTIONS PREVIOUSLY WRITTEN
#------------------------------------------------
# NEW FUNCTION NAME: winner
# INPUT: the board, the token, the dimension
# PROCESS: Determine if the passed-in token wins the game
# OUTPUT: True if the passed-in-token wins the game, False otherwise
# NEW FUNCTION NAME: move
# INPUT: the board, the token, the dimension
# PROCESS: Make and process the next move
# OUTPUT: The next token (taking turns) AND whether or not the game is ove
def move(board, dimension, token):
gameOver = False
displayBoard(board, dimension)
move = int(input("Enter a move for " + token + " (1-" + str(dimension*dimension) +"): "))
print(move)
if (move < 1) or (move > (dimension*dimension)):
print("Move is out of range; try again.")
else:
if makeMove(board, move, token, dimension):
if winner(board, token, dimension):
# ADD LOGIC HERE!
else:
if filled(board, dimension):
# ADD LOGIC HERE
else:
# ADD LOGIC HERE
return token, gameOver
# END OF FUNCTION DEFINITIONS
#------------------------------------------------
# MAIN PART OF THE PROGRAM -- DON'T CHANGE ANYTHING BELOW HERE!
#------------------------------------------------
def main():
print("Play Tic-Tac-Toe!")
dimension = int(input("What is the dimension of the board (3-12)? "))
print(dimension)
if (dimension < 3) or (dimension > 12):
print("The dimension is out of range")
else:
board = fillBoard(dimension)
token = 'X'
gameOver = False
while not gameOver:
token, gameOver = move(board, dimension, token)
displayBoard(board, dimension)
# INCLUDE THE FOLLOWING 2 LINES, BUT NOTHING ELSE BETWEEN HERE
if __name__ == "__main__":
main()
# AND HERE
|
3c455c61a1f25cf7238ca6346b7be1197014f68b | Harshupatil/PythonPrograms- | /CommonFactors.py | 439 | 3.71875 | 4 | #******************************************************************************
#Common factors of two numbers, this are the numbers which divide both input
#numbers.
#*******************************************************************************/
count=0
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a<b:
n=a
else:
n=b;
for i in range(1,n+1):
if a%i==0 and b%i==0:
count=count+1;
print(count) |
708147aba27d5e8e12d15384d291c60fd5ea33fe | retropleinad/TurfCutter | /map.py | 333 | 3.5625 | 4 | import numpy as np
"""
Adjacency matrix:
1.) VxV dimensions, where V is the number of vertices in a graph
2.) A 1 indicates that there is an edge between the indices represented by the dimensions
"""
adj_matrix = np.array([
[0, 1, 1, 0],
[1, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 0]
])
print(adj_matrix) |
6e97734bac2816bed719f2be857d4fe9b8efcbb3 | yongxuUSTC/challenges | /heapq-library.py | 303 | 3.828125 | 4 | #Introduction to heapq library
import heapq
input = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print ("input >>>", input)
#Min Heap (DEFAULT)
heapq.heapify(input)
print ("input after min heap >>>", input)
#Max Heap
heapq._heapify_max(input)
print ("input after max heap >>>", input)
|
5fa5c9fdb51ce0b2933af50289b884c0e570f124 | pitzcritter/CodingDojo--Python | /6 Find Characters.py | 219 | 3.796875 | 4 | # input
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
# output
# new_list = ['hello','world']
newArr = []
for item in word_list:
if item.find(char) != -1:
newArr.append(item)
print newArr |
0e8c10cccc7ada5c337db5155b2223e443604316 | abdullahalmamun0/Python_Full_Course | /09_list.py | 1,301 | 3.796875 | 4 | # =============================================================================
# List
# =============================================================================
a = ["Doreamon",'Shinchan',"Tom and Jerry",
1,3,4,'Shinchan',1.4]
b,c = ["Doreamon","dorejsdhfamon","Shinchan",
'shhdsvssinchan'],[1,6,3,8,2,4]
print(sum(c))
print(min(b))
# def length(i):
# return len(i)
# c.sort(reverse=True)
print(sorted(c,reverse=True))
# a.reverse()
print(a)
# print(a.count(1.4))
print(a.index("Doreamon"))
b = ["jdhbf",2,3,4,"jdshbf"]
print(b+a)
b = a.copy()
print(b)
if "Shinsjdbhfchan" in a:
print("paichi")
else:
print("Pai nai")
print(len(a))
for i in a:
print(i)
#del a[1:4]
a.remove('Shinchan')
a.pop(2)
a.clear()
print(a)
# a[2] = "Meena"
# a[2:5] = ["Meena",2,"Hello"]
print(a)
a.append("Hey")
a.extend(["Hello","I","Am"])
a.insert(1,4)
print(a)
b = ["Doreamon",'Shinchan',["codinglaugh","marjuk",1,4],
"Tom and Jerry",3,1,4,1.4]
# c = b[2].copy()
# print(c)
# print(["hey"]*2)
# print(len(b[1]))
c = []
for i in b:
if type(i) is list:
c = i.copy()
# for j in i:
# print(j)
else:
print(i)
print(c)
# del b[2][0]
# b.append("hey")
# b[2][1] = 3
# b.insert(2,"hey")
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.