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 |
|---|---|---|---|---|---|---|
c8b57f42b4db063ca7c79841fcc6172c99d824ba | rchronic/hackerrank | /Belajar_1/Repeated String | 1,059 | 3.65625 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
sums = 0
if len(s) == n:
x = sorted(s)
for i in x:
if i == 'a':
sums += 1
else:
break
elif len(s) > n:
for i in range(n):
if s[i] == 'a':
sums += 1
else:
flags = True
for i in s:
if i != 'a':
flags = False
else:
sums += 1
if flags:
sums = sums - sums + n
else:
sums = ((n/len(s))*sums) # dividen menentukan banyaknya perulangan s di dalam range n
for i in range(n%len(s)):
if s[i] == 'a':
sums += 1
return sums
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = raw_input()
n = int(raw_input())
result = repeatedString(s, n)
fptr.write(str(result) + '\n')
fptr.close()
|
953693222f0d0cd396538813f42c86476879af24 | KKisly/PrismAssignments | /SalesMan/SalesMan.py | 2,255 | 4.125 | 4 | # This script is to find distance between cities
import csv
import math
from math import pi, log, tan
#loop through csv list
def find (city):
csv_file = csv.reader(open('cc.csv', "rt"), delimiter=",")
for row in csv_file:
if city == row[1]:
finding = row
#print(finding)
return finding
def distance (list1, list2):
x1 = list1[0]
x2 = list2[0]
#sq = ((x1 - x2)**2)
sq = ((list1[0] - list2[0])**2 + (list1[1] - list2[1])**2)
#print(sq)
range = math.sqrt(sq)
return range
def conversion (cityrow):
mapWidth = 30030.000000
mapHeight = 30015.000000
latitude = float(cityrow[2])
longitude = float(cityrow[3])
x = (longitude + 180) * (mapWidth / 360)
#print("x", x)
latRad = latitude * pi / 180
mercN = log(tan((pi / 4) + (latRad / 2)))
y = (mapHeight / 2) - (mapWidth * mercN / (2 * pi))
#print ("y", y)
list = [x, y]
return list
def main():
city = input('Enter first city\n')
city2 = input('Enter second city\n')
city3 = input('Enter third city\n')
Imp_SI = int(input("Would you like output in miles Input (1) or kilometers Input (2)"))
while Imp_SI != 1 and Imp_SI != 2:
Imp_SI = int(input("Please enter correct choice in miles Input (1) or kilometers Input (2)"))
cityrow = find(city)
cityrow2 = find(city2)
cityrow3 = find(city3)
#print(cityrow3)
listcity1 = conversion(cityrow)
# print(listcity1)
listcity2 = conversion(cityrow2)
# print(listcity2)
listcity3 = conversion(cityrow3)
#print(listcity3)
range = distance(listcity1, listcity2)
if Imp_SI == 2:
print("This is distance between", city, "and", city2, "in kilometers:", ("%.2f" % range))
else:
print("This is distance between", city, "and", city2, "in miles:", ("%.2f" % (range/1.609)))
range = distance(listcity2, listcity3)
if Imp_SI == 2:
print("This is distance between", city2, "and", city3, "in kilometers:", ("%.2f" % range))
elif Imp_SI == 1:
print("This is distance between cities", "in miles:", ("%.2f" % (range/1.609)))
if __name__ == "__main__":
main() |
09ee263336d9d5a5be3c23f0d505a177702d2f83 | OwenAspen/Python-Practice | /CowsAndBulls.py | 1,445 | 3.5625 | 4 | import random
#Cows and bulls: Generates a 4 digit string, asks user for a 4 digit string,
#if the strings match, you win. Otherwise, for every matching digit
#in the same position of the string, you will get a cow. for every digit in both
#strings, but not in the same position, you get a bull.
guesses = 0
#Counts the number of guesses taken.
numToGuess = str(random.randint(1000,9999))
#Generates a random 4 digit number.
checkAgainst = []
for i in range(4):
checkAgainst.append(int(numToGuess[i]))
#Converting the number to a list for checking the user input against
while True:
#print(checkAgainst) #Print statement for testing, comment out to actually play
cows = 0
bulls = 0
#Counters
userIn = input('Enter a 4 digit number: ')
userNumList = []
for j in range(4):
userNumList.append(int(userIn[j]))
#User input converted to a list
print(userNumList)
if int(numToGuess) == int(userIn):
guesses += 1
print('Correct! You got the right answer in ' + str(guesses) + ' tries.')
#Check for correct input(win)
break
for k in range(4):
if checkAgainst[k] == userNumList[k]:
cows += 1
#Check for cows
if checkAgainst[k] in userNumList:
if checkAgainst[k] != userNumList[k]:
bulls += 1
#Check for bulls
guesses += 1
print('Cows: ' + str(cows))
print('Bulls: ' + str(bulls))
|
c7850878a9b2db7f0cbdfe2e6b3e5c5468c2f5f5 | mvinovivek/BA_Python | /Class_5/adfd.py | 83 | 3.828125 | 4 | X=[1,2,3,4]
Y=["One","Two","Four","Three"]
for x,y in (zip(X,Y)):
print(x,y)
|
516d924a5a23e85e13e07206430f3178e6f83135 | fazriegi/Python | /Algoritma Pengurutan/Selection Sort/selectionSort.py | 336 | 3.71875 | 4 | # Algoritma Sorting
# Kompleksitas 0(N**2)
def selectionSort(arr):
for i in range(len(arr)-1):
minIndex = i
for j in range(i+1, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
arr[i], arr[minIndex] = arr[minIndex], arr[i]
a = [1, 5, 2, 7, 4, 9, 8]
selectionSort(a)
print(a)
|
d337523cd9af9acdcb78db9d17f73c5017b1c98e | kn33hit/Coursework | /GL_backup/201/LABS/LAB5/lab5.py | 1,018 | 3.765625 | 4 | # file: lab5.py
# author: Neh Patel
# date: 10/3/2013
# section : 17
# email : npatel10@umbc.edu
# description : this program determines whether a number is perfect or not
def main():
# declaring variables
total = 0
divisor = 0
flag = True
num = 0
# input
while (flag):
try:
num = int(input("Enter a number that is not a decimal, and greater than 0:"))
if num > 1:
flag = False
else:
print("input was invalid. Please try again")
except ValueError:
print("numbers only please")
except NameError:
print("numbers only please")
# process
for i in range(1,num):
divisor = num % i
if divisor == 0:
total = i + total
# output
if total == num:
print("The number you entered is a perfect number")
else:
print("The number is not a perfect number")
main()
|
36552fc1aa7896a3b71a13ed5db1c1a4d1bc825e | ray60110/HeadFirst_Python | /Chapter6/dataobject.py | 906 | 3.625 | 4 | def sanitize(time_string):
# create a function to produce standardized time format. xx.xx
# erase anyother marks wihin each value.
if '-' in time_string:
splitter= '-'
elif ':' in time_string:
splitter= ':'
else:
return(time_string)
(mins, secs)= time_string.split(splitter)
return(mins+'.'+secs)
def create_dict(source):
try:
with open(source, 'r') as file:
data= file.readline()
temp= data.strip().split(',')
return({'name':temp[0],
'dob':temp[1],
'time':sorted(set([sanitize(x) for x in temp[2:]]))[0:3]})
except IOError as ioerr:
print('file error'+ str(ioerr))
return None
print(create_dict('sarah2.txt'))
print(create_dict('julie2.txt'))
print(create_dict('mikey2.txt'))
print(create_dict('james2.txt'))
|
8b1a709002770b53100d2d708f1a0a38c3bb7b33 | SlipShabby/Hackerrank | /Python/functionals.py | 943 | 3.890625 | 4 | # map and lambda
cube = lambda x: x**3 # complete the lambda function
def fibonacci(n):
a,b = 0,1
for i in range(n):
yield a
a,b = b,a+b
# return a list of fibonacci numbers
# reduce
def product(fracs):
t = reduce((lambda x,y: x*y) ,fracs)# complete this line with a reduce statement
return t.numerator, t.denominator
# validate email with filter
import re
def fun(email):
# try:
# username, mail = email.split("@")
# website, domain = mail.split(".")
# except ValueError:
# return False
# if not username.replace("-", "").replace("_", "").isalnum():
# return False
# if not website.isalnum():
# return False
# if len(domain) > 3:
# return False
# return True
regex = r"^[A-Za-z0-9_-]+@[A-Za-z0-9]+\.[a-zA-Z]{0,3}$"
if not re.match(regex, email):
return False
return True
|
710c1daafafebff47a6f963c5077017cf4e9cec0 | rynk14/AlgorithmData | /4็ซ ๅๅธฐใจๅๅฒ็ตฑๆฒป/euclid.py | 1,012 | 3.921875 | 4 | # 4็ซ ๏ผๅๅธฐ
"""
p.46ใฆใผใฏใชใใใฎไบ้คๆณ
mใnใงๅฒใฃใใใพใใrใจใใใจ
GCD(m, n)=GCD(n, r)
ใงใใ
"""
def GCD(m, n):
# ใใผในใฑใผใน
if n==0: # ใใพใใ0ใชใใฐ็ตใใ
return m
# ๅๅธฐๅผใณๅบใ
return GCD(n, m%n)
print("ใฆใผใฏใชใใใฎไบ้คๆณ")
print("GCD(51, 15)={}".format(GCD(51, 15)))
print("\n")
"""
p.47ใใฃใใใใๆฐๅๅๅธฐversion
F_0=0
F_1=1
F_N=F_N-1+F_N-2 (N>=2)
"""
def fibo(n):
# ใใผในใฑใผใน
if n==0:
return 0
elif n==1:
return 1
# ๅๅธฐๅผใณๅบใ
return fibo(n-1)+fibo(n-2)
print("ใใฃใใใใๆฐๅ")
print("fibo(7)={}".format(fibo(7)))
"""
ใใฃใใใใๆฐๅใๅๅธฐใงใใใฎใฏ็ก้งใๅคใใฎใง
ๆฌกใฎใใใซใใ
"""
def fibo_kai(n):
# ไพๅคๅฆ็
if n==0:
return 0
elif n==1:
return 1
f = [0, 1]
for i in range(2,n+1):
f.append(f[i-1]+f[i-2])
return f[-1]
print("fibo_kai(7)={}".format(fibo_kai(7)))
|
bd45fe22e646e060c806a8f8969247a332700670 | obviouslyghosts/dailychallenges | /ProjectEuler/036/pe-036.py | 719 | 3.78125 | 4 | """
The decimal number, 585 = 1001001001^2 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic
in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include
leading zeros.)
"""
# an even number will end with a 0 in binary, which cannon be reversed
# all solutions must be odd
limit = 1_000_000
answers = set()
def isPalindromic( f ):
f = str(f)
if f[0] == "0": return False
if f == f[::-1]: return True
return False
for i in range(1, limit, 2):
if isPalindromic(i):
b = bin(i)[2:]
if isPalindromic(b):
answers.add(i)
print(answers)
print("sum: %i" %( sum(answers) ))
|
3afc674c012099ea0b886baf160576039102db5b | tnehf18/chatbot | /ch02_control/ex10_for.py | 4,597 | 4.03125 | 4 | # ํ์ด์ฌ ๊ธฐ์ด (+์นด์นด์คํก ์ฑ๋ด) ์คํฐ๋ 1์ฃผ์ฐจ
# python ์ ์ด๋ฌธ
# 3. ๋ฐ๋ณต๋ฌธ for
# 3.1 ๊ธฐ๋ณธ ํํ
print("\n[ 3.1 ๊ธฐ๋ณธ ํํ ] โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n")
numbers = [1, 2, 3]
print(numbers, type(numbers))
for i in numbers:
print(i)
# range() ํ์ฉ
print("\n# range() ํ์ฉ")
for i in range(0, 5):
print(i)
for i in range(5):
print(i)
# C๊ณ์ด ์ธ์ด์์ ๊ธฐ๋ณธ for ๋ฌธ๊ณผ ๊ฐ์ ์๋ฏธ๋ฅผ ์ง๋ ๋ฐฉ์.
for i in range(0, 5, 1):
print(i)
# 3.2 for ๋ฌธ์ ์์ฉ
print("\n[ 3.2 for ๋ฌธ์ ์์ฉ ] โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n")
# ๋ฌธ์์ด
print("\n# ๋ฌธ์์ด")
print("banana", type("banana"))
for c in "banana":
print(c)
text = "๋ํด๋ฌผ๊ณผ ๋ฐฑ๋์ฐ์ด ๋ง๋ฅด๊ณ ๋ณ๋๋ก ํ๋๋์ด ๋ณด์ฐํ์ฌ ์ฐ๋ฆฌ๋๋ผ ๋ง์ธ"
print(text, type(text))
for word in text.split():
print(word)
# index ์ถ๋ ฅํ๊ธฐ. len(), range() ํ์ฉ
print("\n# index ์ถ๋ ฅํ๊ธฐ. len(), range() ํ์ฉ")
fruits = ["apple", "banana", "cherry"]
print(fruits, type(fruits))
for i in range(len(fruits)):
print(i, fruits[i])
# ์ด์ค ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง ๊ฒฝ์ฐ
print("\n# ์ด์ค ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง ๊ฒฝ์ฐ")
# ๋ณ์๊ฐ ํ๋๊ฐ ์๋๋ผ ๋ณต์๋ก ์ ์ธํ๋ฉด ์๋์ผ๋ก ๊ฐ๊ฐ ๋ณ์์ ๊ฐ์ ํ ๋นํ์ฌ ๋ฐ๋ณต๋ฌธ์ ์คํ.
coord = [(0, 0), (10, 5), (20, 25)]
print(coord, type(coord))
for x, y in coord:
print(x, y)
# ๋ณ์๊ฐ ๋ถ์กฑํ๊ฑฐ๋ ์ผ์นํ์ง ์์ ๊ฒฝ์ฐ, ์๋ฌ๊ฐ ๋ฐ์ํจ.
# coord = [(0, 0), (10, 5), (20, 25)]
#
# for x, y, z in coord:
# print(x, y, z)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# ValueError: not enough values to unpack (expected 3, got 2)
# coord = [(0, 0, 1), (10, 5, 2), (20, 25, 3)]
#
# for x, y in coord:
# print(x, y)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# ValueError: too many values to unpack (expected 2)
# ๋์
๋๋ฆฌ์ ๊ฒฝ์ฐ
print("\n# ๋์
๋๋ฆฌ์ ๊ฒฝ์ฐ")
student = {
"name": "ํ๊ธธ๋",
"gender": "๋จ์ฑ",
"age": 20
}
print(student, type(student))
# keys()
for k in student.keys():
print(k)
# values()
for v in student.values():
print(v)
# items()
for k, v in student.items():
print(k, v)
# 3.3 break, continue, else
print("\n[ 3.3 break, continue, else ] โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n")
# while ๋ฌธ๊ณผ ๋์ผํ๊ฒ break, continue, else ์ฌ์ฉ ๊ฐ๋ฅ.
fruits = ["apple", "banana", "cherry"]
print(fruits, type(fruits))
# break
for x in fruits:
print(x)
if x == "banana":
break
# continue
for x in fruits:
if x == "banana":
continue
print(x)
# else
for x in fruits:
print(x)
else:
print("There are %d kinds of fruits" % len(fruits))
# โโโ
# 3.4 ์ถ์ฝํํ
print("\n[ 3.3 ์ถ์ฝํํ ] โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n")
# ๋๊ดํธ [ ]๋ก for ๋ฌธ์ ๋๋ฌ์ธ์ ์ถ์ฝ ๊ฐ๋ฅ.
fruits = ["apple", "banana", "cherry"]
print(fruits, type(fruits))
[print(x) for x in fruits]
# python ์์ ๊ต์ฅํ ๋ง์ด ์ฐ๋ ํํ์ผ๋ก, print(x) ์๋ฆฌ์ ์ฌ์ฉ์ ์ ์ ํจ์๋ฅผ ๋ฃ์ด์ ํ์ฉํจ.
# ์ถ์ฝํ์ for ๋ฌธ์ ๊ฒฐ๊ณผ๋ฅผ ๋ณ์์ ์ ์ฅ ๊ฐ๋ฅ.
# ()๋ {}๋ ๋ถ๊ฐ๋ฅํ๋ฉฐ, ๊ฒฐ๊ณผ๋ list ๋ก ๋ฐํ๋๋ค.
b = [x for x in fruits]
print(b, type(b))
# ์ถ์ฝ ํํ์ ์ด์ฉํ ๊ตฌ๊ตฌ๋จ์ ๊ฒฐ๊ณผ๊ฐ ์ ์ฅ.
result = [str(x) + "*" + str(y) + "=" + str(x * y) for x in range(1, 10) for y in range(1, 10)]
print(result)
# ()๋ ๋ค๋ฅด๊ฒ ์บ์คํ
๋์ด ์ฌ์ฉ ๋ถ๊ฐ.
# b = (x for x in fruits)
# print(b, type(b))
# {}๋ ๋ณ์๋ก๋ ์ ์ฅ ๊ฐ๋ฅํ์ง๋ง, ์คํ์ด ๋์ง๋ ์๋๋ค.
{print(x) for x in fruits}
b = {x for x in fruits}
print(b, type(b))
|
d2045429e00bfcc4b183d55d221b2d36da495bca | LachezarKostov/SoftUni | /03_ะOP-Python/05-PolymorphismandMagicMethods/02-Exercise/03_account.py | 2,465 | 3.578125 | 4 | class Account:
def __init__(self, owner: str, amount: int = 0):
self.owner = owner
self.amount = amount
self._transactions = []
def add_transaction(self, amount: int):
if not isinstance(amount, int):
raise ValueError("please use int for amount")
self._transactions.append(amount)
# โ if the amount is not an integer, raise ValueError with message
# "please use int for amount"
# otherwise, add the amount to the transactions
@property
def balance(self):
return self.amount + sum(self._transactions)
@staticmethod
def validate_transaction(account: "Account", amount_to_add):
if account.balance + amount_to_add < 0:
raise ValueError("sorry cannot go in debt!")
account._transactions.append(amount_to_add)
return f"New balance: {account.balance}"
# โ if the transaction is possible, add it.
# - if the balance becomes less than zero,
# raise ValueError with message "sorry cannot go in debt!"and break the transaction.
# Otherwise, complete it and return a message "New balance: {account_ballance}"
def __str__(self):
return f"Account of {self.owner} with starting amount: {self.amount}"
def __repr__(self):
return f"Account({self.owner}, {self.amount})"
def __len__(self):
return len(self._transactions)
def __getitem__(self, index):
return self._transactions[index]
def __eq__(self, other):
return self.balance == other.balance
def __ne__(self, other):
return self.balance != other.balance
def __lt__(self, other):
return self.balance < other.balance
def __le__(self, other):
return self.balance <= other.balance
def __gt__(self, other):
return self.balance > other.balance
def __ge__(self, other):
return self.balance >= other.balance
def __add__(self, other):
new_acc = Account(self.owner + "&" + other.owner, self.amount + other.amount)
new_acc._transactions = self._transactions + other._transactions
return new_acc
class Main:
def __init__(self):
pass
def equal_or(acc_1, acc_2):
if acc_1 == acc_2:
return True
for x in range(0, 10):
for y in range(0, 10):
acc_1 = Account("Gosho", x)
acc_2 = Account("Gosho", y)
print(equal_or(acc_1, acc_2), x, y)
|
2cddb5e422737ce9b31a383e5881fca709266226 | ilhamdwibakti/Python3.x_Object_Oriented_Programming | /Episode #13 - Super()/Main.py | 478 | 3.65625 | 4 | class Hero:
def __init__(self,name,health):
self.name = name
self.health = health
def showInfo(self):
print ("{} dengan health: {}".format(self.name,self.health))
class Hero_intelligent(Hero):
def __init__(self,name):
#Hero.__init__(self, name, 100)
super().__init__(name, 100)
super().showInfo()
class Hero_strength(Hero):
def __init__(self,name):
super().__init__(name, 200)
super().showInfo()
lina = Hero_intelligent('lina')
axe = Hero_strength('axe') |
0962cd62297cfe4f2fbd8d0e4f27e6b69b6e7c05 | KrisCheng/HackerProblem | /Python/4_ChannelExchange/force_exchange.py | 1,828 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Desc: see readme
Author: Kris Peng
Copyright (c) 2017 - Kris Peng <kris.dacpc@gmail.com>
'''
import random
import time
def Exchange(num, maxChannel):
matrix = []
for i in range(num):
matrix.append([])
for j in range(num):
matrix[i].append(0)
for i in range(num):
matrix[i][i] = 1
# print(matrix)
changeList = []
for i in range(num):
changeList.append(i)
count = 0
while True:
random.shuffle(changeList)
count = count + 1
# ๆ นๆฎๆๅบไธคไธค้
ๅฏน
for i in range(min(int(num/2),maxChannel)):
tempList = []
for j in range(num):
if(matrix[changeList[i]][j] == 1 or matrix[changeList[i+int(len(changeList)/2)]][j] == 1):
tempList.append(1)
else:
tempList.append(0)
matrix[changeList[i]] = tempList
matrix[changeList[i+int(len(changeList)/2)]] = tempList
# print("Change Log: %x , %x" % (changeList[i], changeList[i+int(len(changeList)/2)]) )
# ๅคๆญๆฏๅฆๆปก่ถณ็ปๆญขๆกไปถ
isFinal = True
# print("Currten Stage:")
for i in range(num):
# print(matrix[i])
if(matrix[i].count(1) != num):
isFinal = False
if(isFinal == False):
# print("Current Num of iteration: %d" % count)
continue
# print("Final Num of iteration: %d" % count)
return count
break
print('่ฏท่พๅ
ฅ้ไฟก็ญๆฐ็ฎ: ')
num = input()
print('่ฏท่พๅ
ฅๆๅคงๅ ๅฏไฟก้ๆฐ็ฎ: ')
maxChannel = input()
# Exchange(int(7), int(3))
temp = []
for i in range(50000):
temp.append(Exchange(int(num), int(maxChannel)))
print("ๆๅฐไบคๆขๆฌกๆฐ: %d" % min(temp)) |
5ed5e46838e79b1b71a7770013167d5f4695afcf | TDhondup/Unit_4_Lesson_5 | /Lesson 5/problem1.py | 189 | 4.03125 | 4 | from turtle import *
me = Turtle()
me.color("red")
me.pensize(6)
me.speed(7)
me.shape("turtle")
def DrawTri():
for x in range(3):
me.forward(100)
me.left(120)
DrawTri()
mainloop() |
fe9fb85561a47f44890223483420b97a84e0bf3e | paweldrzal/python_codecademy | /file_io.py | 519 | 4.0625 | 4 | #File Input/Output
my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
#This told Python to open output.txt in "w" mode ("w" stands for "write"). We stored the result of this operation in a file object, f.
#"r+" will allow you to read and write
for item in my_list:
f.write(str(item) + "\n")
f.close()
#You must close the file. If you don't close your file, Python won't write to it properly. From here on out, you gotta close your files!
|
2cf3991c1690d9a5b0d59f02d064b7547f7d2d24 | anabeatrizzz/exercicios-pa-python | /exemplos_Aula_4/Aula_4_09.py | 197 | 3.984375 | 4 | matriz = [
[1, 42, 23, 14, 51],
[22, 32, 55, 54, 12]
]
print("Os elementos pares da matriz sรฃo: ")
for a in range(0, 2):
for b in range(0, 5):
if matriz[a][b] % 2 == 0:
print(matriz[a][b]) |
8a65934afc899c73a7231a9aa8b33c361807408c | munakata0299/Python_Lesson | /python_programming/lesson63.py | 843 | 3.859375 | 4 | # Pythonใioใใใใกไธใซไฝใฃใฆใใใไธๆใใกใคใซใๅฆ็ใ็ตใใฃใใๆถใใ
import tempfile
# ไธๆใใกใคใซใไฝๆใใฆไฝฟ็จใใๆนๆณใฏไปฅไธใฎ้ใ
with tempfile.TemporaryFile(mode='w+') as t:
t.write('hello')
t.seek(0)
print(t.read())
#ใไธๆใใกใคใซใๆฎใใใๅ ดๅใซใฏไปฅไธใฎ้ใ
with tempfile.NamedTemporaryFile(delete=False) as t:
print(t.name)
with open(t.name, 'w+') as f:
f.write('test\n')
f.seek(0)
print(f.read())
# ใฆใฃใณใใฆใบใฎๅ ดๅใฏไปฅไธใฎๅ ดๆใซไฝๆใใใ
# C:\Users\user\AppData\Local\Temp\tmpใปใปใป
# Mac = cat Windows = type
#ใไธๆใใฉใซใใๆฎใใใๅ ดๅใซใฏไปฅไธใฎ้ใ
with tempfile.TemporaryDirectory() as td:
print(td)
temp_dir = tempfile.mkdtemp()
print(temp_dir) |
4cdbca49da01e32a554673d4c33db8292899f37f | sravankarthik/dsa | /mysolution/last_digit_of_fibonacci_number.py | 444 | 4.03125 | 4 | def last_digit_of_fibonacci_number(n):
assert 0 <= n <= 10 ** 7
# 1 1 2 3 5
if n == 1:
return 1
elif n==2:
return 1
a=1
b=1
for i in range(2,n):
summ=a+b
#print(summ)
x=str(summ)
x=int(x[len(x)-1])
a=b
b=x
return x
if __name__ == '__main__':
input_n = int(input())
print(last_digit_of_fibonacci_number(input_n))
|
5d2b0cdb45e3672193937851c4e8a236641591a9 | tzieba1/IntroPythonFiles | /PythonCodeSnippets/numberCheck.py | 1,459 | 3.921875 | 4 | myString = ""
keepLooping = True
while myString.lower() != "q" and keepLooping != False :
myString = input("A number: ")
myNumber = ""
isNegative = False
isFloat = False
isNumber = True
firstNumberSeen = False
decimalPointSeen = False
loopCounter = 0
while ( loopCounter < len( myString ) ) and isNumber :
if myString[loopCounter].isdecimal():
# positive integer found
firstNumberSeen = True
myNumber = myNumber + myString[loopCounter]
elif myString[loopCounter] == "-":
if not firstNumberSeen:
isNegative = not( isNegative )
else:
isNumber = False
elif myString[loopCounter] == "." or myString[loopCounter] == ",":
if not decimalPointSeen:
decimalPointSeen = True
myNumber = myNumber + myString[loopCounter]
else:
isNumber = False
else:
isNumber = False
loopCounter = loopCounter + 1
if isNumber:
if isNegative:
myNumber = "-" + myNumber
print( "Looks like the number", myNumber )
if "." in myNumber:
myNumber = float( myNumber )
else:
mynumber = int( myNumber )
if myNumber > 6:
keepLooping = False
else:
print( "Not a number" )
|
d1d01c6ba1d4cf2e3037644b0466a36af8ab0d01 | joaoppadua/fight-club | /covid ciencia git/code/budget_uni.py | 541 | 3.609375 | 4 | #Script to generate plot for budget data
import pandas as pd, numpy as np, plotly.express as px
df = pd.read_excel(r'/Users/joaopedropadua/Dropbox/Textos Padua/covid ciencia brasil/orcamento_universidades.xlsx')
graph_df = df[['Universidade', 'Valor per capita (em US$ dรณlares)']]
graph_df_rounded = graph_df.round(3)
#Plot
fig = px.bar(graph_df_rounded, x='Universidade', y='Valor per capita (em US$ dรณlares)', title='Gastos em Universidades com alunos (2018)')
fig.show()
#DEBUGGER:
#print(df.head())
#print(graph_df_rounded.head()) |
f9e5bb8777b25d3547f49c8a7e394aef74201629 | SaribK/2D-Shape-Physics | /Scene.py | 2,923 | 3.53125 | 4 | ## @file Scene.py
# @author Sarib Kashif (kashis2)
# @brief Contains the Scene class to create
# a simulation of a shape moving
# @date Feb 12 2021
# @details Uses provided functions that decide
# how the shape will behave
from scipy import integrate
## @brief Scene is a class that implements an ADT to display
# how a shape behaves
# @details the ADT contains functions Fx and Fy
# which determine how a shape would behave
class Scene:
## @brief constructor method for Scene
# @param s a shape object for which a simulation is made
# @param Fx a function for the force in the x direction
# @param Fy a function for the force in the y direction
# @param vx a real number that represents the initial velocity in the x direction
# @param vy a real number that represents the initial velocity in the y direction
def __init__(self, s, Fx, Fy, vx, vy):
self.s = s
self.Fx = Fx
self.Fy = Fy
self.vx = vx
self.vy = vy
## @brief get the shape that the Scene is using
# @return a shape object
def get_shape(self):
return self.s
## @brief get the forces of both directions
# @return a tuple containing the forces in the x and y directions
def get_unbal_forces(self):
return self.Fx, self.Fy
## @brief get the initial velocity
# @return a tuple containing the velocities in the x and y directions
def get_init_velo(self):
return self.vx, self.vy
## @brief set the shape that scene is using to the provided shape
# @param s a shape object
def set_shape(self, s):
self.s = s
## @brief set the forces to the provided ones
# @param Fx a function for the force in the x direction
# @param Fy a function for the force in the y direction
def set_unbal_forces(self, Fx, Fy):
self.Fx, self.Fy = Fx, Fy
## @brief set the initial velocities to the provided ones
# @param vx a real number that represents the initial velocity in the x direction
# @param vy a real number that represents the initial velocity in the y direction
def set_init_velo(self, vx, vy):
self.vx, self.vy = vx, vy
## @brief set the initial velocities to the provided ones
# @param t_final a real number that represents the final time
# @param nsteps a real number for the number of steps in the simulation
# @return a tuple containing the time and position data for chosen object's scene
def sim(self, t_final, nsteps):
t = []
for i in range(nsteps):
temp = (i * t_final) / (nsteps - 1)
t += [temp]
x = integrate.odeint(self.__ode__,
[self.s.cm_x(), self.s.cm_y(), self.vx, self.vy], t)
return t, x
def __ode__(self, w, t):
x = self.Fx(t) / self.s.mass()
y = self.Fy(t) / self.s.mass()
return [w[2], w[3], x, y]
|
e88ee13da4710e59dd02a5fd48896bc46baca1cf | tamzidhussainkhanpage/zserio | /compiler/extensions/python/runtime/src/zserio/builtin.py | 575 | 3.734375 | 4 | """
The module provides implementation of zserio built-in operators.
"""
def numbits(num_values: int) -> int:
"""
Gets the minimum number of bits required to encode given number of different values.
This method implements zserio built-in operator numBits.
:param num_values: The number of different values from which to calculate number of bits.
:returns: Number of bits required to encode num_values different values.
"""
if num_values == 0:
return 0
if num_values == 1:
return 1
return (num_values - 1).bit_length()
|
97a0585379f2c1396064d4a67889cd952ec2b7af | Nagappansabari/PythonPrograming | /findprimenumber.py | 242 | 3.78125 | 4 | x=input()
y=input()
if x<y:
for z in range(x+1,y-1):
if z%2!=0 and z%3!=0 and z%5!=0 and z%7!=0 and z!=1:
print z
elif z==2 or z==3 or z==5 or z==7:
print z
else:
print("enter the valid range")
|
42561e7d4d758008fb406a9b6cd40c955c63df11 | Nathx/data_structures_and_algorithms | /and_or_xor.py | 480 | 3.578125 | 4 | # https://www.hackerrank.com/challenges/and-xor-or
def max_xor(seq):
stack = []
max_xor = 0
for elem in seq:
while stack:
prev = stack[-1]
max_xor = max(max_xor, elem ^ prev)
if prev >= elem:
stack.pop()
else:
break
stack.append(elem)
return max_xor
if __name__ == '__main__':
n = int(raw_input())
seq = map(int, raw_input().split())
print max_xor(seq)
|
ecce52c06fb160666efeaa384ce5a666e6510e42 | sg13blue/TTT | /ttt.py | 1,271 | 3.703125 | 4 | from tttlib import *
def main():
T=genBoard()
gameNotOver= True
while gameNotOver:
printBoard(T)
#Player is x, game starts by X choosing available spot and displaying game state.
moveX = input("X move?")
m=int(moveX)
if m<-1 or m>9:
print("Not in range")
if T[m]!=0:
print("Spot is taken")
else:
T[m] = 1
state = analyzeBoard(T)
if state==1:
print("X won")
gameNotOver=False
elif state==3:
print("Draw")
gameNotOver = False
printBoard(T)
#o's (Computer's) turn below
if int(genOpenMove(T))== -1:
return 1
elif getWinningMove(T,2)!=-1:
o=int(getWinningMove(T,2))
elif genNonLoser(T,2)!=-1:
o=int(genNonLoser(T,2))
else:
o = int(genRandomMove(T, 2))
if o<-1 or o>9:
print("Not in range")
if T[o]!=0:
print("Spot is taken")
T[o] = 2
state = analyzeBoard(T)
if state==2:
print("O won")
gameNotOver = False
elif state==3:
print("Draw")
gameNotOver = False
printBoard(T)
main()
|
8bee1f10fa3e16c8cae5759e2343617b7829279b | arodrrigues/DP_CS_Code_ARodrigues | /tools/tools/reverseWordA.py | 559 | 4.09375 | 4 | '''
Description: Write a method called reverseWordA. The method takes
a Strings and returns the string in reverse
Parameters: String s
Returns: String
Precondition: s is a valid string of any length.
reverseWordA(โcatโ) โ โtacโ
'''
def reverseWordA(s):
a = "" #sets a to an empty string
#loop through the stirng in reverse, by increments of -1
for i in range(len(s) - 1, -1, -1):
a = a + s[i] #adds the values of the string in reverse
return a
#TESTING
print(reverseWordA("zebra"))
print(reverseWordA("d o g"))
print(reverseWordA(""))
|
81bae11b54999d460c44d4eded128691c2e7ed19 | m-sandesh/Python-Learnings | /Python/15LIstExercise.py | 345 | 4 | 4 | # A program takes start, stop and end listing values
startInp = int(input('Enter Starting Value: '))
endInp = int(input('Enter Ending Value: '))
jumpInp = int(input('Enter Jumping Value: '))
print('Integers\t' + 'Squares\t\t' + 'Cubes')
for i in range(startInp, endInp, jumpInp):
print('{}\t\t{}\t\t{}'.format(i, i**2, i**3))
|
46ef2e9502007296c7dd96e569a06669b8adbeeb | LarisaOvchinnikova/Python | /HW7(list comprehension)/0 - a list of numbers.py | 207 | 3.921875 | 4 | # Use list comprehension and range function
# to create a list of numbers with type str
def createListOfNumbers(n):
x = [str(number) for number in range(n)]
return x
print(createListOfNumbers(10)) |
7a457e123afdf2cc2c4c99f1b474a4d849d6c6fc | adi-797/10-Days-of-Statistics-Hackerrank | /10 Days of Statistics/Multiple Linear Regression.py | 689 | 3.5 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from sklearn import linear_model
input_line = str(raw_input()).split()
m,n = int(input_line[0]),int(input_line[1])
x_train=[]
y_train=[]
for i in range(n):
input_line = map(float,str(raw_input()).split())
x_train.append(input_line[:m])
y_train.append(input_line[m])
input_line = str(raw_input()).split()
k = int(input_line[0])
x_test =[]
for i in range(k):
input_line = map(float,str(raw_input()).split())
x_test.append(input_line)
lm = linear_model.LinearRegression()
lm.fit(x_train, y_train)
a = lm.intercept_
b = lm.coef_
y_pred = lm.predict(x_test)
for item in y_pred:
print round(item,2)
|
00d102b701c88b44e56eab6c98f282f4d90983d6 | rohangoli/PythonAdvanced | /Leetcode/LinkedList/p1227.py | 1,487 | 4.1875 | 4 | ## Merge Two Sorted Linked Lists
# Example 1:
# Input: list1 = [1,2,4], list2 = [1,3,4]
# Output: [1,1,2,3,4,4]
# Example 2:
# Input: list1 = [], list2 = []
# Output: []
# Example 3:
# Input: list1 = [], list2 = [0]
# Output: [0]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if list1 is None:
return list2
if list2 is None:
return list1
temp = ListNode()
ptr1 = list1
ptr2 = list2
ptr3 = temp
while ptr1 and ptr2:
if ptr1.val<= ptr2.val:
ptr3.val = ptr1.val
ptr1 = ptr1.next
else:
ptr3.val = ptr2.val
ptr2 = ptr2.next
ptr3.next = ListNode()
ptr3 = ptr3.next
if ptr1:
ptr3.val = ptr1.val
ptr3.next = ptr1.next
else:
ptr3.val = ptr2.val
ptr3.next = ptr2.next
return temp
def printList(self, listA: Optional[ListNode]) -> None:
curr = listA
while curr!=None:
print(curr.val,'->',end ='')
curr = curr.next
print('')
return None
|
9f08f757d2e93de021298dbf1629044cf949b3de | hmsong95/Lindsey-novel | /Lindsey Python/09C-cacl.py | 475 | 3.640625 | 4 | import random
a=random.randint(1,30) #1์์ 30๊น์ง ์์์ ์ ์๋ฅผ ๋ถ๋ฌ a์ ์ ์ฅํ๋ค.
b=random.randint(1,30) #1์์ 30๊น์ง ์์์ ์ ์๋ฅผ ๋ถ๋ฌ b์ ์ ์ฅํ๋ค.
print(a,"+",b,"=") #๋ฌธ์ ๋ฅผ ์ถ๋ ฅํฉ๋๋ค.
x=input() #๋ต์ ์
๋ ฅ๋ฐ์ x์ ์ ์ฅํฉ๋๋ค. ๋ฌธ์์ด๋ก ์ ์ฅ๋ฉ๋๋ค.
c=int(x) #๋ฌธ์์ด๋ก ๋์ด ์๋ x๋ฅผ ์ ์๋ก ๋ฐ๊พธ์ด c์ ์ ์ฅํฉ๋๋ค.
if a+b==c:
print("์ฒ์ฌ")
else:
print("๋ฐ๋ณด")
|
f5c6335a9718eb0f1ed34b7d7a01f0269ef97ec6 | huangsam/leetcode | /python/firstBadVersion.py | 1,103 | 3.53125 | 4 | # https://leetcode.com/problems/first-bad-version/
# Example of a possible answer (>=1)
ANSWER = 4
def isBadVersion(version):
"""
:type version: int
:rtype: bool
"""
return version >= ANSWER
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
l = 1
l_bad = isBadVersion(l)
if l_bad:
return l
h = n
h_bad = isBadVersion(h)
result = -1
while l < h:
m = (l + h) // 2
m_bad = isBadVersion(m)
if l_bad:
# look between (l, m)
result = l
h = m
h_bad = isBadVersion(h)
elif m_bad:
# look between (l + 1, m)
result = m
l, h = l + 1, m
l_bad = isBadVersion(l)
h_bad = isBadVersion(h)
elif h_bad:
# look between (m + 1, h)
result = h
l = m + 1
l_bad = isBadVersion(l)
return result
|
73f915517faed6cadb3996bd976d96e2542a1260 | burakbayramli/books | /Python_Scripting_for_Computational_Science_Third_Edition/py/regex/introre.py | 1,889 | 3.5625 | 4 | #!/usr/bin/env python
import re
# make some artificial output data from a program (just for testing):
sample_output = """
t=2.5 a: 1.0 6.2 -2.2 12 iterations and eps=1.38756E-05
t=4.25 a: 1.0 1.4 6 iterations and eps=2.22433E-05
>> switching from method AQ4 to AQP1
t=5 a: 0.9 2 iterations and eps=3.78796E-05
t=6.386 a: 1.0 1.1525 6 iterations and eps=2.22433E-06
>> switching from method AQP1 to AQ2
t=8.05 a: 1.0 3 iterations and eps=9.11111E-04
"""
lines = sample_output.split('\n')
# goal: process the lines and extract the t, iterations and eps
# data and store these in lists
# regex for a line, with the data to be extracted enclosed
# parenthesis (groups):
pattern = r't=(.*)\s+a:.*\s{3}(\d+) iterations and eps=(.*)'
# (this one extracts the t value with additional blanks, the
# next extracts exactly the t value):
pattern = r't=(.*)\s{2}a:.*\s+(\d+) iterations and eps=(.*)'
# too simple pattern:
#pattern = r't=(.*)\s+a:.*(\d+).*=(.*)'
# could compile first (for increased efficiency):
# line_pattern = re.compile(pattern)
# arrays for t, iterations and eps:
t = []; iterations = []; eps = []
# the output to be processed is stored in the list of lines:
for line in lines:
match = re.search(pattern, line)
# or if the pattern has been compiled:
# m = line_pattern.search(line)
if match:
t.append(float(match.group(1)))
iterations.append(int(match.group(2)))
eps.append(float(match.group(3)))
print 't =', t
print 'iterations =', iterations
print 'eps =', eps
# can now plot iterations versus t or eps versus t directly,
# or we can make files out of the data
# produce two two-column files with (x,y) data for plotting:
f1 = open('iterations.tmp', 'w')
f2 = open('eps.tmp', 'w')
for i in range(len(t)):
f1.write('%g %g' % (t[i], iterations[i]))
f2.write('%g %g' % (t[i], eps[i]))
f1.close(); f2.close()
|
7bd7d698e7e5f7a0779abaac09e5933e3ae7e59b | sandeepkumar8713/pythonapps | /08_graph/06_strongly_connect_component.py | 2,945 | 4.21875 | 4 | # https://www.geeksforgeeks.org/strongly-connected-components/
# Question : Given a graph with N nodes and M directed edges. Your task is to complete the
# function kosaraju which returns an integer denoting the no of strongly connected components
# in the graph. A directed graph is strongly connected if there is a path between all pairs of
# vertices. A strongly connected component (SCC) of a directed graph is a maximal strongly
# connected sub graph.
#
# Question Type : Generic
# Used : Kosaraju Algorithm
# Create an empty stack 'S' and do DFS traversal of a graph. In DFS traversal,
# after calling recursive DFSUtils for adjacent vertices of a vertex,
# push the vertex to stack.
# Make one more graph, were the edge direction is reversed.
# Now loop over the vertices popped from stack S and do DFS for it using the
# transposed graph if it is not yet visited. Its DFS will give a group of strongly
# connected components.
# Keep track of number of times DFSUtil is called(This is the ans).
# Complexity : O(V+E)
class Graph:
def __init__(self, vertices):
self.V = vertices # No. of vertices
self.graph = dict() # default dictionary to store graph
for i in range(vertices):
self.graph[i] = []
# function to add an edge to graph
def addEdge(self, u, v):
if v not in self.graph[u]:
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited[v] = True
print(v, end=" ")
for i in self.graph[v]:
if visited[i] is False:
self.DFSUtil(i, visited)
def fillOrder(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] is False:
self.fillOrder(i, visited, stack)
stack.append(v)
# Function that returns reverse (or transpose) of this graph
def getTranspose(self):
g = Graph(self.V)
for i in self.graph:
for j in self.graph[i]:
g.addEdge(j, i)
return g
def printSCCs(self):
stack = []
visited = [False] * self.V
for i in range(self.V):
if visited[i] is False:
self.fillOrder(i, visited, stack)
gr = self.getTranspose()
visited = [False] * self.V
count = 0
while stack:
i = stack.pop()
if visited[i] is False:
gr.DFSUtil(i, visited)
print("")
count += 1
print("count of SCCs : %s" % count)
if __name__ == "__main__":
# g = Graph(5)
# g.addEdge(1, 0)
# g.addEdge(0, 2)
# g.addEdge(2, 1)
# g.addEdge(0, 3)
# g.addEdge(3, 4)
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
print("Following are strongly connected components in given graph")
g.printSCCs()
|
0aa149ee7da2c99e37be853763dc71a93787f0e2 | AlfredPianist/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-to_json_string.py | 433 | 3.96875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""3-to_json_string
This module has the function to_json_string which returns the JSON
representation of an object.
"""
import json
def to_json_string(my_obj):
"""Returns the JSON representation of an object as a string.
Args:
my_obj (:obj:): The object to be dumped as JSON.
Returns:
str: The JSON string of the object.
"""
return json.dumps(my_obj)
|
7c66012a1b6bc7c306a020a7da3bc51d1aa9ece6 | shellfly/algs4-py | /algs4/depth_first_search.py | 1,262 | 3.625 | 4 | """
Execution: python depth_first_search.py filename.txt s
Data files: https: // algs4.cs.princeton.edu / 41graph / tinyG.txt
https: // algs4.cs.princeton.edu / 41graph / mediumG.txt
Run depth first search on an undirected graph.
Runs in O(E + V) time.
% python depth_first_search.py tinyG.txt 0
0 1 2 3 4 5 6
NOT connected
% python depth_first_search.py tinyG.txt 9
9 10 11 12
NOT connected
"""
from algs4.graph import Graph
class DepthFirstSearch:
def __init__(self, G, s):
self.marked = [False for _ in range(G.V)]
self.count = 0
self.dfs(G, s)
def dfs(self, G, v):
self.marked[v] = True
self.count += 1
for w in G.adj[v]:
if not self.marked[w]:
self.dfs(G, w)
if __name__ == '__main__':
import sys
f = open(sys.argv[1])
s = int(sys.argv[2])
V = int(f.readline())
E = int(f.readline())
g = Graph(V)
for i in range(E):
v, w = f.readline().split()
g.add_edge(v, w)
search = DepthFirstSearch(g, s)
for v in range(g.V):
if search.marked[v]:
print(str(v) + " ")
if search.count == g.V:
print("connected")
else:
print("not connected")
|
afa81d35577d89c3a4197f6578ae328d69cecb72 | HopeCheung/leetcode | /leetcode-first_time/leetcode53.py | 1,117 | 3.71875 | 4 | class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_num = nums[0]
def judge(nums, max_num):
if len(nums) == 0:
return max_num
if max_num <= 0:
return max(max_num, judge(nums[1:], nums[0]))
else:
if nums[0] >= 0:
return judge(nums[1:], max_num + nums[0])
else:
if len(nums) == 1:
return max_num
else:
return max(max_num, judge(nums[1:], max_num + nums[0]))
return judge(nums[1:], max_num)
###########------------memory limit exceeded
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_num, ans = -pow(2, 31), 0
for i in range(len(nums)):
if ans < 0:
ans = 0
ans += nums[i]
max_num = max(max_num, ans)
return max_num
|
8ad81d24787e9e5df8f96271721be5636014bac2 | drunkwater/leetcode | /medium/python/c0340_740_delete-and-earn/00_leetcode_0340.py | 1,194 | 3.828125 | 4 | # DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#740. Delete and Earn
#Given an array nums of integers, you can perform operations on the array.
#In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
#You start with 0 points. Return the maximum number of points you can earn by applying such operations.
#Example 1:
#Input: nums = [3, 4, 2]
#Output: 6
#Explanation:
#Delete 4 to earn 4 points, consequently 3 is also deleted.
#Then, delete 2 to earn 2 points. 6 total points are earned.
#Example 2:
#Input: nums = [2, 2, 3, 3, 3, 4]
#Output: 9
#Explanation:
#Delete 3 to earn 3 points, deleting both 2's and the 4.
#Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
#9 total points are earned.
#Note:
#The length of nums is at most 20000.
#Each element nums[i] is an integer in the range [1, 10000].
#class Solution(object):
# def deleteAndEarn(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# Time Is Money |
9e012c695b4469202e3a1c9d94c3c4fc20e8a7b7 | AudreyChigarira/Group8-OOP.py | /petclass.py | 834 | 3.640625 | 4 |
#create Class o Instance Variables: ๏ง pet_name is of type string, ๏ง breed is of type string, ๏ง age is of type int, ๏ง appointment of type Appointment
class pet():
def __init__ (self, pet_name, breed, iAge, owner): #def __init__ (self, pet_name, breed, iAge, appointment?):
self.pet_name = pet_name
self.breed = breed
self.age = iAge
#self.appointment = appointment(owner) #When calling the Appointment constructor you will want to pass the owner
# pet constructor
def pet (self, pet_name, breed, age, owner):
self.appointment = appointment(owner) #When calling the Appointment constructor you will want to pass the owner
#pet method
oCustomer.cust_pet = Pet(self.pet_name, self.breed, self.iAge, self.oCustomer)
return(oCustomer.cust_pet)
|
7829693777b0e59bff40fe587184d0608ea27119 | potirar/CodigoPythonDSI | /Comandos/exemplo4(Estrutura condicional).py | 329 | 4.28125 | 4 | # Estutura se e senรฃo (if or else)
nota1 = float(input("Digite a nota 1:"))
nota2 = float(input("Digite a nota 2:"))
nota3 = float(input("Digite a nota 3:"))
media = (nota1+nota2+nota3)/3
if media > 7:
print('Vocรช passou')
elif media == 7:
print('Passou arrastado')
else :
print('Infelizmente, vocรช nรฃo passou')
|
16553922f9f2cf67bb7aad8c2d739b08081c14fa | Gugunner/python-challenge | /PyPoll/main.py | 2,615 | 3.515625 | 4 | # TODO GET TOTAL NUMBER OF VOTES
# TODO GET LIST OF CANDIDATES
# TODO GET PERCENTAGE OF VOTES PER CANDIDATE
# TODO GET NUMBER OF VOTES PER CANDIDATE
# TODO GET WINNER OF ELECTION
import os
import csv
# declare all global variables
elections = { 'candidates': {} }
csvPath = os.path.join('Resources', 'election_data.csv')
totalVotes = 0
def checkForExistingCandidate(candidate):
if not candidate in elections['candidates']:
elections['candidates'][candidate] = { 'voteShare': 0.0, 'votes': 0 }
def addVotesToCandidate(candidate):
votes = elections['candidates'][candidate]['votes']
elections['candidates'][candidate]['votes'] += 1
def addVoteShareOfCandidate(candidate):
global totalVotes
votes = elections['candidates'][candidate]['votes']
elections['candidates'][candidate]['voteShare'] = (votes/totalVotes) * 100
def checkWinnerCandidate():
winnerName = ''
winnerVotes = 0
for candidate in elections['candidates']:
if elections['candidates'][candidate]['votes'] > winnerVotes:
winnerVotes = elections['candidates'][candidate]['votes']
winnerName = candidate
return winnerName
with open(csvPath) as csvFile:
csvreader = csv.reader(csvFile, delimiter = ',')
# advance csv to skip header
next(csvreader)
# get enumerable list to get length of csv
rows = [vote for vote in csvreader]
totalVotes = len(rows)
# Used tupples for each csv column
for (voterId, county, candidate) in rows:
# logic to add names and votes
checkForExistingCandidate(candidate)
addVotesToCandidate(candidate)
# after it's finished get percentage of each candidate with a list comprehension
[addVoteShareOfCandidate(candidate) for candidate in elections['candidates']]
# Create all string variable before printing and writing to text file
results = [' Election Results', '------------------------',
f'Total Votes {totalVotes}', '------------------------']
for candidate in elections['candidates']:
votesShare = elections['candidates'][candidate]['voteShare']
votes = elections['candidates'][candidate]['votes']
results.append(f'{candidate}: ''%.3f'%votesShare+f'% ({votes})')
results.append('------------------------')
results.append(f'Winner: {checkWinnerCandidate()}')
results.append('------------------------')
# Printing and writing to file
for result in results:
print(result)
analysis_file = os.path.join('analysis', 'analysis.txt')
analysis = open(analysis_file, 'w')
fileResults = [f'{result}\n 'for result in results ]
analysis.writelines(fileResults) |
c1a91dd53dc15fe46f8cebab2af6c821e2030629 | rifatmondol/Python-Exercises | /009 - [Strings] Data Por Extenso.py | 533 | 4 | 4 | #009 - Data por extenso. Faรงa um programa que solicite a data de nascimento (dd/mm/aaaa) do usuรกrio e
#imprima a data com o nome do mรชs por extenso.
#Data de Nascimento: 29/10/1973
#Vocรช nasceu em 29 de Outubro de 1973.
meses = ['Janeiro', 'Fevereiro', 'Marรงo', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro',
'Outubro', 'Novembro', 'Dezembro']
dia, mes, ano = input('Escreva a data de nascimento no formato DD/MM/AAAA: ').split('/')
print('Vocรช nasceu no dia {} de {} de {}'.format(dia, meses[int(mes)-1], ano)) |
b2b0ef0e5f9055632008d88784e9a802cee84a9c | rickyriosp/MITx-6.00.2x-Introduction-to-Computational-Thinking-and-Data-Science | /Quiz/midterm_problem3.py | 944 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 11:47:12 2018
@author: nas7ybruises
"""
def greedySum(L, s):
""" input: s, positive integer, what the sum should add up to
L, list of unique positive integers sorted in descending order
Use the greedy approach where you find the largest multiplier for
the largest value in L then for the second largest, and so on to
solve the equation s = L[0]*m_0 + L[1]*m_1 + ... + L[n-1]*m_(n-1)
return: the sum of the multipliers or "no solution" if greedy approach does
not yield a set of multipliers such that the equation sums to 's'
"""
maxCost = s
m = [0] * len(L)
for i in range(len(L)):
m_n = 1
while m_n * L[i] <= maxCost:
m_n += 1
m[i] = m_n-1
maxCost -= (m_n-1) * L[i]
return sum(m) if maxCost == 0 else 'no solution'
# Test
#print(greedySum([10, 5, 1], 14))
|
d48b7136bc7481b4a71d285ed40d710cc0d07006 | aotalento/python-challange | /pybank/.ipynb_checkpoints/Main-checkpoint.py | 2,588 | 3.59375 | 4 | # import dependants
import csv
import os
# add file path
BankData = os.path.join("budget_data.csv")
# Set list variables
Profits = []
MonthlyChange = []
Date = []
# Set variables to zero
MonthCount = 0
TotalProfits = 0
Change = 0
StartingProfit = 0
with open(BankData, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
csvheader = next(csvreader)
#Count the months in the sheet
for row in csvreader:
MonthCount = MonthCount + 1
#Set the date column
Date.append(row[0])
#Set the profits column
Profits.append(row[1])
#Calculate total profits
TotalProfits = TotalProfits + int(row[1])
#Calculate average change in profits
FinalProfit = int(row[1])
Monthly_Change= FinalProfit - StartingProfit
#Add a list for the changes
MonthlyChange.append(Monthly_Change)
Change = Change + Monthly_Change
StartingProfit = FinalProfit
ProfitChanges = round((Change/MonthCount))
#Find the hightst number in the change
GreatestIncrease = max(MonthlyChange)
IncreaseDate = Date[MonthlyChange.index(GreatestIncrease)]
#Find the lowest change
GreatestLoss = min(MonthlyChange)
LossDate = Date[MonthlyChange.index(GreatestLoss)]
print("-----------------------------------------------")
print(" Financial Analysis")
print("-----------------------------------------------")
print("Total Months: " + str(MonthCount))
print("Total Profits: $" + str(TotalProfits))
print("Average Profit Change: $" + str(ProfitChanges))
print('Greatest Increase in Profits:' + str(IncreaseDate) +" ($" + str(GreatestIncrease) + ")")
print('Greatest Loss in Profits:' + str(LossDate) + '($' + str(GreatestLoss) + ')')
with open('Financial_Analysis.txt', 'w') as text:
text.write("-----------------------------------------------\n")
text.write(" Financial Analysis" + "\n")
text.write("-----------------------------------------------\n")
text.write("Total Months: " + str(MonthCount) + "\n")
text.write("Total Profits: $" + str(TotalProfits) + "\n")
text.write("Average Profit Change: $" +str(ProfitChanges) + "\n")
text.write('Greatest Increase in Profits:' + str(IncreaseDate) +" ($" + str(GreatestIncrease) + ")" + "\n")
text.write('Greatest Loss in Profits:' + str(LossDate) + '($' + str(GreatestLoss) + ')' + "\n") |
9e187db8632740055b7af48f8e00e62fba5ac349 | bbuchake/learn-python | /Candy and Pie Store/candystore.py | 641 | 3.90625 | 4 | candyInStore = ["Snickers", "Kit Kat", "Sour Patch Kids", "Juicy Fruit", "Sweedish Fish", "Skittles", "Hershey Bar", "Skittles", "Starbursts", "M&Ms"]
allowance = 5
selectedCandy = []
#for i in range(len(candyInStore)):
#print("[" + str(i) + "] " + candyInStore[i])
for candy in candyInStore:
print ("[" + str(candyInStore.index(candy)) + "] " + candy)
while allowance > 0:
candyIndex = int(input ("Which candy would you like to take home?"))
selectedCandy.append(candyInStore[candyIndex])
allowance = allowance - 1
print("You are taking home: ")
for j in range(len(selectedCandy)):
print(selectedCandy[j])
|
28308ec2f781dd9db5644a23690bd3659ca3c806 | tdkumaran/python-75-hackathon | /String/stroperation4.py | 500 | 4.09375 | 4 | #split string
s="am daily coding in Python, so, I develoope my knowledge"
print(s.split(","))
#join list of string
date="14"
month="12"
year="2018"
today="-".join([date,month,year])
print(today)
#case converting
print(s.capitalize())
#return first letter capitalize
print(s.lower())
#print all uppercase to lowercase
print(s.upper())
#print all lowercase to uppercase
print(s.title())
#print in every word starting letter as capital
print(s.swapcase())
#print every lower to upper and viceversa
|
43769796453af972a5e03580d2056fe4e28408f4 | Andressa-Anthero7/Exercicios-Python | /Desafio-97.py | 349 | 3.78125 | 4 | #Faรงa programa que tenha uma funรงรฃo chamada escreva(),
# que receba um texto qualquer e mostre uma mensagem
# com tamanho adaptรกvel
#Autora:Andressa Cristina Anthero
def escreva(frase):
tam = len(frase) + 4
print('~'*tam)
print(f' {frase}')
print('~'*tam)
frase = str(input('Escreva a frase aqui: '))
escreva(frase)
|
30cbc0b09c88c599b493f7b796853dee33aaf7c3 | twterryh/statistical_analysis | /NumpyScipy/05_norm(length).py | 315 | 3.671875 | 4 | import numpy as np
# vector length : norm of vector
# ||a||
# = root a.T * root a
a = np.array([1,3])
print(np.linalg.norm(a))
# 3.1622776601683795
# ๋จ์ ๋ฒกํฐ (unit vector) : ๊ธธ์ด๊ฐ 1 ์ธ ๋ฒกํฐ
# ex) [0,1], [0,1], [1/np.sqrt(2),1/np.sqrt(2)]
a = np.array([0,1])
print(np.linalg.norm(a))
|
b905432dbcca308d3624de9cc0194222a2fbe72d | BramvdnHeuvel/Batteryboys | /classes/house.py | 1,010 | 4.03125 | 4 | class House:
"""
The house class represents a house in the smart grid. Each house has an id,
an x and y coordinate which determine the location of the house in the grid,
and an output.
"""
def __init__(self, id, x, y, output):
self.id = id
self.x = x
self.y = y
self.output = output
self.connected = None
def __eq__(self, other):
try:
if self.x == other.x and self.y == other.y:
return True
except AttributeError:
return False
else:
return False
def connect(self, battery):
"""
Connect house to battery, update power, and return battery
"""
self.connected = battery
battery.store(self.output)
return self.connected
def __repr__(self):
"""
Specify which house to use.
"""
return '<House id={} x={} y={} out={}>'.format(self.id,self.x,self.y,self.output)
|
000d3e67d07fd3cb072c9daae86945ea891af873 | Anastasiya999/Python | /zestaw6/test_fracs.py | 1,982 | 3.6875 | 4 | import unittest
from fracs import *
class TestFracs(unittest.TestCase):
def setUp(self):
self.zero=Frac(0,1)
self.negative=Frac(-5,7)
self.positive=Frac(3,4)
self.need_simplify=Frac(5,10)
def test_print(self):
self.assertEqual(str(self.need_simplify),"1/2")
self.assertEqual(repr(self.zero),"Frac(0, 1)")
def test_cmp(self):
self.assertTrue(self.positive==self.positive)
self.assertFalse(self.positive==self.zero)
self.assertTrue(self.need_simplify==Frac(1,2))
self.assertTrue(self.positive!=self.negative)
self.assertFalse(self.zero!=Frac(0,4))
self.assertTrue(Frac(2,5)<Frac(3,5))
self.assertFalse(Frac(-2,7)<Frac(-5,7))
self.assertTrue(Frac(2,5)<=Frac(3,5))
self.assertFalse(self.positive<=self.negative)
self.assertTrue(self.positive>self.negative)
self.assertFalse(self.zero>Frac(0,2))
self.assertTrue(self.zero>=Frac(0,5))
self.assertFalse(self.negative>=self.positive)
def test_add(self):
self.assertEqual(self.zero+Frac(5,6),Frac(5,6))
self.assertNotEqual(Frac(-5,8)+Frac(4,8), self.zero)
def test_sub(self):
self.assertEqual(Frac(1,2)-Frac(8,16),self.zero)
self.assertNotEqual(self.zero-self.positive,self.positive)
def test_div(self):
self.assertEqual(Frac(1,2)/Frac(1,2),Frac(1,1))
self.assertNotEqual(self.zero/self.positive,self.positive)
self.assertRaises(ZeroDivisionError,Frac.__truediv__,self.positive,self.zero)
def test_mul(self):
self.assertEqual(self.zero*self.positive,self.zero)
self.assertNotEqual(Frac(2,5)*Frac(3,4),Frac(5,20))
def test_float(self):
self.assertEqual(float(Frac(1,2)),1/2)
self.assertNotEqual(float(self.positive),3//4)
def tearDown(self): pass
if __name__ == '__main__':
unittest.main() # uruchamia wszystkie testy
|
adc7e738ba1adba1ce1e67b2241b7c64e3668c4a | joaomlneto/tuenti-challenge-2020 | /07/main.py | 1,388 | 3.546875 | 4 | #!/usr/bin/env python3
import argparse
import icu
import os
import re
import sys
parser = argparse.ArgumentParser(description="Tuenti Challenge 2020 - Problem 07")
parser.add_argument("-f", "--file", dest="filename", type=str,
help="the text file to analyze", required=True)
args = parser.parse_args()
mapping = {
"'": 'q',
',': 'w',
'.': 'e',
'p': 'r',
'y': 't',
'f': 'y',
'g': 'u',
'c': 'i',
'r': 'o',
'l': 'p',
'?': '[UNKNOWN]',
'+': '[UNKNOWN]',
'a': 'a',
'o': 's',
'e': 'd',
'u': 'f',
'i': 'g',
'd': 'h',
'h': 'j',
't': 'k',
'n': 'l',
's': ';',
';': 'z',
'q': 'x',
'j': 'c',
'k': 'v',
'x': 'b',
'b': 'n',
'm': 'm',
'w': ',',
'v': '.',
'z': '/',
' ': ' ',
'\n': '\n',
'0': '0',
'1': '1',
'2': '2',
'3': '3',
'4': '4',
'5': '5',
'6': '6',
'7': '7',
'8': '8',
'9': '9',
'(': '(',
')': ')',
'-': "'"
}
# compute how often each word appears
with open(args.filename, 'r') as file:
num_cases = int(next(file))
for i in range(0, num_cases):
encrypted_line = str(next(file))
out = ''.join([mapping[x.lower()] if x in mapping else '[?????]' for x in encrypted_line]).rstrip().ljust(80, ' ')
print('Case #%i: %s\n' % (i + 1, out), end='')
|
f068cf0ac9571a39aa5dd868d3f6d3e5eb7609b6 | joreakshay/python | /SimplePrograms/List/list.py | 258 | 3.984375 | 4 | def addelement(l1,var):
if type(var)==list :
l1.extend(var)
else :
l1.append(var)
def main():
l1=[1,2,3]
print l1
addelement(l1,4)
print l1
l2=[5,6,7]
addelement(l1,l2)
print l1
if __name__=="__main__":
main() |
cacefab29f4ebd4a312ad416c3963cc4edf19ea2 | jessicagmarshall/machine-learning | /conjugate_priors/Marshall_MSE_GaussianKnownSigma.py | 3,600 | 3.609375 | 4 | #Jessica Marshall
#ECE414 Machine Learning
#Conjugate Priors Programming Assignment
#MSE plots - Gaussian sigma
##########################################
#import libraries
import math
import numpy as np
import matplotlib.pyplot as plt
##########################################
#generate normally distributed observations with awgn
#here we assume the mean is known, the standard deviation is unknown parameter
#this is the likelihood function in Baye's rule
mu = 0 #known
sigma = 2
variance = sigma**2
precision = 1/variance #unknown -> trying to estimate
N = 100 #number of observations
mu_noise = 0
sigma_noise = sigma/2
variance_noise = sigma_noise**2
X = np.random.normal(mu + mu_noise, (math.sqrt(variance + variance_noise)), N) #mus and variances add
##########################################
#mean squared error of maximum likelihood
numIter = 10 #times we run the estimator (requires new data)
ML = np.zeros((numIter, N)) #hold max likelihood values of each observation update for each estimator run
data = np.zeros((numIter, N))
for i in range(0, numIter): #using the new mu and sigma, run estimator multiple times by generating list of observations multiple times
X_ML = np.random.normal(mu+ mu_noise, math.sqrt(variance + variance_noise), N) #generate 1000 observations
data[i] = X_ML
for j in range(0, N):
ML[i, j] = (1/(j+1))*(((X_ML[:j+1]- mu)**2).sum()) #store ML estimate of variance for this observation index
#for each observation "set" calculate the MSE of each ML estimate
SE = ((1/ML) - precision)**2
MSE_ML = np.mean(SE, axis=0)
#plot mean squared error of max likelihood estimate at each observation
fig2 = plt.figure()
x = np.linspace(1, N, N)
ax21 = fig2.add_subplot(1, 1, 1)
ax21.plot(x, MSE_ML, 'b', label='MSE of Max Likelihood Estimate')
ax21.set_title('MSE of Max Likelihood Estimate and Conjugate Prior - Precision of Gaussian with Known Mean', fontweight='bold')
##########################################
#update equations for Gaussian
#the conjugate prior of the Gaussian with known mean is a Gamma
#define hyperparameters of initial prior
a_0= [5, 2, 10] #choose 3 different hyperparameter a's and b's
b_0 = [4, 2, 5] #make this very broad
color = ['y','r', 'c']
SE_conjprior= np.zeros((numIter, N))
for l in range(0, len(a_0)):
#do this for multiple different hyperparameters
update_a = a_0[l]
update_b = b_0[l]
for i in range(0, numIter):
X_ML = data[i] #use same observations as max likelihood for each trial to ensure comparability
for j in range(0, N): #N is the observation in question, one index off
n_update = j + 1
sum_xn_mu_squared = sum((X_ML[0:n_update] - mu)**2)
update_a = update_a + (n_update/2)
update_b = update_b + (sum_xn_mu_squared/2)
#mean squared error of precision
precision_est = update_a/update_b
SE_conjprior[i, j] = (1/(j+1))*((precision_est-precision)**2)
#plot MSE of conjugate prior update at each obsercation
MSE_conjprior = np.mean(SE_conjprior, axis=0)
ax22 = fig2.add_subplot(1, 1, 1)
ax22.plot(x, MSE_conjprior, color[l], label='MSE of Conjugate Prior: a = ' + str(a_0[l]) + ', b = ' + str(b_0[l]))
handles, labels = ax21.get_legend_handles_labels()
ax22.legend(handles, labels)
ax22.set_xlabel('Observations')
ax22.set_ylabel('Mean Squared Error') |
98c0a69dc1892e8cd61fbb9fe307f4b25a0cb84b | lgc13/LucasCosta_portfolio | /python/practice/personal_practice/ticTacToeV2.py | 896 | 4.21875 | 4 | # ticTacToeGame v2, made by Lucas Costa and Sasha Larson
# started on Feb 26, 2017
# what we need in order to make a tic tac toe game in python
# v2: we will also make it so that we can play against the computer
# finally, we will make this 2D
"""
What we need:
1- Board array
2- Players
a- accept input
3- Rules
4- Fill in board
a- remember input
b- show current input
5- Declare winner
How the computer will think/display things
1- Welcome log
2- Display the board
3- Ask for input for player 1
a- Display board with player 1 input
b- check if there's a winner
4- Ask for input for player 2
a- Display board with player 1 and 2 input
b- check if there's a winner
5- Display winner/tie message
"""
# making board list
row = ['1','2','3']
col = ['',' ',' ']
board2 = [row, col]
board = [["1", "2", "3"],["4", "5", "6"]]
for i in row:
for j in col:
print board2
print board
|
1dbdeb0ab1e9ac41973b8448a6e993c7b914ae5e | yangzhao5566/go_study | /DesignPatterns/bag.py | 880 | 3.671875 | 4 | """
Bag
"""
class Bag(object):
"""
bag
"""
def __init__(self):
self._items = list()
def __len__(self):
return len(self._items)
def __contains__(self, item):
return item in self._items
def add(self, item):
self._items.append(item)
def remove(self, item):
assert item in self._items, "item must in the bag"
return self._items.remove(item)
def __iter__(self):
return _BagIterator(self._items)
class _BagIterator(object):
def __init__(self, seq):
self._bag_items = seq
self._cur_item = 0
def __iter__(self):
return self
def __next__(self):
if self._cur_item < len(self._bag_items):
item = self._bag_items[self._cur_item]
self._cur_item += 1
return item
else:
raise StopIteration
|
0ee0bb58c02635d4c55e982d1195ab044d761b77 | kotegowder/linkedin_learning_python | /06_class.py | 486 | 3.78125 | 4 | class myClass():
def method1(self):
print("myClass method1")
def method2(self, someStr):
print("myClass method2 " + someStr)
class myAnotherClass(myClass):
def method1(self):
myClass.method1(self)
print("myAnotherClass method1")
def method2(self, someStr):
print("myAnotherClass method2")
def main():
c = myClass()
c.method1()
c.method2("This is a string")
c1 = myAnotherClass()
c1.method1()
c1.method2("This is a string")
if __name__ == "__main__":
main()
|
aefaf80ed082b09aedfb6d874233c58f55b64826 | wwoods93/Python_Challenge | /challenge1.py | 722 | 3.75 | 4 | ###################################################################
# Python Challenge Level 1 Solution
# Wilson Woods
# 10/16/19
# Program translates a string where all chars are shifted by a set amount
# In this case shift is +2 (a = c, b = d, etc.)
# increment = [shift amount] & decrement = [26 - shift amount]
###################################################################
increment = 2
decrement = 24
mystring = raw_input('Enter string: ')
for c in mystring:
if ord(c) < 97:
print (c),
elif ord(c) > 120:
newAsc = ord(c) - decrement
newChar = chr(newAsc)
print(newChar),
else:
newAsc = ord(c) + increment
newChar = chr(newAsc)
print(newChar),
|
df36833f719eaa8e9828c69a86d72ee5148ae8f2 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/chtgen002/question4.py | 1,068 | 3.84375 | 4 | """
Graph of mathematical function
Genevieve Brownyn Chetty (CHTGEN002)
16/04/2014
"""
import math
def main():
function = input("Enter a function f(x):\n")
x=0
y=0
for row in range(10,-11,-1): #-10 to 10 axes limit
for column in range(-10,11,1):
x=column
rndf=round(eval(function))
if (rndf==row): #print function
print("o", end="")
if ((row==0) and (column==0) and not (row==rndf)): #print origin
print("+", end="")
if ((row==0) and not (column==0) and not (row==rndf)): #print x axis
print("-", end="")
if ((column==0) and not (row==0) and not (row==rndf)): #print y axis
print("|", end="")
else: #empty spaces
if not (row==0):
if not (column==0):
if not (row==rndf):
print(" ", end="")
print()
main() |
69331a7c381ccfcf1011036cbc2a4ebe156e3318 | Hafizuddin961/data-science-project1 | /test.py | 293 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 7 10:19:02 2020
@author: hafizuddin
"""
import pandas as pd
df = pd.read_csv("glassdoor_jobs.csv")
df = df[df['Salary Estimate'] != '-1']
salary = df['Salary Estimate'].apply(lambda x: x.split('(')[0])
salary_hour = salary.find('Per Hour') |
07c424d0d6e51c2469e74073ffa102c06b77cd6b | NR4l3rt0/pcap_netacad | /frequency_histogram.py | 2,010 | 3.984375 | 4 | """
This program will check how many characters there are in a given text file
and will create a histogram from it (if the value is 0, then will be omitted)
"""
from os import strerror
# In this case, we will assume that the text file is in the same directory as the program
def take_txt_name():
out= False
while not out:
txt_name= input("Please, enter the name of the file you want to analyse: ")
try:
assert txt_name != str()
out= True
except:
print("Error: no valid input")
exit()
return txt_name
# This will try to read the file and put it in the memory
def read_file(txt_name):
file= ''
try:
lines_no= 0
txt_f= open(txt_name, 'rt')
line= txt_f.readline()
while line != '':
file += line
line= txt_f.readline()
lines_no += 1
except IOError as e:
print("Error in the I/O operation: ", strerror(e.errno))
exit(e.errno)
# close the stream
else:
txt_f.close()
print("Number of lines read=", lines_no)
return file
def create_results(file):
result= dict()
file= file.lower() # transform the file to be case-insensitive
for i in range(97, 123): # define and initialize the dictionary's keys
result.update({chr(i): 0})
for ch in file: # actualize the values for each key for this concrete text
if ch in result.keys():
result[ch] += 1
else:
continue
for el in result: # show the results if the value is greater than 0
if result[el] != 0:
print(el, result[el], sep=" -> ")
else:
continue
# start
try:
txt_name= take_txt_name()
file= read_file(txt_name)
create_results(file)
except KeyboardInterrupt:
print()
print("Thanks anyways!")
print()
|
469330e8d9e9ff567f57b8ef3e41445c8c797775 | billxsheng/python | /maps.py | 321 | 3.578125 | 4 | import collections
dict1 = {"day1": "Mon", "day2": "Tues"}
dict2 = {"day3": "Wed", "day4": "Thurs"}
map = collections.ChainMap(dict1, dict2)
print(map)
print('Keys = {}'.format(list(map.keys())))
print('Values = {}'.format(list(map.values())))
print()
for key,val in map.items():
print('{} = {}'.format(key, val))
|
96b581a2b0125ee8a0dc3c70110eb992d49c2f1e | sorttomat/julekalender | /luke4.py | 1,746 | 3.53125 | 4 |
def erPartall(tall):
return tall % 2 == 0
def checkElementInThing(thing, element):
antall = 0
for elem in thing:
if elem == element:
antall += 1
return antall
def numberOfEachLetter(word):
antBokstaver = []
for bokstav in word:
antBokstaver.append(checkElementInThing(word, bokstav))
word = word.replace(bokstav, "")
return antBokstaver
def sjekkMulighet(lst):
partallOddetall = []
for elem in lst:
if erPartall(elem):
partallOddetall.append(True)
else:
partallOddetall.append(False)
print(False)
if checkElementInThing(partallOddetall, False) == 1 or checkElementInThing(partallOddetall, False) == 0:
return True
return False
def checkPalendrome(word):
antBokstaver = numberOfEachLetter(word)
if sjekkMulighet(antBokstaver) or len(word) == 0 or len(word) == 1:
return True
return False
def checkAlreadyPalendrome(word):
if word == word[::-1]:
return True
return False
def checkAllWords(filename, newFilename):
palindromes = open(newFilename, "w")
count = 0
with open(filename, "r") as infile:
for line in infile:
word = line.strip("\n")
word = word.strip("-")
word = word.lower()
if checkPalendrome(word) and checkAlreadyPalendrome(word) == False:
palindrome = word + "\n"
palindromes.write(palindrome)
count += 1
palindromes.write("Number of palindromes: \n")
palindromes.write(str(count))
palindromes.close()
infile.close()
checkAllWords("anagramlist.txt", "listoveranagrams.txt")
|
65fc656cd60ff2b32d80fd1417e43931744b761b | AshokKumarChoppadandi/PythonExamples | /PythonBasics/Basics.py | 12,220 | 3.78125 | 4 | # This is a comment
"""
This are Multi-line comments
"""
# importing the libraries
import sys
import math
import random
import threading
import time
from functools import reduce
"""
print('HELLO WORLD...!!!')
"""
"""
# Primitive DataTypes:
# integers, floats, complex numbers, strings, booleans
# Variable Declaration
a = 5
b = "This is a String"
c = 'This is also a String'
d = 5.5
e = True
f = 'z'
print(a, b, c, d, e, f)
"""
"""
# Variable declaration with it's types
a2: int = 5
b2: str = "This is a String"
c2: str = 'This is also a String'
d2: float = 5.5
e2: bool = True
f2: chr = 'z'
print(a2, b2, c2, d2, e2, f2)
"""
"""
# Reading input from Console
name = input("What is your name ???\n")
print("Hello: ", name)
"""
"""
# Multi-line Expressions
sum1 = (
1 + 2
+ 3
)
print("Sum1", sum1)
sum2 = 1 + 2 \
+ 3
print("Sum2", sum2)
"""
"""
# Multiple Expressions in one line
v1 = 4; v1 += 2
print(v1)
"""
"""
# Assigning Same Value to multiple variables
val1 = val2 = 5
print("val1:", val1)
print("val2:", val2)
"""
"""
# To get the type of the Variable
test = 10
print("10 is of :", type(test))
# Maximum integer size that Python supports
print(sys.maxsize)
# Maximum float size that Python supports
print(sys.float_info.max)
# Float values up to 15 digit precision gives correct value beyond that gives wrong values
f1 = 1.1111111111111111
f2 = 1.1111111111111111
f3 = f1 + f2
print("f1 + f2 =", f3)
# Complex Numbers
c1 = 5 + 6j
print("Complex Number:", c1)
# Escape Sequence
escStr = "This is an String with Escape sequences \n \" \\ \t \'"
print(escStr)
escStr2 = '''This is an String with Escape sequences \n \" \\ \t \''''
print(escStr2)
"""
'''
escStr3 = """This is an String with Escape sequences \n \" \\ \t \'"""
print(escStr3)
'''
"""
# Type Casting
# Float to Integer
print("CAST1:", type(int(5.4)))
# Float to String
print("CAST2:", type(str(5.4)))
# Integer to Float
print("CAST3:", type(float(5)))
# This also convert into String
print("CAST4:", type(chr(50)))
# Converts Single Character to an Integer
print("CAST5:", type(ord('a')))
"""
"""
# Printing the Result with the required separator
print(4, 9, 1990, sep="/")
print(4, 9, 1990, sep="-")
print(4, 9, 1990, sep=":")
print(4, 9, 1990, sep="\t")
"""
"""
# Printing values with the required end line string
print("This line don't have new line character at the end of the line", end="")
print("THIS IS THE NEXT LINE")
"""
"""
# Printing different types of values
print("\n%4d, %s, %.2f %c" % (10, "TEST", 1.2345, 'A'))
print("\n%04d, %s, %.2f %c" % (10, "TEST", 1.2345, 'A'))
"""
# Arithmetic Operations
"""
print("10 + 4:", 10 + 4)
print("10 - 4:", 10 - 4)
print("10 * 4:", 10 * 4)
print("10 / 4:", 10 / 4)
print("10 % 4:", 10 % 4)
print("10 ** 4:", 10 ** 4)
print("10 // 4:", 10 // 4)
i1 = 5
i1 += 2
print("Final i1 =", i1)
"""
"""
# Math Functions
print("abs(-1):", abs(-1))
print("max(3,5):", max(3,5))
print("min(3,5):", min(3,5))
print("pow(3,5):", pow(3,5))
print("math.ceil(3.5):", math.ceil(3.5))
print("math.floor(3.5):", math.floor(3.5))
print("round(3.5):", round(3.5))
print("exp(1):", math.exp(1))
print("math.sqrt(9):", math.sqrt(9))
print("log(100):", math.log(100, 10))
print("radians(0):", math.radians(0))
print("degrees(pi):", math.degrees(math.pi))
"""
"""
# Random Number
print("Random number in 1 to 100:", random.randint(1, 101))
print("Random number in 1 to 100:", random.randint(1, 101))
print("Random number in 1 to 100:", random.randint(1, 101))
"""
"""
# NaN - Not a Number
# Inf - Infinity
print("Infinity > 0:", (math.inf > 0))
print("Infinity - Infinity:", (math.inf - math.inf))
print("Infinity - 100:", (math.inf - 100))
"""
"""
# Conditional Statements - if, if else, nested if, else if ladder
age = 60
# Logical Operators: <, >, <=, >=, ==, !=
if age < 18:
print("Person is a Minor")
elif age > 18:
print("Person is a Major")
elif age == 18:
print("Person is of age 18")
else:
print("Not a correct age")
# Relational Operators
if age <= 5:
print("Kid")
elif (age > 5) and (age < 18):
print("Minor")
elif (age >= 18) and (age < 30):
print("Youth")
elif (age >= 30) and (age <= 45):
print("Middle Aged")
else:
print("Senior Citizen")
"""
"""
# Ternary Operation in Python
# condition_true if condition else condition_false
personAge = 21
person = "Major" if personAge > 10 else "Minor"
print("Person is :", personAge)
"""
"""
# Strings
# In Python, Strings can be declared with single or doubles, triple single or double quotes
str1 = 'This is string with single quotes'
str2 = "This is string with double quotes"
str3 = '''This is a string with triple single quotes'''
"""
'''
str4 = """This is a string with triple double quotes"""
print(str1)
print(str2)
print(str3)
print(str4)
'''
"""
# Ignoring escape sequences in Strings
escstr1 = r"This is a string without escape sequence \t\n"
print(escstr1)
# Appending the Strings
string1 = "test1"
string2 = "test2"
print(string1 + " " + string2)
charString = "Hello World"
# Length of the String
print("Length :", len(charString))
# Char at index 0
print("charString[0] :", charString[0])
# Last Char
print("charString[-1] :", charString[-1])
# Char from index 0 to 2 but not 3
print("charString[0:2] :", charString[0:3])
# Every Other character in the String - Print first char and skip the next
print("Every Other Char :", charString[0:-1:2])
# Every Other two characters in the String - Print first char and skip next two
print("Every Other Two Char :", charString[0:-1:3])
# Replace the chars in the string
charString2 = charString.replace("Hello", "Goodbye")
print(charString2)
# Chars 0 till index 8 and chars from index 9 to last
charString3 = charString2[:8] + "w" + charString2[9:]
print(charString3)
# Find a String exists in the String
print("world" in charString3)
# Find a String not exists in the String
print("world" not in charString3)
# Find the index of the String
print("Index of world :", charString3.find("world"))
# Trim / Strip empty spaces in Strings
print(" Hello World ".strip())
# lstrip
print(" Hello World".lstrip())
# rstrip
print("Hello World ".rstrip())
# Concat list of Strings
print(" ".join(["Hello", "World", "Welcome"]))
# Splitting Strings
print("HELLO WORLD WELCOME".split(" "))
# 'f' allows us to substitute the value of the variables and do calculations
int1 = int2 = 5
print(f"{int1} + {int2} = {int1 + int2}")
# Converting String to lower case
print("HELLO".lower())
# Converting String to upper case
print("hello".upper())
# Check string whether it is a AlphaNumeric
print("ABC 123".isalnum())
print("ABC123".isalnum())
# Check string whether it is a Alphabets
print("ABC D".isalpha())
print("ABCD".isalpha())
# Check string whether it is a Digit
print("123 4".isdigit())
print("1234".isdigit())
"""
"""
# Lists - Mutable pieces of Data
list1 = [1, "test", 3.14, False]
# Length of the list
print("Length :", len(list1))
# First value of the list
print("First Value :", list1[0])
# Last value of the list
print("Last Value :", list1[-1])
# Replacing index 1 value with 'TEST' string
list1[1] = "TEST"
print(list1)
# Replacing indices 1 and 2 but not 3 with values 'TEST1' and 100
list1[1:3] = ["TEST1", 100]
print(list1)
# Adding new elements from index 2 without disturbing the other values
list1[2:2] = ["TEST123", 3.143]
print(list1)
# Adding elements using insert at index 0 without disturbing the other values
list1.insert(0, "One")
print(list1)
# Creating a New list by adding two lists
list2 = list1 + [1, 2, 3, "TEST456"]
print(list2)
# Removing an element from last
print(list2.pop())
# Removing an element with an index value is 0
print(list2.pop(0))
# Removing an element with name
print(list2.remove("TEST123"))
print(list2)
# Multi dimensional list
list3 = [[1, 2], [3, 4], [5, 6]]
print(list3[0])
print(list3[1])
print(list3[2])
print(list3[0][0])
print(list3[0][1])
print(list3[1][0])
print(list3[1][1])
print(list3[2][0])
print(list3[2][1])
list4 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Find a value exists in the list
print("5 Exists :", 5 in list4)
# Value not exists in the list
print("15 Not Exists :", 15 not in list4)
# First value
print("First Value :", list4[0])
# Second value
print("Last Value :", list4[-1])
# Values from index 0 to 2 but not including 3
print("Last Value :", list4[0:3])
# Printing Every other value in the list
print("Every other value :", list4[0:-1:2])
# Reversing the list
print("Reverse List :", list4[::-1])
# Minimum value from the list
print("Minimum Value :", min(list4))
# Maximum value from the list
print("Maximum Value :", max(list4))
"""
"""
# Loops
# while loop
# Print number from 1 to 5
w1 = 1
while w1 < 5:
print(w1)
w1 += 1
# Print only even number from 1 to 10
w2 = 1
while w2 <= 10:
if w2 % 2 == 0:
print(w2)
w2 += 1
# Print only even number from 1 to 8 - using break and continue
w3 = 1
while w3 <= 10:
if w3 % 2 == 0:
print(w3)
elif w3 == 8:
break
else:
w3 += 1
continue
w3 += 1
# Iterating through the list
wList1 = [1, 2, 3, 4, 5, 6]
# Destructive approach
while len(wList1):
print(wList1.pop(0))
# Non Destructive approach
wList2 = [1, 2, 3, 4, 5, 6]
index = 0
listLength = len(wList2)
while index < listLength:
print(wList2[index])
index += 1
"""
"""
# For Loop
# Iterating through range of numbers
for x in range(1, 5):
print(x, end="")
print()
fList1 = [1, "TEST", 100, True]
# Iterating through a List
for x in fList1:
print(x, " ", end="")
print()
# Iterators
iList = [1, 2, 3, 4, 5, 6]
iter1 = iter(iList)
print(next(iter1))
print(next(iter1))
print(next(iter1))
"""
"""
# Range Function
# Creating a list of numbers using range function
rList1 = list(range(0, 5))
print(rList1)
# Creating a list of numbers using range function with interval of 2 numbers
rList2 = list(range(0, 10, 2))
print(rList2)
# Iterating through multi dimensional array / list
rList3 = [[1, 2, 3], ['A', 'B', 'C'], ['a', 'b', 'c']]
for x in range(0, 3):
for y in range(0, 3):
print(rList3[x][y])
"""
"""
# Tuples - Immutable collection of data
t1 = (1, "Test", 3.143)
# Length of the Tuple
print("Length :", len(t1))
# First value
print("First value :", t1[0])
# Last Value
print("Last Value :", t1[-1])
# Values from 0 to 1 but not 2
print("Values from 0 to 1 but not 2 :", t1[0:2])
# Every other value
print("Every other value :", t1[0:-1:2])
"""
"""
# Dictionaries are the list of Key Value pairs - Duplicate keys are not allowed
# Creating a Dictionary
students1 = {
"1": "Student1",
"2": "Student2",
"3": "Student3"
}
print(students1)
students2 = dict([
("1", "Student1"),
("2", "Student2"),
("3", "Student3")
])
print(students2)
# Length of the Dictionary
print(len(students1))
# Getting a value of the Key
print(students1["2"])
# Adding or Changing the value of the Key
students1["3"] = "Student333"
students1["4"] = "Student4"
print(students1)
# Converting Dictionary to List of Key Value tuples
print(list(students1.items()))
# Get the list of keys from the Dictionary
print("Keys :", list(students1.keys()))
# Get the list of values from the Dictionary
print("Values :", list(students1.values()))
# Deleting a Key from Dictionary
del students1["2"]
print(students1)
students1.pop("4")
print(students1)
# Checking whether a key exists or not
print("2" in students1)
print("2" in students2)
# Iterating a Dictionary using for loop
# Iterates through all the keys
for x in students2:
print(x)
# Iterates through all the Values
for x in students2.values():
print(x)
# Printing the dictionary value automatically
dict1 = {"id": "1", "name": "TEST"}
print("%(id)s Name is %(name)s" % dict1)
dict2 = {"name": "NAME", "price": 10.053}
print("%(name)s price is RS. %(price).2f" % dict2)
"""
# Sets - An unordered list only have the Unique values
# Creating a Set
set1 = set([1, 2, "TEST"])
set2 = {1, 4, "TEST"}
print(set1)
print(len(set1))
# Adding two sets - Only distinct values
set3 = set1 | set2
print(set3)
# Adding an element to the set
set3.add(5.14)
print(set3)
# Remove or discard an element from the set
|
030b1278003f9f627aba06031631e167af7f33e8 | smriti-ranjan/PythonBootcamp_byFloxus | /EvenOddUsingBitwise.py | 236 | 4.40625 | 4 | #Floxus Python Bootcamp : Assignment - 1
#1. Write a program to check a number is even or odd using bitwise operator?
number = int(input("Enter a number:"))
if number ^ 1 == number + 1:
print('Even')
else:
print('Odd')
|
bcc000176091070d278e3356f25bbc0a1dd04a06 | gurmeetkhehra/python-practice | /list is empty or not.py | 163 | 4.375 | 4 | # 5. Write a Python program to check a list is empty or not.
emptylist = []
print (emptylist)
emptylist =[]
if not emptylist:
print("List is not emptylist.") |
7fdce4352c1a2280eae620d0ba23aaf69eb4656d | mathiasarens/python-test | /BinaryTreeZigzagLevelOrderTraversal.py | 2,124 | 4.125 | 4 | import queue
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype
"""
nodes_odd = queue.Queue()
nodes_even = queue.Queue()
if root:
nodes_even.put(root)
result = []
while not nodes_even.empty() or not nodes_odd.empty():
result_even = []
while not nodes_even.empty():
node = nodes_even.get()
result_even.append(node)
if result_even:
result.append(result_even)
for node in reversed(result_even):
if node.right is not None:
nodes_odd.put(node.right)
if node.left is not None:
nodes_odd.put(node.left)
print("result_even:", list(map(lambda n: n.val, result_even)))
result_odd = []
while not nodes_odd.empty():
node = nodes_odd.get()
result_odd.append(node)
if result_odd:
result.append(result_odd)
for node in reversed(result_odd):
if node.left is not None:
nodes_even.put(node.left)
if node.right is not None:
nodes_even.put(node.right)
print("result_odd:", list(map(lambda n: n.val, result_odd)))
return list(map(lambda outer: list(map(lambda inner: inner.val, outer)), result))
solution = Solution()
root = TreeNode(3)
node1 = TreeNode(9)
node2 = TreeNode(20)
node3 = TreeNode(15)
node4 = TreeNode(7)
node5 = TreeNode(4)
node6 = TreeNode(8)
node7 = TreeNode(6)
node8 = TreeNode(8)
root.left = node1
root.right = node2
node2.left = node3
node2.right = node4
node1.left = node5
node1.right = node6
node5.right = node7
node6.left = node8
result = solution.zigzagLevelOrder(root)
print(result) |
afc1e3ff126c58967bf4306fdfcd8c38bcde97bf | python15/homework | /3/shijiangnan/Three_week_operation.py | 2,824 | 3.65625 | 4 | '''
ๅฐ้ฟๆไผฏๆฐๅญ่กจ็คบ็ไธไธฒๆดๆฐ(ๅฐไบ1ไธ)่ฝฌๆขๆๆ ๅ็ไธญๆ่ดงๅธ่กจ่พพๅผ๏ผๅไฝไธบๅ
:ๆฏๅฆโ1234โ่ฝฌๅไธบ"ๅฃนไป่ดฐไฝฐๅๆพ่ๅ
",โ1001โ่ฝฌๅๆไธบ"ๅฃนไป้ถๅฃนๅ
",ๆฐๅญ็ไธญๆๅฏนๅบ๏ผ้ถ", "ๅฃน", "่ดฐ", "ๅ", "่", "ไผ", "้", "ๆ", "ๆ", "็","ๆพ", "ไฝฐ", "ไป", "ไธ".
'''
num_dir={"0":"้ถ","1":"ๅฃน","2":"่ดฐ","3":"ๅ","4":"่","5":"ไผ","6":"้","7":"ๆ","8":"ๆ","9":"็"}
unit={"0":"ๅ
","1":"ๆพ","2":"ไฝฐ","3":"ไป","4":"ไธ"}
def inputshuzi():
while True:
num=''
num=input("่ฏท่พๅ
ฅๆฐๅญ๏ผ").lstrip('0')
if num.isdigit():
if len(num) <= 5:
szlist=list(str(num))
count=0
libiao=[]
for i in reversed(szlist):
a=num_dir[i] + unit[str(count)]
libiao.append(a)
count+=1
#count=str(count)
libiao.reverse()
print(libiao)
print(''.join(libiao))
break
else:
print("input need less 6 digits")
else:
print("please input digit")
inputshuzi()
# ็จ1001 ่ฟไธชๆฐๅญๆต่ฏไฝ ็ไปฃ็ ๏ผ็็ไผๆไปไน้ฎ้ข
#ๅฐ้ฟๆไผฏๆฐๅญ่กจ็คบ็ไธไธฒๆดๆฐ(ๅฐไบ1ไธ)่ฝฌๆขๆๆ ๅ็ไธญๆ่ดงๅธ่กจ่พพๅผ๏ผๅไฝไธบๅ
:ๆฏๅฆโ1234โ่ฝฌๅไธบ"ๅฃนไป่ดฐไฝฐๅๆพ่ๅ
",โ1001โ่ฝฌๅๆไธบ"ๅฃนไป้ถๅฃนๅ
",ๆฐๅญ็ไธญๆๅฏนๅบ๏ผ้ถ", "ๅฃน", "่ดฐ", "ๅ", "่", "ไผ", "้", "ๆ", "ๆ", "็","ๆพ", "ไฝฐ", "ไป", "ไธ".
'''
num_dir={"0":"้ถ","1":"ๅฃน","2":"่ดฐ","3":"ๅ","4":"่","5":"ไผ","6":"้","7":"ๆ","8":"ๆ","9":"็"}
unit={"0":"ๅ
","1":"ๆพ","2":"ไฝฐ","3":"ไป","4":"ไธ"}
def inputshuzi():
while True:
num=''
num=input("่ฏท่พๅ
ฅๆฐๅญ๏ผ").lstrip('0')
if num.isdigit():
if len(num) <= 5:
szlist=list(str(num))
count=0
paic=0
libiao=[]
fxl=list(reversed(szlist))
for i in fxl:
if i == "0":
a="้ถ"
else:
a=num_dir[i] + unit[str(count)]
#count+=1
#continue
#a=num_dir[i] + unit[str(count)]
libiao.append(a)
count+=1
#count=str(count)
libiao.reverse()
libiao2=list(set(libiao))
libiao2.sort(key=libiao.index)
print(libiao2)
print(''.join(libiao2))
break
else:
print("input need less 6 digits")
else:
print("please input digit")
inputshuzi()
|
23a36e266e69b03b008b367ff6efa3caa18cea0c | Aeternix1/Python-Crash-Course | /Chapter_8/modules.py | 1,053 | 3.828125 | 4 | #You can store all of your functions in a separate file called a module
#Then you can import the module into your main program
#Import a module you make a file which contains all of your functions
#In the file that you use the functions
#import pizza (should be at the top of the file)
#To call the function you need to do this
#pizza.make_pizza(16, 'pepperoni')
#You can also import specific functions
#from module_name import function_name
#from module_name import function_0, function_1, etc
#then just use the imported function
#You can use an alias for a function that you import
#from pizza import make_pizza as mp
#mp(16, 'pepperoni')
#from module_name import function_name as fn
#You can also provide an alias for a module name
#import pizza as p
#p.make_pizza(16,'pepperoni')
#you can import all of the functions using *
#from pizza import *
#This is not the best approach as it often leads to isssues as functions
#From one module interfere with functions from another
#It is best to take the functions you need from the module
|
415d473399dbe80d9f4729477fcb5ed5b9cffb03 | ygidtu/pysashimi | /src/BamInfo.py | 2,564 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
u"""
Created by ygidtu@gmail.com at 2019.12.06
"""
from typing import Dict, List, Optional
def set_barcodes(barcodes: Optional[List[str]]) -> Dict:
u"""
separate barcodes by its first character to reduce set size
:params barcodes: list or set of barcodes
"""
res = {}
if barcodes is not None:
for b in barcodes:
if b:
f = b[:min(3, len(b))]
if f not in res.keys():
res[f] = set()
res[f].add(b)
return res
class BamInfo(object):
def __init__(self, alias, title, label, path, color, barcodes=None, kind: str = "bam"):
self.alias = alias
self.title = title
self.label = label
self.path = [path]
self.color = color
self.barcodes = set_barcodes(barcodes)
self.show_mean = False
self.type = kind
def has_barcode(self, barcode: str) -> bool:
u"""
check whether contains barcodes
:param barcode: barcode string
"""
if barcode:
f = barcode[:min(3, len(barcode))]
temp = self.barcodes.get(f, set())
return barcode in temp
return False
def empty_barcode(self) -> bool:
u"""
check whether this bam do not contain any barcodes
"""
count = 0
for i in self.barcodes.values():
count += len(i)
if count > 0:
return False
return True
def __hash__(self):
return hash(self.alias)
def __str__(self) -> str:
temp = []
for x in [self.alias, self.title, self.label, self.path, self.color]:
if x is None or x == "":
x = "None"
temp.append(str(x))
return "\t".join(temp)
def __eq__(self, other) -> bool:
return self.__hash__() == other.__hash__()
def to_csv(self) -> str:
temp = []
for x in [self.alias, self.title, self.label, self.path, self.color]:
if x is None or x == "":
x = "None"
if isinstance(x, list):
x = ";".join(x)
temp.append(str(x))
return ",".join(temp)
def __add__(self, other):
self.path += other.path
for i, j in other.barcodes.items():
if i not in self.barcodes.keys():
self.barcodes[i] = j
else:
self.barcodes[i] |= j
return self
if __name__ == '__main__':
pass
|
10a1c5fe2082916767393ed5d2a86a9552f3d639 | wajahatali987/git-assiment | /Pandas assigment part 1(Cleaning Us-Census Data) by wajahat ali.py | 4,023 | 3.640625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# importing libarary
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
import re
# In[17]:
# loading data by using glob & loop & concatenation all csv files
files = glob("states*")
us_census = pd.concat((pd.read_csv(file) for file in files ),ignore_index=True)
del us_census["Unnamed: 0"]
us_census.head()
# In[3]:
# look .dtypes and .columns
d_types=us_census.dtypes
print("Data types of us_census : \n",d_types)
print('___________________________________')
col= us_census.columns
print("Column of us_census : \n",col)
# In[4]:
# task 4 : look at the Data head Frame dtypes
#so that you can understand why some of these dtypes are objects
#instead of integers or floats.
us_census.head(2).dtypes
# In[5]:
# Use regex to turn the Income column into a format
# that is ready for conversion into a numerical type
us_census["Income"]=us_census["Income"].replace("\$"," ",regex=True)
us_census['Income'] = us_census['Income'].astype("float")
print("After conversion the Data type of income columns is : ",us_census['Income'].dtypes)
# In[6]:
#Look at the GenderPop column
#going to separate this into two columns, the Men column, and the Women column.
us_census['GenderPop'][0]
# In[7]:
# Split the column into those two new columns
#using str.split and separating out columns in to male and female.
# Convert both of the columns into numerical datatypes.
split_gender = us_census['GenderPop'].str.split('_', expand=True)
us_census["female"]=split_gender[1].str.extract('(\d+)',expand=True)
us_census["female"]=pd.to_numeric(us_census["female"])
us_census["Male"]=split_gender[0].str.extract('(\d+)',expand=True)
us_census["Male"]=pd.to_numeric(us_census["Male"])
# In[8]:
us_census.dtypes
# In[9]:
# Use matplotlib to make a scatterplot!
x=us_census["Income"]
y=us_census["female"]
plt.scatter(x,y)
plt.xlabel("Income")
plt.ylabel("female")
plt.show()
# In[10]:
#Did you get an error? These monstrous csv files probably have nan values in them!
#Print out your column with the number of women per state to see.
female_na_values = us_census["female"][us_census["female"].isnull()]
print(female_na_values)
# In[11]:
# We can fill in those nans by using pandasโ .fillna() function.
#You have the TotalPop per state, and you have the Men per state.
#As an estimate for the nan values in the Women column,
#you could use the TotalPop of that state minus the Men for that state.
total_pop=us_census["TotalPop"]-us_census["Male"]
us_census['female']=us_census['female'].fillna(value= total_pop)
# In[12]:
# We forgot to check for duplicates! Use .duplicated() on your census DataFrame to see if we have duplicate rows in there.
# Drop those duplicates using the .drop_duplicates() function.
duplicated_row = us_census[us_census.duplicated()]
us_census.drop_duplicates(keep='first',inplace=True)
# In[13]:
# Make the scatterplot again. Now, it should be perfect!
# Your job is secure, for now.
plt.scatter(x,y)
plt.xlabel("Income")
plt.ylabel("female")
plt.show()
# In[14]:
us_census.dtypes
# In[15]:
# Try to make a histogram for each one!
# You will have to get the columns into numerical format,
# and those percentage signs will have to go.
#Donโt forget to fill the nan values with something that makes sense!
#You probably dropped the duplicate rows when making your last graph,
#but it couldnโt hurt to check for duplicates again.
# In[16]:
us_census = us_census.replace('%*','',regex=True)
us_census[["Hispanic","White","Black","Native","Asian","Pacific"]] =us_census[["Hispanic","White","Black","Native","Asian","Pacific"]].apply(pd.to_numeric)
us_census[["Hispanic","White","Black","Native","Asian","Pacific"]].fillna(0)
histogram_display =us_census[["Hispanic","White","Black","Native","Asian","Pacific"]].hist(rwidth=0.87)
us_census[["Hispanic","White","Black","Native","Asian","Pacific"]].apply(lambda x :x.drop_duplicates(keep=False,inplace=True))
|
3c8451e3733309d614ced4d239cbff65d518905d | rioshen/deliberate-practice | /code-kata/simple_lists/single_list_test.py | 1,128 | 3.671875 | 4 | import unittest
from single_list import SingleList
class ListTest(unittest.TestCase):
def test_single_one(self):
lst = SingleList()
self.assertEqual(None, lst.find("fred"))
lst.add("fred")
self.assertEqual("fred", lst.find("fred").value)
self.assertEqual(None, lst.find("wilma"))
lst.add("wilma")
self.assertEqual("wilma", lst.find("wilma").value)
self.assertEqual(["fred", "wilma"], lst.values())
def test_single_two(self):
lst = SingleList()
lst.add("fred")
lst.add("wilma")
lst.add("betty")
lst.add("barney")
self.assertEqual(["fred", "wilma", "betty", "barney"], lst.values())
lst.delete(lst.find("wilma"))
self.assertEqual(["fred", "betty", "barney"], lst.values())
lst.delete(lst.find("barney"))
self.assertEqual(["fred", "betty"], lst.values())
lst.delete(lst.find("fred"))
self.assertEqual(["betty"], lst.values())
lst.delete(lst.find("betty"))
self.assertEqual([], lst.values())
if __name__ == '__main__':
unittest.main()
|
1777ead4ef6176ca94a6f7d64cef58e039112f91 | BhargaviSiddipeta/Python | /ICP/icp_3/icp3/websc.py | 1,091 | 3.890625 | 4 | import requests
import urllib.request
import os
from bs4 import BeautifulSoup
#set the wiki page to the link
html_page = requests.get("https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India")
# open the link it for parsing
soup = BeautifulSoup(html_page.text, "html.parser")
# print title of the page
print(soup.title.string)
# print all the href tags in anchor tag
for i in soup.find_all('a'):
print(i.get('href'))
th_list = [ ]
titles = []
#method find all the data within a particular tag which is passed to the find_all( ) method. For example see the following line of code.
print(html.find_all('script'))
#Extract information within all table
for rows in soup.find_all('table', class_='wikitable sortable plainrowheaders') :
rows_1 = rows.find_all('tr')
for row in rows_1:
td = row.find_all("td")
for i in td:
print(i.text)
th = row.find("th")
if th.text not in th_list:
th_list.append(th.text)
print("State or Union Territory: ", th.text)
print(titles) |
460103378fd3bc3a56ff679f273f7cf5f2737571 | iamsaib197/Lane_Car_Detection | /lane_car_detection.py | 927 | 3.5 | 4 | import cv2
from cv2 import CascadeClassifier
import numpy
import pandas as pd
cap = cv2.VideoCapture('C:/Users/HP/PycharmProjects/lane_Car_detection/yellow.mp4')
# Trained XML classifiers describes some features of some object we want to detect
car_cascade = cv2.CascadeClassifier('cars.xml')
# loop runs if capturing has been initialized.
while True:
# reads frames from a video
ret, frames = cap.read()
# convert to gray scale of each frames
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectMultiScale(gray, 1.3, 1)
#for drawing rectangles over the cars
for (x ,y ,w ,h) in cars:
cv2.rectangle(frames ,(x ,y) ,( x +w , y +h) ,(0 ,0 ,255) ,2)
# Display frames in a window
cv2.imshow('video2', frames)
#If we wish to stop the detection mode
if cv2.waitKey(33) & 0xFF==ord('q'):
break
cv2.destroyAllWindows() |
e2401614cbc981128a0cbb1c9ebced34e1fd8b22 | Kordisgames/Translater | /one.py | 989 | 4.125 | 4 | print('ะะพัะฐะณะพะฒัะน ะบะพะฝะฒะตััะตั ะธะท ะดะตัััะธัะฝะพะน ัะธััะตะผั');
num = int(input("ะะฒะตะดะธัะต ัะธัะปะพ ะฒ ะดะตัััะธัะธัะฝะพะน ัะธััะตะผะต: "));
# setting
delimiter = 3; # ะพัะฝะพะฒะฐะฝะธะต ัะธััะตะผั ะธััะธัะปะตะฝะธั 1 - 9
#
firstNum = num; # ะกะพะทัะฐะฝัะตะผ ะฟะตัะฒะธัะฝะพะต ะทะฝะฐัะตะฝะธะต ะดะปั
pos1, pos2, answer = 0, 0, '';
# ะะฐะฟััะบะฐะตะผ ัะธะบะป ะฟัะตะพะฑัะฐะทะพะฒะฐะฝะธั ะฒ 3-ั ัะธััะตะผั
while True:
# ะกัะฐะฝะดะฐััะฝัะต ะฟัะตะพะฑัะฐะทะพะฒะฐะฝะธั ะธ ะพะฟะตัะฐัะพัั
pos1 = num // delimiter; pos2 = num % delimiter;
# ะัะฒะพะด ะบะฐะถะดะพะณะพ ะดะตะนััะฒะธั
print(f"{num} // {delimiter} = {pos1} | {num} % {delimiter} = {pos2}");
num = pos1; answer += str(pos2);
# ะัะปะธ ะฑะพะปััะต ะดะตะปะธัั ะฝะตัะตะณะพ - ะพััะฐะฝะฐะฒะปะธะฒะฐะตะผ
if(pos1 == 0):
break;
# ะะตัะตะฒะพัะฐัะธะฒะฐะตะผ ัััะพะบั
answer = answer[::-1];
# ะัะฒะพะดะธะผ ะพัะฒะตั
print(f"{firstNum} = {answer}"); |
e4ed1ae71a4e46ef187d6106431ae94f60cff96f | Aasthaengg/IBMdataset | /Python_codes/p02865/s291039913.py | 106 | 3.640625 | 4 | import math
n = int(input())
if n%2==0:
print(round(((n-2)/2)))
else:
print(round(((n+1)/2)-1)) |
0a2dc71aa14bc2a1d7a341b300ebbbaabbe0c381 | Pin2-jack/Encryption-Decryption | /Encryption.py | 9,073 | 4.53125 | 5 | """
Encrypt Decrypt
Encrypt is a function that takes a string, -message-, as an attribute and will return None.
Encrypt will:
Ask the user to enter a file name. This file should contain pairs of characters and numbers.
Match the characters from -message- to the numbers given in the file.
Save the numbers to a text file.
Decrypt is a function that takes no arguments and will return a string.
Ask the user for two inputs, the name of a file containing the cipher and the name
of a file containing an encrypted message.
Match the characters given by the cipher file to the numbers given in the message file.
return the decyphered string.
Note:
A cypher.txt file is provided.
you can use the following string to test your code.
m = "The Kalevala is a 19th-century compilation of poetry written by Elias Lรถnnrot it contains Finnish oral folklore and mythology"
"""
# Function to Encrypt the code according to given Cypher file, the Function will read cypher file and replace the
# single number(containing 1 digit) by adding '0' on left side with digit, number with double digit will remain same
# and for characters not in cypher file, it adds '*' on right side with that character , so its easy to Decrypt
def Encrypt(str_msg):
while True: # loop for correct file name and Extension
File_name = input("Enter a Name of file containing Cypher code : ")
if File_name.endswith(('.txt')):
break
print("Error!! Enter file Name with correct Extention: ")
handler = open(File_name, 'r') # Reads a file that is needed to Encryp
Final_string = "" # Empty Final String
Final_dict = {}
for line in handler: # loop for reading lines in file(file that is needed to Encrypt)
if len(line[2:].rstrip("\n")) < 2: # if the number in cypher file is 1 digit then it adds string('0') in front of that digit
num = "0" + line[2:].rstrip("\n")
else: # if number is 2 digit then it will add to number
num = line[2:].rstrip("\n")
Final_dict[line[0]] = num
for char in str_msg: # loop for each characters in the string argument
Status = 0
for key, value in Final_dict.items(): # loop for keys and values of dictionary made of cypher code
if char == key: # condition (if character matches the key (i.e letter in dictionary of cypher file)
Final_string += value # it add the value of dictionary (which is with key of dictionary) instead of character
Status = 1
break
if char == " ": # condition for space in string message to encrypt
Final_string += " " # it adds 2 spaces which helps id Decrypting code(even numbers)
Status = 1
if Status == 0: # condition for characters which are not included in cypher file
#Final_string += char + "0"
Final_string += char + "*" # it adds * after a character which helps in Decrypting (makes even length(i.e. 2))
handler.close()
Encrypted_code = open('Encrypted_data.txt', 'w') # Makes new file for the Encrypted data
Encrypted_code.write(Final_string) # Writes a Encrypted code in File
Encrypted_code.close()
print("\nA New File Named Encrypted_data.txt containing Encrypted code is created in your Device\n")
m = "The Kalevala is a 19th-century compilation of poetry written by Elias Lรถnnrot it contains Finnish oral folklore and mythology"
Encrypt(m)
# Function to Decrypt the Encrypted code
def Decrypt():
while True: #loop for correct file name and Extension
Cypher_file_name = input("Enter a Cypher File Name: ")
if Cypher_file_name.endswith(('.txt')):
break
print("Error!! Enter file name with correct Extention: ")
cypher_handler = open(Cypher_file_name, 'r') # reads file with cypher code
while True: # loop for correct file name and Extension
Encrypt_file_name = input("Enter a Name of File Containing Encrypted Message: ")
if Encrypt_file_name.endswith(('.txt')):
break
print("Error!! Enter file name with correct Extention: ")
Encrypted_handler = open(Encrypt_file_name, 'r') # reads file that is needed to Decrypt
string_list=[]
n = 0
for digits in Encrypted_handler: # loop for digits in Encrypted
for n in range(0, len(digits), 2):
string_list.append(digits[n:n+2])
Final_string = "" # Empty final string for Decrypted code
Final_dict = {}
for line in cypher_handler: # loop for reading lines in Cypher file
if len(line[2:].rstrip("\n")) < 2: # if number has 1 digit, it adds string '0' before number easy Decryption and as done in encryption
num = "0" + line[2:].rstrip("\n")
else: # for 2 digits in number, it adds that number in number
num = line[2:].rstrip("\n")
Final_dict[line[0]] = num
cypher_handler.close()
for item in string_list: # loop for every items in the list( contains characters of the string argument)
status = 0
for key, value in Final_dict.items(): # loop for key and values in Dinctionary ( made of cypher code)
if item == value: # condition for item(number(digits) of argument passed) and value in dictionary of cypher code
Final_string += key # it replaces with character again
status = 1
break
if item == " ": # if it contains 2 blank space, it makes 1
Final_string += " "
status = 1
if status == 0: # condition that removes '*' character
Final_string += item.rstrip("*")
#Final_string += item.lstrip("0")
print("The Decrypted (Readable)/ Decyphered code is :\n")
return Final_string # prints the Decrypted code (Readable)
print(Decrypt())
"""
Hider
Hider is a function that takes a string, -sentence- and a list of letters, -hide- as arguments.
Hider will modify the words of -sentence- by changing the letters of the words by *
if they appear in -hide-. If a word has 2 or more letters that appear in -hide-,
the whole word should be replaced with *.
Hider should work for both the upper and lowercase letters.
example = "The brown fox jumps over the lazy dog."
letterList = ["b", "d","j", "m"]
Hider(example, letterList)
#ouptput: The *rown fox ***** over the lazy *og.
"""
# Function for hiding a letter that contains particular characters in list and word that has 2 or more characters in word
def Hider(str, letter_list):
str = str.lower() # converts string into lower case
final = ""
for character in str: # loop for reading character in string and making new list
if character in letter_list :
final += '*'
else:
final += character
final = final.split() # splits word and makes list
i = 0
for word in final: # loop for reading each word in list
i += 1
count = 0
for letter in word: # loop for counting number of letters contained in letter list(letters that are replaced)
if letter == '*':
count += 1
if count >= 2: # if word contains 2 or more letters from list, it replaces whole word with '*'
final[i-1] = '*'*len(word)
print("\nThe Hidden Sentence :\n")
return " ".join(final)
example = "The brown fox Jumps over the lazy dog."
letterList = ["b", "d", "j", "m"]
print(Hider(example, letterList)) |
d4e430356e13c0140253e7562f03893efc3855bd | skyrocxp/python_study | /exercises8.py | 2,813 | 3.53125 | 4 | # LY-05-for
# ็ฎๅๅพๅฝขๆๅฐ
'''
ๆๅฐไปฅไธๅพๅฝขๅจ่พๅบไธ้ข
*
* *
* * *
* * * *
* * * * *
'''
# ๆนๆก1
for i in range(1,6):
print("* " * i)
print("------ๆ-ๆฏ-ๅ-ไธฝ-็-ๅ-ๅฒ-็บฟ-------")
# ๆนๆก2
for i in range(1,6):
# ๆๅฐไธ่ก
# ๆฏไธ่กๆๅฐๅ ไธชๆๅท,่ท่กๅท็ธๅ
ณ
# ไธ่กๅ
ๆๅฐไธ้่ฆๆข่ก,ไธ่กๆๅฐๅฎๆฏๆข่ก
for j in range(i):
print("* ",end = "")
print()
print("------ๆ-ๆฏ-ๅ-ไธฝ-็-ๅ-ๅฒ-็บฟ-------")
'''
ๆๅฐ็ฉบๅฟไธ่งๅฝข
*
* *
* *
* *
* * * * *
'''
# ็ฌฌไธไธชๆนๆณ,็ดๆฅไฝฟ็จPrint
# ็ฌฌไบไธชๆนๆณ,ไฝฟ็จforๅพช็ฏ
for i in range(5):
for j in range(i+1):
if i == 4:
print("* ",end = "")
elif j == 0 or j == i:
print("* ",end = "")
else:
print(" ",end = "")
print()
print("------ๆ-ๆฏ-ๅ-ไธฝ-็-ๅ-ๅฒ-็บฟ-------")
'''
ๆๅฐไปฅไธๅพๅฝขๅจ่พๅบไธ้ข
* * * * *
* * * *
* * *
* *
*
'''
# i-forๆงๅถ่กๅท
# j-forๆงๅถๅๅท
for i in range(5):
for j in range(5-i):
print("* ",end="")
print()
print("------ๆ-ๆฏ-ๅ-ไธฝ-็-ๅ-ๅฒ-็บฟ-------")
# i-forๆงๅถ่กๅท
# j-forๆงๅถๅๅท
for i in range(5,0,-1):
for j in range(i,0,-1):
print("* ",end="")
print()
print("------ๆ-ๆฏ-ๅ-ไธฝ-็-ๅ-ๅฒ-็บฟ-------")
'''
ๆๅฐ็ฉบไธ่ง
* * * * *
* *
* *
* *
*
'''
for i in range(5):
for j in range(5-i):
if i == 0:
print("* ",end = "")
elif j == 0 or j == 5-i-1:
print("* ",end = "")
else:
print(" ",end = "")
print()
print("------ๆ-ๆฏ-ๅ-ไธฝ-็-ๅ-ๅฒ-็บฟ-------")
'''
ๆๅฐไธ่งๅฝข,ๆญฃไธ่งๅฝข
*
* *
* * *
* * * *
* * * * *
'''
for i in range(1,6):
# ๆปไฝๆ่ทฏๆฏ,ๅ
ๆๅฐไธ่ก็ฉบๆ ผ,ไปฃ่กจๆๆๅ็็ฉบๆ ผ
# ๅไธๆข่ก,ๆๅฐๆๅท
for j in range(6-i):
print(" ",end = "")
for k in range(i):
print("* ",end = "")
print()
print("------ๆ-ๆฏ-ๅ-ไธฝ-็-ๅ-ๅฒ-็บฟ-------")
'''
ๆๅฐ็ฉบๆญฃไธ่งๅฝข
*
* *
* *
* *
* * * * *
'''
for i in range(1,6):
# ๅ
ๆๅฐ็ฌฌไธ่กๅๆๅไธ่ก,็ฌฌไธ่กไธบ(6-i)ไธช็ฉบๆ ผ+"*"
# ๆๅไธ่กไธบ5ไธช("*"+็ฉบๆ ผ)
if i == 1:
print(" "*(6-i)+"*")
elif i == 5:
print(" "+"* "* 5)
# ๆๅฐไธญ้ด้จๅ,ไพ็ถๅ
ๆๅฐ็ฉบๆ ผ
else:
for j in range(4-i):
print(" ", end = "")
# ็ฉบๆ ผๅ้ข็ฌฌไธไธช็ฌฆๅทๆๅฐ"*"+็ฉบๆ ผ
# ็ฌฌ่กๅทไธชๅญ็ฌฆๆๅฐ"*"+็ฉบๆ ผ
for k in range(i+1):
if k == 1 or k == i:
print("* ",end = "")
# ๅ
ถไปๅฐๆน็จๅ็ฉบๆ ผ่กฅ้ฝ
else:
print(" ",end = "")
print()
print("------ๆ-ๆฏ-ๅ-ไธฝ-็-ๅ-ๅฒ-็บฟ-------")
|
71e4ba5af603b8091a72628e5ddda7e75638b4ea | retr0rafay/100DaysOfPython | /Day 23 - Turtle Crossing/car_manager.py | 889 | 3.75 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager(Turtle):
def __init__(self):
self.all_cars = list()
self.car_speed = STARTING_MOVE_DISTANCE
def create_car(self):
chance = random.randint(1, 6)
if chance == 1:
car = Turtle('square')
car.penup()
car.shapesize(stretch_wid=2, stretch_len=1)
car.tiltangle(90)
car.setheading(0)
car.color(random.choice(COLORS))
random_y = random.randint(-250, 250)
car.setposition(300, random_y)
self.all_cars.append(car)
def move_car(self):
for car in self.all_cars:
car.back(self.car_speed)
def level_up_car(self):
self.car_speed += MOVE_INCREMENT
|
9da9a91bb92939dec3da67925279afbf2e95924b | victoriacorreaalves/Curso-Introducao-Ciencia-da-Computacao-com-Python-Parte-1-USP | /semana 1/dezenas.py | 193 | 4.03125 | 4 | # pede um nรบmero para o usuรกrio e retorna o nรบmero da dezena desse nรบmero
n= input("Digite um nรบmero inteiro:")
num= int(n)
d= (num // 10) % 10
print ("O dรญgito das dezenas รฉ", d) |
aa9b7bd421235d55eb0b9f8d3dc5a1250423293d | farazlfc/CP | /Diamond_aka_cherry_pickup.py | 3,591 | 3.859375 | 4 | '''Task Description:
Diamond Mine is your new favorite game . Its map is represented as a square matrix. The board is filled with cells, and each cell will have an initial value as follows:
โข A value โฅ 0 represents a path.
โข A value of 1 represents a diamond.
โข A value of โ1 represents an obstruction.
The basic rules for playing Diamond Mine are as follows: โข The player starts at (0, 0) and moves to (nโ1, nโ1), by moving right (โ) or down (โ) through valid path cells. โข After reaching (nโ1, nโ1), the player must travel back to (0, 0)by moving left (โ) or up (โ) through valid path cells. โข When passing through a path cell containing a diamond, the diamond is picked up. Once picked up, the cell becomes an empty path cell. โข If there is no valid path between (0, 0) and (nโ1, nโ1), then no diamonds can be collected. โข The ultimate goal is to collect as many diamonds as you can.
For example, consider the following grid:
[ [0 1]
[-1 0] ]
Start at the top left corner. Move right one, collecting a diamond. Move down one to the goal. Cell (1, 0) is blocked, so we can only return on the path we took initially. All paths have been explored, and 1 diamond was collected.
Function Description Complete the function collectMax. It must return an integer denoting the maximum number of diamonds you can collect given the current map.
collectMax has the following parameter(s):
mat[mat[0],...mat[n-1]]: an array of integers describing the game grid map Constraints
โข 1 โค n โค 100
โขโ1 โค mat[i][j] โค 1
Case 0:
Sample Input :
[ [0 1 -1]
[1 0 -1]
[1 1 1] ]
Output: 5
Explanation :You can collect a maximum of 5 diamonds by taking the following path: (0, 0) โ (0,1) โ (1,1) โ (2, 1) โ (2, 2) โ (2, 1) โ (2, 0) โ (1, 0) โ (0, 0).
Case 1:
Sample Input:
[ [0 1 1]
[1 0 1]
[1 1 1]]
Output: 7
You can collect all 7 diamonds by following the
path:
0 โ 1 โ 1
โ โ
1 0 1
โ โ
1 โ 1 โ 1
Case 2:
Sample :
[[0 1 1]
[1 0 -1]
[1 1 -1]]
Output: 0
Explanation :The cell at (2, 2) is blocked, so you cannot collect any diamonds.'''
arr = [[1,0,0],
[1,-1,1],
[1,1,1]]
n = 3
dp = [[[[-1 for _ in range(n)]for _ in range(n)]for _ in range(n)]for _ in range(n)]
def recurse(i,j,l,r):
if i<0 or l<0 or i>=n or l>=n or j<0 or r<0 or j>=n or r>=n:
return -1*float("inf") #cliff se gir gaye
if arr[i][j] == -1 or arr[l][r] == -1:
return -1*float("inf") #galat aagaye
if dp[i][j][l][r] != -1:
return dp[i][j][l][r]
ans = -1*float("inf")
if i == n-1 and j == n-1 and l==n-1 and r ==n-1:
return int(arr[n-1][n-1]==1) #exclusive conditiom
if i == n-1 and j == n-1:
ans = int(arr[l][r] == 1) + max(recurse(i,j,l+1,r),recurse(i,j,l,r+1))
dp[i][j][l][r] = ans;
return ans;
if l == n-1 and r == n-1:
ans = int(arr[i][j] == 1) + max(recurse(i+1,j,l,r),recurse(i,j+1,l,r))
dp[i][j][l][r] = ans;
return ans;
if i == l and j == r:
val = int(arr[i][j] == 1)
ans = max(ans,val + recurse(i+1,j,l+1,r))
ans = max(ans,val + recurse(i+1,j,l,r+1))
ans = max(ans,val + recurse(i,j+1,l+1,r))
ans = max(ans,val + recurse(i,j+1,l,r+1))
dp[i][j][l][r] = ans;
return ans;
#if everything different
else:
val_1 = int(arr[i][j] == 1)
val_2 = int(arr[l][r] == 1)
val = val_1 + val_2
ans = max(ans,val + recurse(i+1,j,l+1,r))
ans = max(ans,val + recurse(i+1,j,l,r+1))
ans = max(ans,val + recurse(i,j+1,l+1,r))
ans = max(ans,val + recurse(i,j+1,l,r+1))
dp[i][j][l][r] = ans;
return ans;
val = (recurse(0,0,0,0))
print(max(val,0))
|
30887f3afa75ad9429defc270fd6a46e04f58fd6 | ianramzy/old-code | /Counter/counter.py | 263 | 3.921875 | 4 | num = 0
ans = input(str(num)+" Press enter or 'q' to quit...")
while True:
if ans.lower() == 'q':
break
else:
num = num + 1
if num > 5:
num = 0
ans = input(str(num)+" Press enter or 'q' to quit...")
|
46547cae5d0973f64d6895cbb6965bf4d8089043 | marcelopontes1/Estudos-Python-GUPPE | /S5/decimo_nono_programa.py | 369 | 4.375 | 4 | num1 = int(input('Insira um nรบmero: '))
if num1 % 3 == 0 or num1 % 5 == 0:
print('O nรบmero รฉ divisรญvel por 3 OU 5')
if num1 % 3 == 0 and num1 % 5 == 0:
print('O nรบmero รฉ divisรญvel por 3 E 5 ao mesmo tempo')
else:
print('O nรบmero nรฃo รฉ divisรญvel por 3 E 5 ao mesmo tempo')
else:
print('O nรบero nรฃo รฉ divisรญvel por 3 OU 5') |
c4ccaba26bbcd0f824635ff487158a6bd1621834 | oalawode/ATM_mock_project | /database.py | 3,159 | 3.625 | 4 | # create record
# update record
# read record
# delete record
# CURD
import os
import validate
user_db_path = "data/userRecord/"
def create(user_account_number, first_name, last_name, email, password, opening_balance):
# create a file
# name of file is account number .txt
# add the user details to the file
# return true
# if saving to the file fails, then delete created file
user_data = first_name + "," + last_name + "," + email + "," + password + "," + str(opening_balance)
if does_account_number_exist(user_account_number):
return False
if does_email_exist(email):
print("User already exists")
return False
completion_state = False
try:
f = open(user_db_path + str(user_account_number) + ".txt", "x")
except FileExistsError:
does_file_contain_data = read(user_db_path + str(user_account_number) + ".txt")
if not does_file_contain_data:
delete(user_account_number)
else:
f.write(str(user_data));
completion_state = True
finally:
f.close();
return completion_state
def update(user_account_number):
print("Update user record")
def read(user_account_number):
# find user record using account number
# fetch content of the file
is_valid_account_number = validate.account_number_validation(user_account_number)
try:
if is_valid_account_number:
f = open(user_db_path + str(user_account_number) + ".txt", "r")
else:
f = open(user_db_path + user_account_number, "r")
except FileNotFoundError:
print("User not found!")
except TypeError:
print("Invalid Account Number format.")
else:
return f.readline()
return False
def delete(user_account_number):
# find user record using account number
# delete the user record
# return true
print("Delete user record")
is_delete_successful = False
if os.path.exists(user_db_path + str(user_account_number) + ".txt"):
try:
os.remove(user_db_path + str(user_account_number) + ".txt")
is_delete_successful = True
except FileNotFoundError:
print("User not found")
return is_delete_successful
def find(user_account_number):
print("Find user record")
def does_email_exist(email):
all_users = os.listdir(user_db_path)
for user in all_users:
user_list = (str.split(read(user), ","))
if email in user_list:
return True
return False
def does_account_number_exist(account_number):
all_users = os.listdir(user_db_path)
for user in all_users:
if user == str(account_number) + ".txt":
return True
return False
def authenticate_user(account_number, password):
if does_account_number_exist(account_number):
user = str.split(read(account_number), ",")
if password == user[3]:
return user
return False
def current_balance(user):
current_balance = user[4]
return current_balance
def set_current_balance(user, account_balance):
user[4] = account_balance |
58447a0a14ea0f5450bf45e39596d46d8eab67ec | viniciusbds/math | /MatematicaDiscreta/relacoes/transitiva.py | 820 | 3.765625 | 4 | #-*-coding: utf-8-*-
'''
Recebe como parรขmetros um conjunto no qual a relaรงรฃo รฉ aplicada e a prรณpria relaรงรฃo.
'''
def transitiva(A, relacao):
for a in A:
for b in A:
for c in A:
if (a,b) in relacao and (b,c) in relacao and not (a,c) in relacao:
return False
return True
A = [1,2,3,4]
R1 = [(1, 1),(1, 2),(2, 1),(2, 2),(3, 4),(4, 1),(4, 4)]
R2 = [(1, 1),(1, 2),(2, 1)]
R3 = [(1, 1),(1, 2),(1, 4),(2, 1),(2, 2),(3, 3),(4, 1),(4, 4)]
R4 = [(2, 1),(3, 1),(3, 2),(4, 1),(4, 2),(4, 3)]
R5 = [(1, 1),(1, 2),(1, 3),(1, 4),(2, 2),(2, 3),(2, 4),(3, 3),(3, 4),(4, 4)]
R6 = [(3,4)]
# Testando ...
assert not transitiva(A,R1)
assert not transitiva(A,R2)
assert not transitiva(A,R3)
assert transitiva(A,R4)
assert transitiva(A,R5)
assert transitiva(A,R6)
|
b95b06eab0b89ff242d6067cb95adae5e4836877 | jcbwlkr/aoc | /2017/day08/blah.py | 645 | 3.71875 | 4 | def isAnagram(a, b):
tester = list(a)
tested = list(b)
print("Tester: ", tester)
print("Tested: ", tested)
print("testing...")
i = 0
while i < len(tester):
j = 0
while j < len(tested):
print(i,j)
if tester[i] == tested[j]:
if len(tester) == 1:
return 1
tester.pop(i)
tested.pop(j)
if isAnagram(tester, tested) == 1:
print("It's an anagram!")
return 1
else:
j += 1
i += 1
return 0
print(isAnagram("abc", "cba"))
|
06cc0d80ff286192a99fea6d499545f9cea1ba01 | jmyket/python_cc | /chapter_9/user_attr.py | 558 | 3.515625 | 4 | from chapter_9_classes import user
class Privileges:
def __init__(self, privileges = []):
self.privileges = privileges
def show_privileges(self):
print(
f"admin privileges: {self.privileges}"
)
class Admin(user.Users):
def __init__(
self, first_name = None, last_name = None, last_login = None
, age = None, sex = None
):
super().__init__(
first_name, last_name, last_login, age, sex
)
self.first_name = "admin"
self.privileges = Privileges() |
ac726c28888f7b722782d3d847a255c6efb9b6b6 | maclamont/ProgrammingTests | /PYTHON/ProjectEuler/Ex10_Lamont.py | 792 | 4.34375 | 4 | #! /Users/macl2/anaconda/bin/python -tt
'''
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
'''
import math
def IsPrime(num): # function to check if it is prime or not
rangenum = int(math.sqrt(num))
for i in range(3,rangenum+1,2): # just loop to the square root of the value. Only look at odd numbers
if num%i==0:
return 0
return 1
def main():
SumOfPrimes = 2 # in my loop I'm only looking at odd numbers, so start the counter with 2
num = 2000000
for i in range(3,num,2): # loop over the odd numbers
if IsPrime(i): # if it is prime, sum it up
SumOfPrimes += i
print 'Sum of Primes below 2000000 =', SumOfPrimes
return
if __name__ == '__main__':
main() |
1bee2f9381cc922d172ee7e65912ff8605c2be00 | BryantHuang9/NumberGuessing | /File1.py | 1,657 | 4.03125 | 4 | import random
def compare_num(num, answer, tries):
if tries > 0:
if int(num) == answer:
print("Correct. Congratulations!")
exit()
elif answer == 1:
print("Hint: It is a prime number.")
elif answer == 2:
print("Hint: It is a multiple of 2.")
elif answer == 3:
print("Hint: It is a multiple of 3.")
elif answer == 4:
print("Hint: It is a perfect square.")
elif answer == 5:
print("Hint: It is a multiple of 5.")
elif answer == 6:
print("Hint: It is a multiple of 2.")
elif answer == 7:
print("Hint: It is a prime number.")
elif answer == 8:
print("Hint: It is a multiple of 4.")
elif answer == 9:
print("Hint: It is a perfect square.")
elif answer == 10:
print("Hint: It is a multiple of 5.")
if tries == 2:
print("You have " + str(tries) + " more tries.")
if tries == 1:
print("You have " + str(tries) + " more try.")
elif tries == 0:
if int(num) == answer:
print("Correct. Congratulations!")
else:
print("Game over.")
print("The number is " + str(answer))
print("Welcome to the Number Guessing Game! You will have 3 tries to guess the right number. Good luck!")
answer = random.randint(1, 10)
# print(answer)
tries = 3
attempt = 1
while tries <= 3 and tries > 0:
tries -= 1
num = input("Attempt # " + str(attempt) + " Guess an integer between 1 and 10: ")
attempt += 1
compare_num(num, answer, tries)
|
ec6b2ceba4b412a51ce518fe7a0ca8614560b035 | dongxietest/AIDP-ython | /01Pbase/day04/2019.05.25 WAID1905/PythonBase03/exercise04.py | 1,025 | 3.96875 | 4 | # ็ปไน ๏ผ๏ผใๆๅฐๅฝๆๆฅๅ
# ่ทๅ็จๆท่พๅ
ฅ็ๆฌๆ็ฌฌไธๅคฉๆฏๆๆๅ ๏ผ5
# ่ทๅ็จๆท่พๅ
ฅ็ๆฌๆ็ๆปๅคฉๆฐ๏ผ31
# ๆๅฐๆฌๆๆฅๅใ
start = int(input("่พๅ
ฅ็ๆฌๆ็ฌฌไธๅคฉๆฏๆๆๅ ๏ผ"))
days = int(input("่พๅ
ฅ็ๆฌๆ็ๆปๅคฉๆฐ๏ผ"))
print("ไธ ไบ ไธ ๅ ไบ ๅ
ญ ๆฅ")
# ๆๅฐๅผๅง็็ฉบ็ฝๅ ไฝ
print(" " * 4 * (start -1), sep="",end="")
# ๅฝๅ้ๅ็ๅคฉๆฐ
i = 1
# ๅฝๅ้ๅๅคฉๆฐๅฏนๅบๆฏๆๆๅ
j = start
# ๅคๅฑๅพช็ฏ้ๅๆๆๅคฉๆฐ
while i <= days:
# ๅ
ๅฑๅพช็ฏๆๅฐๅจไธๅฐๅจๆฅ็ๆฐๆฎ
while j < 8:
print("%2d" % i, end=" ")
# ๅฝๅๅคฉๆฐๅ
ๅฎนๅทฒๆๅฐ๏ผๅคฉๆฐๅ ๏ผ
i = i + 1
# ๅฝๅๅคฉๆฐๅ
ๅฎนๅทฒๆๅฐ๏ผๆๆๅผๅ ๏ผ
j = j + 1
# ่ฅๅฝๅ่กๅ
็ๅคฉๆฐ่ถ
ๅบๆๅคงๅคฉๆฐๆถ๏ผๅๆญขๅพช็ฏ่พๅบ
if i > days:
break
# ๅฐๆๆๆฅไนๅ๏ผๆข่ก่พๅบ
print()
# ้็ฝฎๅฝๅ็ๆๆๆฐ๏ผไธบๆๆ๏ผ
j = 1
# ็ปๆ่พๅ
ฅ
print()
|
cef2a59889605c41dbb72ce3b648ae11875aa19b | sahdev-01/Hello-sahdev | /odd or even.py | 186 | 4.375 | 4 | # To find odd or even number entered by a user
number = int(input("Enter a number: "))
if number % 2 == 0:
print(number, "is even number.")
else:
print(number, "is odd number.")
|
d6719d43ca09f6922cc05c7f689323555719bbaf | AdamMcCarthyCompSci/Programming-1-Practicals | /Practical 5/p9p3.py | 599 | 4.25 | 4 | '''
Prompt for positive integer
if input isn't positive
print warning
else
set factorial variable to 1
create for loop where counter starts at 1 and ends at input+1
multiply factorial variable by counter
print factorial answer
'''
integerinput=int(input('Enter an integer to calculate its factorial (must be positive): '))
if integerinput<=0:
print('Integer must be greater than 0.')
else:
factorial=1
for counter in range(1,integerinput+1):
factorial*=counter
print('Factorial of',integerinput,'is',factorial)
print('Finished!') |
32e67576ade4556f8d65613c5f4aa002e5cadd3f | gauravtatke/codetinkering | /leetcode/numbercompliment.py | 1,620 | 3.78125 | 4 | #!/usr/bin/env python3
#Given a positive integer, output its complement number. The complement strategy
#is to flip the bits of its binary representation.
#Note:
#The given integer is guaranteed to fit within the range of a 32-bit signed
#integer. You could assume no leading zero bit in the integerโs binary
#representation.
def findcompliment1(num):
#function using string manupulation
#num = bin(num).lstrip('0').lstrip('b')
cnum = 0
for i, nu in enumerate([1 if ch == '0' else 0 \
for ch in reversed(bin(num)[2:])]):
cnum = cnum + nu*(2**i)
return cnum
#if we use just ~num to flip the bits, it gives wrong result because BITWISE #NOT only flips the bits. Machine interprets it as negative number stored in #2's compliment and return something unexpected. For e.g. ~2 returns -3
#to just flip the bits as required by the problem, we have to create a mask of #1 bits of length = LEFTMOST 1 bit to RIGHTMOST bit. For e.g. for 5 (101) mask #is needed of length 3 (111), for 10 (1010), mask is needed for len 4 (1111).
#once mask is created, we can either do mask Bitwise XOR num (mask ^ num) or #Bitwise NOT num Bitwise AND mask (~num & mask)
#couple of ways to create mask of required length
#1. mask = 1
#mask = 1 << (len(bin(num)-2))
#2. mask = 1
#while mask <= num:
# mask = mask << 1
#mask -= 1
#3. mask = 1
#while mask < num:
# mask = mask << 1 | 1
def findcompliment2(num):
mask = 1
while mask < num:
mask = mask << 1|1
return num ^ mask
def main():
print(findcompliment2(6))
if __name__ == '__main__':
main()
|
7f630a40c03ffa7cd35f44f7bae2bacc2aff31dc | Haruho/PythonProject | /Teach/openfile.py | 271 | 3.5 | 4 | #ๆๅผๆไปถ
#็ฌฌไบไธชๅๆฐ'w'ไปฃ่กจๆฐๅปบไธไธชๅๅญๆฏ็ฌฌไธไธชๅๆฐ็ๆไปถ๏ผๅ
ๅซๅ็ผ๏ผๅทฒ็ปๅญๅจ็ๅฐไผ่ฆ็
open('test1.txt','w')
#็ฌฌไบไธชๅๆฐ่ฟๆ'r'-ไป
่ฏปๅๆไปถ
#'r+'ๅฏนๆไปถ่ฟ่กๅ
ๅฎนๆทปๅ ๏ผ่ชๅจๆทปๅ ๅฐๆไปถๅ
ๅฎน็ๆซๅฐพ
|
b1af980db3be4bd5eeaa68893d41dce021819d9a | ff-sherpa/LearningPython | /pothole/potholes.py | 1,329 | 3.640625 | 4 | # potholes.py
# Analyze potnole data to find 10 block section with most potholes.
import csv
import operator
# create dictionary
potholes_by_block = {}
def make_block(address):
''' Rewrite an address to strip address in 1000s (10 blocks)'''
parts = address.split()
num = parts[0]
new = num[:-3] # or new = parts[0][:-3]
# for number like '5412', this makes '5XXX'
# parts[:-3] = grab everything except the last 3 characters
parts[0] = num[:-3] + 'XXX'
#print parts[0]
return ' '.join(parts)
f = open('pothole_data.csv')
for row in csv.DictReader(f):
status = row['STATUS']
if status == 'Open':
addr = row['STREET ADDRESS']
block = make_block(addr)
num = row['NUMBER OF POTHOLES FILLED ON BLOCK']
# Tabulate
# will build dictionary as follows:
# 4XXX W 56th St: num_or_potholes
if block not in potholes_by_block:
# this is the first occurance of address
potholes_by_block[block] = 1
else:
potholes_by_block[block] += 1
# find block with max potholes
xx = max(potholes_by_block.iteritems(), key=operator.itemgetter(1))[0]
# sorted
sorted_blocks = sorted(potholes_by_block.items(), key=operator.itemgetter(1))
print sorted_blocks
print xx, '=>', potholes_by_block[xx]
|
73d7bcd07d00a861b875a0db295f14433e088e23 | scaryswe/Chatbot | /Chatbot.py | 1,213 | 3.703125 | 4 | #chatbot Ashraj Grewal cs1.0
import random
def get_bot_response(user_response):
bot_response_happy = ["Great! That's how you belong", "Keep the good times going!", "Good, life is too short to be anything else"]
bot_response_angry = ["Sorry to hear that, take some time to think", "Have a cup of tea!", "Go listen to some calming music"]
bot_response_sad = ["It is okay to not be okay!", "We need to have downs to appreciate the ups", "*Virtual Hug*"]
bot_response_okay = ["being confused is natural", "use this time to think", "Do something you love to center yourself"]
if user_response == "happy":
return random.choice(bot_response_happy)
elif user_response == "angry":
return random.choice(bot_response_angry)
elif user_response == "sad":
return random.choice(bot_response_sad)
elif user_response == "okay":
return random.choice(bot_response_okay)
else:
return "We need to feel all emotions to stay human :)"
print("Welcome to the Mood Bot")
while True:
user_response = input ("How do you feel right now? Enter your mood:")
feeling = get_bot_response(user_response)
print(feeling)
if user_response == 'done':
break |
654710f5af7d99df94d195dae23f635a49a8832c | SafetyBits/codebreaker | /affineCipher.py | 2,384 | 3.609375 | 4 | # Affine Cipher
# http://inventwithpython.com/codebreaker (BSD Licensed)
import sys, random, pyperclip
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = 'A COMPUTER WOULD DESERVE TO BE CALLED INTELLIGENT IF IT COULD DECEIVE A HUMAN INTO BELIEVING THAT IT WAS HUMAN. -ALAN TURING'
keyA, keyB = 5, 7
mode = 'encrypt' # set to 'encrypt' or 'decrypt'
message = message.upper()
if keyA == 1:
sys.exit('The affine cipher becomes incredibly weak when keyA is set to 1. Choose a different key.')
if keyB == 0:
sys.exit('The affine cipher becomes incredibly weak when keyB is set to 0. Choose a different key.')
if gcd(keyA, len(SYMBOLS)) != 1:
sys.exit('The key (%s) and the size of the alphabet (%s) are not relatively prime. Choose a different key.' % (key, len(SYMBOLS)))
print('Original text:')
print(message)
if mode == 'encrypt':
translated = encryptMessage(keyA, keyB, message)
elif mode == 'decrypt':
translated = decryptMessage(keyA, keyB, message)
print('%sed text:' % (mode.title()))
print(translated)
pyperclip.copy(translated)
print('%sed text copied to clipboard.' % (mode.title()))
def gcd(a, b):
# Return the Greatest Common Divisor of a and b.
while a != 0:
a, b = b % a, a
return b
def findModInverse(a, m):
for b in range(m):
if (a * b) % m == 1:
return b
return None # None is returned only when gcd(a, m) == 1, which is invalid.
def encryptMessage(keyA, keyB, message):
ciphertext = ''
for symbol in message:
symIndex = SYMBOLS.find(symbol)
if symIndex != -1:
# encrypt this symbol
ciphertext += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)]
else:
# just append this symbol unencrypted
ciphertext += symbol
return ciphertext
def decryptMessage(keyA, keyB, message):
plaintext = ''
modInverseOfKeyA = findModInverse(keyA, len(SYMBOLS))
for symbol in message:
symIndex = SYMBOLS.find(symbol)
if symIndex != -1:
# decrypt this symbol
plaintext += SYMBOLS[(symIndex - keyB) * modInverseOfKeyA % len(SYMBOLS)]
else:
# just append this symbol unencrypted
plaintext += symbol
return plaintext
if __name__ == '__main__':
main() |
56c4d425f231167ce70dd0c70c5de565174985b8 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/hamming/071e786374ec4931bd5d961fefc16ee9.py | 291 | 3.859375 | 4 | """The Hamming distance."""
def distance(string1, string2):
"""Return the number of positions where the symbols are different."""
if len(string1) != len(string2):
raise ValueError(string1, string2)
return sum(1 for sym1, sym2 in zip(string1, string2) if sym1 != sym2)
|
6cc1b36a183bad8b9147033d08638f3789738a53 | Kylin2048/test | /P42_3_17_4_ๆ ผๅผๅ่พๅบ.py | 173 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 22:26:28 2021
3.17.4
@author: Qilin Wang
"""
a = eval(input())
b = eval(input())
print("%d้คไปฅ%d็ไฝๆฐๆฏ%d" %(a,b,a%b)) |
5c575aa581708d2b8751a9c9404b8a3c3fc45c1a | sushmita119/pythonProgramming | /programmingInPython/nqt prime.py | 289 | 3.578125 | 4 | def prime(n):
l=[]
for i in range(n+1):
if i>1:
for j in range(2,i):
if i%j==0:
break
else:
#print(i,end=" ")
l.append(str(i))
print(",".join(l))
n=50
prime(n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.