blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dca00d13b5dcc3d426fe42ffa8c864bbf24d40d4 | chiragnayak/python | /PyTraining/tech_rnd/Day_1_22March2021/comprehension.py | 1,401 | 3.640625 | 4 | print('-' * 75)
# Without using comprehension
sqr = []
for n in range(1, 11):
if n % 5 == 0 or n % 3 == 0:
sqr.append(n ** 2)
print('sqr -', sqr)
# List Comprehension
# [expr iteration <condition>]
sqr_lc = [n ** 2 for n in range(1, 11) if n % 5 == 0 or n % 3 == 0]
print('sqr_lc -', sqr_lc)
print('-' * 75)
# List of strings
strings = ['shell', 'perl', 'ruby', 'python', 'c_java']
len_lc = [len(elem) for elem in strings]
print('Len LC -', len_lc)
print('-' * 75)
# List of strings
strings = ['php', '1221', 'perl', 'python', 'madam']
chk_palin_lc = [elem == elem[::-1] for elem in strings]
print('CHK Palin LC -', chk_palin_lc)
palin_lc = [elem for elem in strings if elem == elem[::-1]]
print('Palin LC -', palin_lc)
print('-' * 75)
# Set Comprehension
# {expr iteration <condition>}
strings = ['shell', 'perl', 'ruby', 'python', 'c_java']
len_sc = {len(elem) for elem in strings}
print('Len SC -', len_sc, '-', type(len_sc))
print('-' * 75)
# Dictionary Comprehension
# {key: value iteration <condition>}
strings = ['shell', 'perl', 'ruby', 'python', 'c_java']
len_dc = {elem: len(elem) for elem in strings}
print('Len DC -', len_dc, '-', type(len_dc))
print('-' * 75)
# List of strings
strings = ['php', 'mam']
'''
dc = [{'p': 2, 'h': 1},
{'m': 2, 'a': 1}]
'''
wc = [{char: elem.count(char) for char in elem} for elem in strings]
print('wc -', wc)
print('-' * 75)
|
bb34fbc6f2baf6bfbd99ffa0865c2331d164af74 | JPauly-tec/Tarea1PaulyJimenez | /CharFunction.py | 1,258 | 3.84375 | 4 | def char_check(x): # revisa dato ENTRADA: carácter a revisar SALIDA: 0 o 1
global ER # crea variable global de error
if isinstance(x, str): # revisa que la entrada sea un string
if x.isalpha() is True: # revisa que la entrada sea del alfabeto
if len(x) == 1: # revisa que la extension sea igual a 1 digito
return 0 # si todo se cumple, devuelve 0
else:
ER = "ERROR CODE: 003; cáracter debe ser un unico caracter"
print(ER)
return 1
else:
ER = "ERROR CODE 002; cáracter debe ser letra"
print(ER)
return 1
else:
ER = "ERROR CODE: 001; cáracter debe ser String"
print(ER)
return 1
def caps_switch(y): # cambiar carácter entre MAYUS y MINUS,
# ENTRADA: un carácter, SALIDA: carácter invertido
CP = char_check(y) # corre chr check con la variable ingresada
if CP == 0: # si todo check_char se cumple, invierte la entrada
if y.isupper():
return y.lower()
else:
return y.upper()
else: # si no, solo se devuelve el codigo de error pertinente
print(ER)
return
|
e4f681424d3296907ab7773d320e238725942a85 | hrithiksagar/Competetive-Programming | /Python/Chapter 5 Dictionary and Set/problem 6.py | 955 | 3.828125 | 4 | """
Create an empty dict.
allow 4 friends to enter thier fav lang as values and use keys as their names
assume that the names are unique
IF names of 2 friends are same; what will happen?
If languages if two friends are smae what will happen?
"""
# favLang = {}
# a = input("enter ur fav lang Shubham: \n")
# b = input("enter ur fav lang Ankit: \n")
# c = input("enter ur fav lang Sonali: \n")
# d = input("enter ur fav lang Harshitha: \n")
# favLang['Shubham'] = a
# favLang['Ankit'] = b
# favLang['Sonali'] =c
# favLang['Harshitha'] =d
#
# print(favLang)
# qsn what if condition
favLang = {}
a = input("enter ur fav lang Shubham: \n")
b = input("enter ur fav lang Ankit: \n")
c = input("enter ur fav lang Shubham: \n")
d = input("enter ur fav lang Harshitha: \n")
favLang['Shubham'] = a
favLang['Ankit'] = b
favLang['Shubham'] =c
favLang['Harshitha'] =d
print(favLang)
# if Key value is present 2 times, then latest occurrence will be the updated on
|
92974d20628f8bb20c01ea8a7eac9811ce743e18 | Almenon/AREPL-vscode | /test/manualAreplTests/multipleTypes.py | 1,036 | 3.78125 | 4 | ###########################################
# Code
###########################################
import math # doesn't show up (good, we dont want modules to show)
a = 1
b = 1.1
c = float('nan')
d = float('infinity')
e = float('-infinity')
accent = 'é'
g = {}
h = []
i = [[[]]]
j = lambda x: x+1 # doesnt show up???
def k(x):
return x+1
class l():
def __init__(self,x):
self.x = x
m = l(5)
n = False
with open(__file__) as f:
o = f
from typing import List,Dict
x: List[int] = [1,2,3]
y: Dict[str, str] = {'a':'b'}
###########################################
# Expected Result
###########################################
"""
-{
a: 1,
b: 1.1,
c: "NaN",
d: "Infinity",
e: "-Infinity",
f: "é",
g: {},
h: [],
i: -[
+[1 items]
],
l: -{
py/type: "__main__.l"
},
m: -{
py/object: "__main__.l",
x: 5
},
n: false,
o: -{
py/id: 0
}
}
we should see lambda too but we havn't implemented that yet
"""
|
f4258360799c484e20942b855aac1f887b6d956d | Degamey/Memorizing-game | /main.py | 3,893 | 3.5 | 4 | import turtle
import time
import random as r
from langue import *
from tifunc import timer
from string import ascii_uppercase,ascii_lowercase
from testrandom import randchoes
let=ascii_uppercase+ascii_lowercase
letnum=let+"0123456789"
print(let)
t=turtle.Turtle()
t.hideturtle()
t.screen.setup(900, 600)
t.write('ИГРА ЗАПОМИНАЙКА', align='center', font=("Comic Sans MS", 18, "bold"))
turtle.title("ЗАПОМИНАЙКА")
timer(2)
t.reset()
t.hideturtle()
t.write(rusruler, align='center', font=("Comic Sans MS", 12, "bold"))
timer(5)
t.reset()
t.hideturtle()
gameover=0
sym=int(turtle.numinput("Что вы хотите запоминать?","0-Числа; 1-СИМВОЛЫ; 2-СИМВОЛЫ С ЦИФРАМИ",minval=0,maxval=2))
symnum=int(turtle.numinput("Сколько символов вы хотите запоминать?","Введите количество символов",minval=3,maxval=6))
secondnum=turtle.numinput("Сколько секунд изначально?","Введите изначальнае количество секунд(мин.5,макс.10)",minval=5,maxval=10)
if sym==0:
minval="1"
maxval="9"
for i in range(symnum-1):
minval+="0"
maxval+="9"
minval=int(minval)
maxval=int(maxval)
while gameover != 1:
secret=r.randint(minval,maxval)
t.write(secret, align='center', font=("Comic Sans MS", 15, "bold"))
#timer(secondnum)
time.sleep(secondnum)
t.reset()
t.hideturtle()
world=int(turtle.numinput("Введите число","Введите число которое вы запомнили"))
if world != secret:
gameover=1
if gameover == 1:
t.write(rusgameover, align='center', font=("Comic Sans MS", 8, "bold"))
time.sleep(4)
exit("You lose")
if secondnum == 2:
t.write(rusgamewin, align='center', font=("Comic Sans MS", 8, "bold"))
time.sleep(4)
exit("You win")
secondnum-=1
elif sym == 1:
while gameover != 1:
secret=randchoes(let,symnum)
print(secret)
t.write(secret, align='center', font=("Comic Sans MS", 15, "bold"))
#timer(secondnum)
time.sleep(secondnum)
t.reset()
t.hideturtle()
world=turtle.textinput("Введите символы","Введите символы которое вы запомнили")
if world != secret:
gameover=1
if gameover == 1:
t.write(rusgameover, align='center', font=("Comic Sans MS", 8, "bold"))
time.sleep(4)
exit("You lose")
if secondnum == 2:
t.write(rusgamewin, align='center', font=("Comic Sans MS", 8, "bold"))
time.sleep(4)
exit("You win")
secondnum-=1
elif sym == 2:
while gameover != 1:
secret=randchoes(letnum,symnum)
t.write(secret, align='center', font=("Comic Sans MS", 15, "bold"))
#timer(secondnum)
time.sleep(secondnum)
t.reset()
t.hideturtle()
world=turtle.textinput("Введите символы","Введите символы которое вы запомнили")
if world != secret:
gameover=1
if gameover == 1:
t.write(rusgameover, align='center', font=("Comic Sans MS", 8, "bold"))
time.sleep(4)
exit("You lose")
if secondnum == 2:
t.write(rusgamewin, align='center', font=("Comic Sans MS", 8, "bold"))
time.sleep(4)
exit("You win")
t.screen.exitonclick()
t.screen.mainloop() |
3f4d8f9a394ae861f5be27f68d110b0fbd0e72dd | popadrianc/learning_python | /Exercises/ex3.py | 557 | 4.15625 | 4 | #This should be a counting program
print("I will start counting cakes")
print("Banana cake", 25 + 30 / 6)
print("Apple cake", 100 - 25 * 3 % 4)
print("Now I will count the syrup:")
print( 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 3 +2 < 5 - 7?")
print(3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
print("Oh, that's why it's False.")
print("How about some more.")
print("Is it greater?, 5 > -2")
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
|
5a287b325f31a4c536474f03c85bbdea4213cbe3 | Anaivbvo/CSE | /notes/Anai S.L. Lopez - Challanges.py | 1,455 | 4.34375 | 4 | """
Easy:
1. Write a Python program which accepts the user's first and last name and print them in reverse order with a space
between them.
"""
print("Anai", "Lopez")
namelist = ["Anai", "Lopez"]
namelist. reverse( )
print(namelist)
"""
2. Write a Python program to find whether a given number (accept from the user) is even or odd, print out an
appropriate message to the user.
"""
print("Examples of even numbers: 0, 2, 4, 6, 8, etc")
print("Examples of odd numbers: 1, 3, 5, 7, 9, etc")
"""
3. Write a Python program that will accept the base and height of a triangle and compute the area.
"""
print("Triangle A has the base of: _ and the height of _.")
"""
4. Write a Python program to check if a number is positive, negative or zero.
"""
"""
Medium:
5. Write a Python program which accepts the radius of a circle from the user and compute the area.
Sample Output :
r = 1.1
Area = 3.8013271108436504
6. Write a Python program to get the volume of a sphere from a given radius.
7. Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.
8. Write a Python program to test whether a number is within 150 of 2000 or 3000.
"""
"""
Hard:
9. Write a Python program to test whether a passed letter is a vowel or not.
10. Write a Python program to check if a string is numeric
11. Write a Python program to get the system time
12. Write a Python program to find common divisors between two numbers in a given pair
""" |
f5d23f05333c4921107d563423501046ff875e06 | hebaflemban/datastructure- | /queue.py | 1,484 | 3.796875 | 4 | from random import randint
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class Queue:
def __init__(self, limit=None, front=None, back=None):
self.front = front
self.back = back
self.limit = limit
self.length = 0
def is_empty(self):
return self.length == 0
def is_full(self):
return self.length == self.limit
def enqueue (self, data):
if self.is_full():
print("Sorry line is closed")
else:
if self.is_empty():
new_node = Node(data)
self.front = new_node
else:
new_node = Node(data, next=self.back)
self.back = new_node
self.length +=1
def dequeue (self):
if self.is_empty():
print("No one in line")
else:
out = self.front
self.front = out.next
self.length -= 1
return out.data
def peek(self):
return f"You'll be waiting for {(self.length*30)/60} minutes if you got in line now \n {self.length} groups ahead of you"
medusa_q = Queue(limit=20)
print(medusa_q.peek())
for i in range(4):
grp = randint(1,20)
print(grp)
if grp <= 12:
medusa_q.enqueue(grp)
else:
medusa_q.enqueue(12)
medusa_q.enqueue(grp-12)
print(medusa_q.peek())
print("Group size:", medusa_q.dequeue())
print(medusa_q.peek())
|
7e7d25ce8c8f6f176a4587022aed9bb4e9b27724 | Mugambiii/python-1 | /lesson 7 -functions.py | 1,540 | 4.03125 | 4 | def addition():
num1 = float(input("Enter first number"))
num2 = float(input("Enter second number"))
result = num1 + num2
print("{} + {} ={}".format(num1, num2, result))
#addition
# def addition2(num1,num2,num3):
# result = num1 + num2 + num3
# print("{} + {} ={}".format(num1, num2,num3, result))
# addition2(num1 = 10, num2 = 30, num3 = 50)
# def welcome (name):
# print("Welcome {}".format(name))
# welcome(name="Babra")
# welcome(name = "Jackson")
# def student_marks(name,marks):
# print(name)
# print(marks)
# total_marks = 0
# for score in marks:
# total_marks += score
# print("Hi {} . Your total marks is {}".format(name,total_marks))
#
# student_marks(name = "Babra", marks = [70,87,90])
# student_marks(name = "John",marks = [76,67,86])
#list of customers
#print "Happy to serve you XX for every customer
# def customer_list(customers):
# for name in customers:
# print("Happy to serve you {}".format(name))
#
# customer_list(customers=["Babra","John","Kevin"])
def withdraw(amount):
balance = 1000
if amount <50:
print("amount less than allowed minimum")
elif amount >= 70000:
print("amount exceeds the maximum limit")
print("withdraw not possible")
elif amount > balance:
print("insufficient funds")
print("withdraw not possible")
else:
balance -= amount
print("withdraw transaction of {} successful. New balance is {}".format(amount,balance))
withdraw(amount = 999)
|
489b0d1a7f6ecd7be001d001cf323db2f86f2c1c | AdamZhouSE/pythonHomework | /Code/CodeRecords/2126/60899/275099.py | 363 | 3.71875 | 4 | def largestDivisibleSubset(nums):
s = {-1: set()}
for n in sorted(nums):
s[n] = max((s[d] for d in s if n % d == 0), key=len) | {n}
return list(max(s.values(), key=len))
def main():
list0 = list(map(int,input().split(",")))
list1 = largestDivisibleSubset(list0)
list1.sort()
print(list1)
if __name__ == '__main__':
main()
|
8118ce64a2b70ee1871287574a5007e9d36d02b2 | Falconssko/skola | /uloha 6.py | 503 | 3.796875 | 4 | a=input("zadaj meno 1. cloveka:")
am=float(input("zadaj vahu 1. cloveka:"))
b=input("zadaj meno 2. cloveka:")
bm=float(input("zadaj vahu 2. cloveka:"))
c=input("zadaj meno 3. cloveka:")
cm=float(input("zadaj vahu 3. cloveka:"))
P = (am+bm+cm)/3
print('priemerna vaha je:', P)
if am > P:
print("a nadpriemernu vahu ma", a)
elif bm > P:
print("a nadpriemernu vahu ma", b)
elif cm > P:
print('a nadpriemernu vahu ma', c)
else:
print('gratulujem nikto nie je tucny')
|
f109aac3d2da36f385d0ece865e370490eda837b | error707-persona/Hacktoberfest-21 | /CryptoGraphy.py | 1,862 | 4.0625 | 4 | #CRYPTOGRAGHY USING RAIL FENCE CIPHER METHOD
'''
Input Text : Sentence that needs to be encrypted,
Key : Any integer (encrypting the text)
'''
def main():
clearText =input("Enter text :")
clearText = clearText.replace(" ","")
clearText = clearText.upper()
key = int(input("enter Key:"))
cipherText = cipher(clearText, key)
print ("Ciphered Text: {0}".format(cipherText))
decipherText = decipher(cipherText, key)
print ("Deciphered Text: {0}".format(decipherText))
return
def cipher(clearText, key):
result = ""
matrix = [["" for x in range(len(clearText))] for y in range(key)]
increment = 1
row = 0
col = 0
for c in clearText:
if row + increment < 0 or row + increment >=len(matrix):
increment = increment * -1
matrix[ row ][ col ] = c
row += increment
col += 1
for list in matrix:
result += "".join(list)
return result
def decipher(cipherText, key):
result = ""
matrix = [["" for x in range(len(cipherText))] for y in range(key)]
idx = 0
increment = 1
for selectedRow in range(0, len(matrix)):
row = 0
for col in range(0, len(matrix[ row ])):
if row + increment < 0 or row + increment >= len(matrix):
increment = increment * -1
if row == selectedRow:
matrix[row][col] += cipherText[idx]
idx += 1
row += increment
matrix = transpose( matrix )
for list in matrix:
result += "".join(list)
return result
def transpose( m ):
result = [ [ 0 for y in range( len(m) ) ] for x in range( len(m[0]) ) ]
for i in range( len(m) ):
for j in range( len(m[0]) ):
result[ j ][ i ] = m[ i ][ j ]
return result
main()
|
379a52c89378c8772d3e5b69ad18c097ed5ca7f1 | mtj6/class_project | /album.py | 455 | 3.921875 | 4 | def make_album(artist_name, album_title, tracks_number=' '):
"""Return information about an album."""
album = {'name' : artist_name, 'title' : album_title}
if tracks_number:
album['tracks_number'] = tracks_number
return album
record = make_album('beyonce', 'lemonade')
print(record)
record = make_album('bob dylan', 'blood on the tracks', tracks_number=10)
print(record)
record = make_album('maclemore', 'gemini')
print(record) |
d8afaf00398a7259cca4be7eea1a8983a6fe1b96 | zoro16/tf_tutorials | /high_level_api/numpy_arrays.py | 1,700 | 3.515625 | 4 | import numpy as np
import tensorflow as tf
# Load the training data into two NumPy arrays, for example using `np.load()`.
with np.load("/var/data/training_data.npy") as data:
features = data["features"]
labels = data["labels"]
# Assume that each row of `features` corresponds to the same row as `labels`.
assert features.shape[0] == labels.shape[0]
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
'''
Note that the above code snippet will embed the features and labels arrays in your TensorFlow graph as tf.constant() operations. This works well for a small dataset, but wastes memory---because the contents of the array will be copied multiple times---and can run into the 2GB limit for the tf.GraphDef protocol buffer.
As an alternative, you can define the Dataset in terms of tf.placeholder() tensors, and feed the NumPy arrays when you initialize an Iterator over the dataset.
'''
# Load the training data into two NumPy arrays, for example using `np.load()`.
with np.load("/var/data/training_data.npy") as data:
features = data["features"]
labels = data["labels"]
# Assume that each row of `features` corresponds to the same row as `labels`.
assert features.shape[0] == labels.shape[0]
features_placeholder = tf.placeholder(features.dtype, features.shape)
labels_placeholder = tf.placeholder(labels.dtype, labels.shape)
dataset = tf.data.Dataset.from_tensor_slices((features_placeholder, labels_placeholder))
# [Other transformations on `dataset`...]
dataset = ...
iterator = dataset.make_initializable_iterator()
sess.run(iterator.initializer, feed_dict={features_placeholder: features,
labels_placeholder: labels})
|
86e34ae6075047e37b7dc0739e3789d0d610279a | Neeraj-kaushik/Coding_Ninjas_Python | /ConditionalsAndLoops/PalindromeNumber.py | 163 | 3.796875 | 4 | num=int(input())
rev=0
digit=num
while digit!=0:
rev=rev*10
rev=rev+digit%10
digit=digit//10
if rev==num :
print("true")
else:
print("false") |
0eeee7705ee7710ecbd77a31fb9f64a1afc5ff7e | alvinwang922/Data-Structures-and-Algorithms | /Tries/Add-Search-Word.py | 1,675 | 3.953125 | 4 | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string
containing only letters a-z or .. A . means it can represent any one letter.
"""
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.WordDictionary = defaultdict(set)
def addWord(self, word: str):
"""
Adds a word into the data structure.
"""
self.WordDictionary[len(word)].add(word)
def search(self, word: str):
"""
Returns if the word is in the data structure. A word could contain
the dot character '.' to represent any one letter.
"""
if not word:
return False
if "." not in word:
return word in self.WordDictionary[len(word)]
for w in self.WordDictionary[len(word)]:
counter = 0
for char in word:
if char != "." and char != w[counter]:
break
counter += 1
else:
return True
return False
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
operations = ["WordDictionary", "addWord", "addWord", "addWord", "search", "search",
"search", "search"]
inputs = [[], ["bad"], ["dad"], ["mad"], ["pad"], ["bad"], [".ad"], ["b.."]]
print("Running the operations above on the inputs above, the booleans returned should be \
[None, None, None, None, False, True, True, True].")
|
8b376abd8af5b6453563d51c08783db557131ec7 | Tom-Szendrey/Highschool-basic-notes | /Notes/Banking Examples Programs/school.py | 814 | 3.96875 | 4 | #mr t
#jan 1 2000
# this program proves that I know what I am doing
class Person(object):
#the class methods variables and code goes here.
def __init__(self, initial):
self.name= initial
self.birthdate=""
self.height=0
def set_dob(self,date):
self.birthdate=date
def set_height(self,h):
self.height=h
class Student(Person):
def init(self):
self.uniformInfraction=0
self.grade=0
def set_grade(self,g):
self.grade=g
def nonUniform(self):
self.uniformInfraction+=1
class Teacher(Person):
yearExp=0
def expIncrease(self):
self.yearExp+=1
def setOffice(self,o):
self.office=o
|
3a2f98d1c97fe2e70e14dda9c1bdfa224a8f6ed6 | hanrick2000/leetCode-5 | /PythonForLeetCode/728_SelfDividingNumbers.py | 629 | 3.515625 | 4 | class Solution:
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
result = []
for i in range(left, right + 1):
temp = i
divide = True
while temp > 0:
mode = temp % 10
if mode == 0 or i % mode != 0:
divide = False
temp = int(temp / 10)
if divide:
result.append(i)
return result
sol = Solution()
result = sol.selfDividingNumbers(1, 22)
print(result)
|
6d82cb65b98b404608ac85d11d3c570a4a58cc87 | harsilspatel/HackerRank | /Mathematics/Geometry/Points On a Line.py | 193 | 3.640625 | 4 | x = []
y = []
for i in range(int(input())):
a, b = map(int, input().split())
x.append(a)
y.append(b)
x.sort()
y.sort()
if (x[-1] == x[0] or y[-1] == y[0]):
print ("YES")
else:
print ("NO") |
6675c87e0b827a62b53192168ac50e857b22ac0d | AlexandrSech/Z49-TMS | /students/Volodzko/Task_2/task_2_3.py | 223 | 3.828125 | 4 | """
Создать строку равную первым пяти символам введенной строки
"""
my_strinng = input("Введите строку: ")
string_result = my_strinng[:5]
print(string_result) |
1d54e4197fa4926dff7c1c8ecfe7e70bc5b7ce74 | deepsjuneja/Task1 | /prime.py | 237 | 3.96875 | 4 | def num():
n = int(input("Enter a number"))
c = 0
for i in range(2, n):
if n%i == 0:
c = c+1
if c == 0:
print("Prime Number")
else:
print("Not a prime number")
num()
|
36476a1e2fe20f04e4ad0a5c2d00e731b6345fb2 | Reid00/KnowledgeGraph | /DataStructure/letcode05.py | 799 | 3.53125 | 4 | # -*- encoding: utf-8 -*-
'''
@File :letcode05.py
@Time :2020/07/10 16:38:10
@Author :Reid
@Version :1.0
@Desc :请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
'''
# 示例:
# 输入:s = "We are happy."
# 输出:"We%20are%20happy."
# 限制:
# 0 <= s 的长度 <= 10000
def resolution():
"""
内置replace 方法
"""
s = 'we are happy'
return s.replace(' ', '%20')
def manual_replace():
"""
手写实现replace 方法
"""
s = 'we are happy'
res = list()
for char in s:
if char != ' ':
res.append(char)
else:
char = '%20'
res.append(char)
return ''.join(res)
if __name__ == "__main__":
res = manual_replace()
print(res)
|
423e730dd654924ded852fefb1801788a81ef167 | astorcam/scripts_Seguridad | /analFrec.py | 449 | 3.8125 | 4 | import operator
text= input("Mete el texto cifrado: ")
letras=["e","a","o","l","s","n","d","r","u","i","t","c","p","m","y","q","b","h","g","f","v","j","ñ","z","x","k","w"]
caracteres={}
for char in text:
if char.isalpha() or char=="ñ":
if char in caracteres:
caracteres[char]+=1
else:
caracteres [char]=1
apariciones = dict( sorted(caracteres.items(), key=operator.itemgetter(1),reverse=True))
lista = list(apariciones)
print (lista)
|
71ee5e3080435b48daf880ca08517318b892905a | pytorch/tutorials | /advanced_source/dynamic_quantization_tutorial.py | 10,140 | 3.5 | 4 | """
(beta) Dynamic Quantization on an LSTM Word Language Model
==================================================================
**Author**: `James Reed <https://github.com/jamesr66a>`_
**Edited by**: `Seth Weidman <https://github.com/SethHWeidman/>`_
Introduction
------------
Quantization involves converting the weights and activations of your model from float
to int, which can result in smaller model size and faster inference with only a small
hit to accuracy.
In this tutorial, we will apply the easiest form of quantization -
`dynamic quantization <https://pytorch.org/docs/stable/quantization.html#torch.quantization.quantize_dynamic>`_ -
to an LSTM-based next word-prediction model, closely following the
`word language model <https://github.com/pytorch/examples/tree/master/word_language_model>`_
from the PyTorch examples.
"""
# imports
import os
from io import open
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
######################################################################
# 1. Define the model
# -------------------
#
# Here we define the LSTM model architecture, following the
# `model <https://github.com/pytorch/examples/blob/master/word_language_model/model.py>`_
# from the word language model example.
class LSTMModel(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(self, ntoken, ninp, nhid, nlayers, dropout=0.5):
super(LSTMModel, self).__init__()
self.drop = nn.Dropout(dropout)
self.encoder = nn.Embedding(ntoken, ninp)
self.rnn = nn.LSTM(ninp, nhid, nlayers, dropout=dropout)
self.decoder = nn.Linear(nhid, ntoken)
self.init_weights()
self.nhid = nhid
self.nlayers = nlayers
def init_weights(self):
initrange = 0.1
self.encoder.weight.data.uniform_(-initrange, initrange)
self.decoder.bias.data.zero_()
self.decoder.weight.data.uniform_(-initrange, initrange)
def forward(self, input, hidden):
emb = self.drop(self.encoder(input))
output, hidden = self.rnn(emb, hidden)
output = self.drop(output)
decoded = self.decoder(output)
return decoded, hidden
def init_hidden(self, bsz):
weight = next(self.parameters())
return (weight.new_zeros(self.nlayers, bsz, self.nhid),
weight.new_zeros(self.nlayers, bsz, self.nhid))
######################################################################
# 2. Load in the text data
# ------------------------
#
# Next, we load the
# `Wikitext-2 dataset <https://www.google.com/search?q=wikitext+2+data>`_ into a `Corpus`,
# again following the
# `preprocessing <https://github.com/pytorch/examples/blob/master/word_language_model/data.py>`_
# from the word language model example.
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = []
def add_word(self, word):
if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) - 1
return self.word2idx[word]
def __len__(self):
return len(self.idx2word)
class Corpus(object):
def __init__(self, path):
self.dictionary = Dictionary()
self.train = self.tokenize(os.path.join(path, 'train.txt'))
self.valid = self.tokenize(os.path.join(path, 'valid.txt'))
self.test = self.tokenize(os.path.join(path, 'test.txt'))
def tokenize(self, path):
"""Tokenizes a text file."""
assert os.path.exists(path)
# Add words to the dictionary
with open(path, 'r', encoding="utf8") as f:
for line in f:
words = line.split() + ['<eos>']
for word in words:
self.dictionary.add_word(word)
# Tokenize file content
with open(path, 'r', encoding="utf8") as f:
idss = []
for line in f:
words = line.split() + ['<eos>']
ids = []
for word in words:
ids.append(self.dictionary.word2idx[word])
idss.append(torch.tensor(ids).type(torch.int64))
ids = torch.cat(idss)
return ids
model_data_filepath = 'data/'
corpus = Corpus(model_data_filepath + 'wikitext-2')
######################################################################
# 3. Load the pretrained model
# -----------------------------
#
# This is a tutorial on dynamic quantization, a quantization technique
# that is applied after a model has been trained. Therefore, we'll simply load some
# pretrained weights into this model architecture; these weights were obtained
# by training for five epochs using the default settings in the word language model
# example.
ntokens = len(corpus.dictionary)
model = LSTMModel(
ntoken = ntokens,
ninp = 512,
nhid = 256,
nlayers = 5,
)
model.load_state_dict(
torch.load(
model_data_filepath + 'word_language_model_quantize.pth',
map_location=torch.device('cpu')
)
)
model.eval()
print(model)
######################################################################
# Now let's generate some text to ensure that the pretrained model is working
# properly - similarly to before, we follow
# `here <https://github.com/pytorch/examples/blob/master/word_language_model/generate.py>`_
input_ = torch.randint(ntokens, (1, 1), dtype=torch.long)
hidden = model.init_hidden(1)
temperature = 1.0
num_words = 1000
with open(model_data_filepath + 'out.txt', 'w') as outf:
with torch.no_grad(): # no tracking history
for i in range(num_words):
output, hidden = model(input_, hidden)
word_weights = output.squeeze().div(temperature).exp().cpu()
word_idx = torch.multinomial(word_weights, 1)[0]
input_.fill_(word_idx)
word = corpus.dictionary.idx2word[word_idx]
outf.write(str(word.encode('utf-8')) + ('\n' if i % 20 == 19 else ' '))
if i % 100 == 0:
print('| Generated {}/{} words'.format(i, 1000))
with open(model_data_filepath + 'out.txt', 'r') as outf:
all_output = outf.read()
print(all_output)
######################################################################
# It's no GPT-2, but it looks like the model has started to learn the structure of
# language!
#
# We're almost ready to demonstrate dynamic quantization. We just need to define a few more
# helper functions:
bptt = 25
criterion = nn.CrossEntropyLoss()
eval_batch_size = 1
# create test data set
def batchify(data, bsz):
# Work out how cleanly we can divide the dataset into ``bsz`` parts.
nbatch = data.size(0) // bsz
# Trim off any extra elements that wouldn't cleanly fit (remainders).
data = data.narrow(0, 0, nbatch * bsz)
# Evenly divide the data across the ``bsz`` batches.
return data.view(bsz, -1).t().contiguous()
test_data = batchify(corpus.test, eval_batch_size)
# Evaluation functions
def get_batch(source, i):
seq_len = min(bptt, len(source) - 1 - i)
data = source[i:i+seq_len]
target = source[i+1:i+1+seq_len].reshape(-1)
return data, target
def repackage_hidden(h):
"""Wraps hidden states in new Tensors, to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h)
def evaluate(model_, data_source):
# Turn on evaluation mode which disables dropout.
model_.eval()
total_loss = 0.
hidden = model_.init_hidden(eval_batch_size)
with torch.no_grad():
for i in range(0, data_source.size(0) - 1, bptt):
data, targets = get_batch(data_source, i)
output, hidden = model_(data, hidden)
hidden = repackage_hidden(hidden)
output_flat = output.view(-1, ntokens)
total_loss += len(data) * criterion(output_flat, targets).item()
return total_loss / (len(data_source) - 1)
######################################################################
# 4. Test dynamic quantization
# ----------------------------
#
# Finally, we can call ``torch.quantization.quantize_dynamic`` on the model!
# Specifically,
#
# - We specify that we want the ``nn.LSTM`` and ``nn.Linear`` modules in our
# model to be quantized
# - We specify that we want weights to be converted to ``int8`` values
import torch.quantization
quantized_model = torch.quantization.quantize_dynamic(
model, {nn.LSTM, nn.Linear}, dtype=torch.qint8
)
print(quantized_model)
######################################################################
# The model looks the same; how has this benefited us? First, we see a
# significant reduction in model size:
def print_size_of_model(model):
torch.save(model.state_dict(), "temp.p")
print('Size (MB):', os.path.getsize("temp.p")/1e6)
os.remove('temp.p')
print_size_of_model(model)
print_size_of_model(quantized_model)
######################################################################
# Second, we see faster inference time, with no difference in evaluation loss:
#
# Note: we set the number of threads to one for single threaded comparison, since quantized
# models run single threaded.
torch.set_num_threads(1)
def time_model_evaluation(model, test_data):
s = time.time()
loss = evaluate(model, test_data)
elapsed = time.time() - s
print('''loss: {0:.3f}\nelapsed time (seconds): {1:.1f}'''.format(loss, elapsed))
time_model_evaluation(model, test_data)
time_model_evaluation(quantized_model, test_data)
######################################################################
# Running this locally on a MacBook Pro, without quantization, inference takes about 200 seconds,
# and with quantization it takes just about 100 seconds.
#
# Conclusion
# ----------
#
# Dynamic quantization can be an easy way to reduce model size while only
# having a limited effect on accuracy.
#
# Thanks for reading! As always, we welcome any feedback, so please create an issue
# `here <https://github.com/pytorch/pytorch/issues>`_ if you have any.
|
c78f15642c1c6a5f47637fa44d1ed4b79575a8ac | aniruddhafrnd/python_proj | /pgm1_divison_q1.py | 393 | 3.765625 | 4 | '''
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
'''
mylst = []
myno = range(2000,3200)
for x in myno:
if x%7 == 0 and x%5 != 0:
# print (x)
mylst.append(str(x))
print (','.join(mylst))
|
f0af3341d0db22d926e56a932e4abbf8c7bc6a53 | maxrmjf8/IACodigos | /CodeClass.py | 1,679 | 4.25 | 4 | #Code in Class
#Ejercicio 1.- Programa en python que dado como dato el sueldo de un trabajador, le aplique un aumento del 15% si su sueldo es inferior a $1000.00 y del 12% en caso contrario.
def main():
st= float(input("Introduce tu sueldo: "))
if(st<1000):
sf = st*.15 + st
elif(st >= 1000):
sf= st*.12+st
print("El sueldo final es: ", sf)
if __name__ == "__main__":
main()
#Ejercicio 2.- Programa que dado como datos la categoría y el sueldo de un trabajor, calcule el aumento correspondiente teniendo en cuenta la siguiente información e imprima el nuevo sueldo del trabajador:
#Categoría 1 : Aumento 15%
#Categoría 2 : Aumento 10%
#Categoría 3 : Aumento 8%
#Categoría 4 : Aumento 7%
def main():
ciclo = True
while (ciclo==True):
print("Trabajador")
print("Categoría 1, Categoría 2, Categoría 3, Categoría 4")
TT= int(input("¿Cuál es la clase de trabajador que es? "))
ST= float(input("Ingrese su sueldo: "))
if(TT==1):
sf= ST*.15+ST
print("El sueldo final es: ", sf)
elif(TT==2):
sf= ST*.10+ST
print("El sueldo final es: ", sf)
elif(TT==3):
sf= ST*.08+ST
print("El sueldo final es: ", sf)
elif(TT==4):
sf= ST*.07+ST
print("El sueldo final es: ", sf)
else:
print("Valor inválido")
opc=input("¿Desea ingresar otro trabajador? (Y/N)")
if (opc== "Y" or opc== "y"):
ciclo=True
else:
ciclo=False
if __name__ == "__main__":
main() |
aab5c091441863757056c2fcb055402d66d6f700 | chingxwen/FYP | /News/Classes/Plotting News Graph - function.py | 2,162 | 3.515625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
df = pd.read_csv("Formatted_Data_Sentiment.csv")
senti = df["Sentiment"]
df["Date"] = pd.to_datetime(df["Date"], format = "%Y/%m/%d")
date = df['Date']
#Line Graph
def senti_linegraph(date, senti):
start_date = input("Please input start date: ")
converted_start_date = datetime.strptime(start_date, "%Y/%m/%d")
end_date = input("Please input end date: ")
converted_end_date = datetime.strptime(end_date, "%Y/%m/%d")
daterange = []
sentirange = []
for i in range(len(date)):
if date[i] >= converted_start_date and date[i] <= converted_end_date:
# print(date[i])
daterange.append(date[i])
sentirange.append(senti[i])
#Graph to show the relationship between the said date and the sentiments of the articles in the range
plt.plot(daterange, sentirange, 'rD-')
# plt.ylim(-10,80)
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 25
fig_size[1] = 10
plt.rcParams["figure.figsize"] = fig_size
plt.title("Sentiments vs Date")
plt.xlabel('Date')
plt.ylabel('Sentiments In Each Article')
plt.show()
#Define number of positive, negative and neutral articles
pos_art = 0
neg_art = 0
neu_art = len(senti) - pos_art - neg_art
def senti_info(senti):
for num in senti:
if num > 0:
pos_art += 1
elif num < 0:
neg_art += 1
else:
pass
print("Out Of {} Articles, {} Are Positive , {} Are Negative And {} Is/Are Neutral"
.format(len(senti), pos_art, neg_art, neu_art))
#Piechart
def senti_piechart():
labels = ["Positive", "Negative", "Neutral"]
size = [pos_art, neg_art, neu_art]
colors = ['#2CCDBD', '#CD2C7D', '#FFA500']
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 10
fig_size[1] = 5
plt.title("Net Sentiment")
plt.pie(size, labels = labels, colors = colors, autopct='%1.1f%%', startangle=90)
plt.show()
|
624c8bcf049a6af39333583a6cd0b9ad82027331 | farmkate/asciichan | /crypto/LC101rot13.py | 470 | 3.921875 | 4 | #LC101rot13.py
def rot13(mess):
# Your code here
rotate = 13
cipher = ''
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for char in mess:
if char.isalpha():
index = alphabet.index(char)
cipher = cipher + alphabet[(index + rotate) % 26]
else:
cipher = cipher + char
return cipher
print(rot13('abcde'))
print(rot13('nopqr'))
print(rot13(rot13('since rot13 is symmetric you should see this message')))
|
f17dacabee9825e9cc3d0806ecf4daf7a9c7c0c1 | kennethyu2017/cs231n_assignments | /assignment3/cs231n/image_utils.py | 3,017 | 3.625 | 4 | import urllib2, os, tempfile
import numpy as np
from scipy.misc import imread
from cs231n.fast_layers import conv_forward_fast
"""
Utility functions used for viewing and processing images.
"""
def blur_image(X):
"""
A very gentle image blurring operation, to be used as a regularizer for image
generation.
Inputs:
- X: Image data of shape (N, 3, H, W)
Returns:
- X_blur: Blurred version of X, of shape (N, 3, H, W)
"""
w_blur = np.zeros((3, 3, 3, 3)) # shape (F,C,H,W)
b_blur = np.zeros(3)
blur_param = {'stride': 1, 'pad': 1}
for i in xrange(3):
# w_blur[1] is for conv only on color channel 1, so only w_blur[1,1] has non-zero value.
# same to w_blur[2] for color channel 2, w_blur[3] for color channel 3.
w_blur[i, i] = np.asarray([[1, 2, 1], [2, 188, 2], [1, 2, 1]], dtype=np.float32)
# the conv results have only 3-feature maps corresponding to R,G,B color channels.
# the each pixel of X scale about (-1,1), so after conv with the receiptive field above,
# each element of result feature map scale about (-200,200), so divide w_blur by 200 to
# keep the original scale ~ (-1,1)
w_blur /= 200.0
return conv_forward_fast(X, w_blur, b_blur, blur_param)[0]
def preprocess_image(img, mean_img, mean='image'):
"""
Convert to float, transepose, and subtract mean pixel
Input:
- img: (H, W, 3)
Returns:
- (1, 3, H, 3)
"""
if mean == 'image':
mean = mean_img
elif mean == 'pixel':
mean = mean_img.mean(axis=(1, 2), keepdims=True)
elif mean == 'none':
mean = 0
else:
raise ValueError('mean must be image or pixel or none')
return img.astype(np.float32).transpose(2, 0, 1)[None] - mean
def deprocess_image(img, mean_img, mean='image', renorm=False):
"""
Add mean pixel, transpose, and convert to uint8
Input:
- (1, 3, H, W) or (3, H, W)
Returns:
- (H, W, 3)
"""
if mean == 'image':
mean = mean_img
elif mean == 'pixel':
mean = mean_img.mean(axis=(1, 2), keepdims=True)
elif mean == 'none':
mean = 0
else:
raise ValueError('mean must be image or pixel or none')
if img.ndim == 3:
img = img[None]
img = (img + mean)[0].transpose(1, 2, 0)
if renorm:
# TODO: should first renorm then add the mean? cause mean is in the natural image scale range
# , if we add mean to the image before renorm, we add them with different scale.
low, high = img.min(), img.max()
img = 255.0 * (img - low) / (high - low)
return img.astype(np.uint8)
def image_from_url(url):
"""
Read an image from a URL. Returns a numpy array with the pixel data.
We write the image to a temporary file then read it back. Kinda gross.
"""
try:
f = urllib2.urlopen(url)
_, fname = tempfile.mkstemp()
with open(fname, 'wb') as ff:
ff.write(f.read())
img = imread(fname)
os.remove(fname)
return img
except urllib2.URLError as e:
print 'URL Error: ', e.reason, url
except urllib2.HTTPError as e:
print 'HTTP Error: ', e.code, url
|
9b1d4324e57abc09372304022a26f1f66e468aad | BaoziSwifter/MyPythonLeetCode | /pythonLeetcode/448.找到所有数组中消失的数字.py | 2,809 | 3.859375 | 4 | #
# @lc app=leetcode.cn id=448 lang=python3
#
# [448] 找到所有数组中消失的数字
#
# https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/description/
#
# algorithms
# Easy (54.02%)
# Likes: 226
# Dislikes: 0
# Total Accepted: 17.8K
# Total Submissions: 32.9K
# Testcase Example: '[4,3,2,7,8,2,3,1]'
#
# 给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
#
# 找到所有在 [1, n] 范围之间没有出现在数组中的数字。
#
# 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
#
# 示例:
#
#
# 输入:
# [4,3,2,7,8,2,3,1]
#
# 输出:
# [5,6]
#
#
#
# @lc code=start
class Solution:
# 集合相减
# def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
# return list(set(range(1,len(nums)+1))-set(nums))
# 2
# def findDisappearedNumbers(self, nums):
# 将所有正数作为数组下标,置对应数组值为负值。那么,仍为正数的位置即为(未出现过)消失的数字。
# 举个例子:
# 原始数组:[4,3,2,7,8,2,3,1]
# 重置后为:[-4,-3,-2,-7,8,2,-3,-1]
# 结论:[8,2] 分别对应的index为[5,6](消失的数字)
# for num in nums:
# index = abs(num) - 1
# # 始终保持nums[index]为负数
# nums[index] = -abs(nums[index])
# return [i + 1 for i, num in enumerate(nums) if num > 0]
# 3
# def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
# flags = list(range(1, 1 + len(nums)))
# for num in nums:
# flags[num-1] = 0
# res = [i for i in flgas if i != 0]
# return res
# 4
# def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
# numss = set(nums)
# return [ i for i in range(1, len(nums)+1) if i not in numss]
# 5
# def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
# if nums == []:
# return []
# a = set(nums)
# maxlen = len(nums)
# b = []
# for i in range(1, maxlen+1):
# if i not in a:
# b.append(i)
# return b
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
if not nums:
return None
nums.sort()
storeList = []
start = 0
for i in nums:
if i - start > 1:
storeList.extend(list(range(start+1,i)))
start = i
maxVal = nums[-1]
storeList.extend(list(range(maxVal+1,len(nums)+1)))
return storeList
# @lc code=end
|
de4e48a7ecbb312cf5c162f7893346dbe17a708c | pumbaacave/atcoder | /Leetcode/kthSmallestBST.py | 918 | 3.734375 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
# inorder travel
cnt = 0
cur = root
stack: List[TreeNode] = [root]
# invariance: node can enter stack only after all left children processed
while cur:
stack.append(cur)
cur = cur.left
while stack:
cur = stack.pop(-1)
# process left child
# process current
cnt += 1
if cnt == k:
return cur.val
cur = cur.right
# process right child
while cur
stack.append(cur)
cur = cur.left
return -1
|
0aeb9869c502f0d730499f86429c3be86710b7e1 | dishant-helpshift/Git_Intro | /code01.py | 334 | 3.59375 | 4 | def getFizzBuzzUptoN( n ):
fizzbuzzSeq = []
for i in range( 1, n+1):
tmpstr = ""
if i%3==0:
tmpstr += "Fizz"
if i%5==0:
tmpstr += "Buzz"
if tmpstr == "":
tmpstr = tmpstr + str(i)
fizzbuzzSeq.append( tmpstr )
return fizzbuzzSeq
if __name__ == "__main__":
fizzbuzzSeq = getFizzBuzzUptoN( 10 )
print(fizzbuzzSeq) |
cced8ec5079198dc899ae32536b47b4b25e288b0 | kadarakos/dag-cppn | /network.py | 7,309 | 3.875 | 4 | import random
import math
random.seed(2777)
class Node(object):
"""A neuron in a network.
Takes inputs, adds them up and applies
and activation function to the sum.
Parameters
----------
idx : str
Name of the node.
func : function
Activation function.
Attributes
----------
idx : str
Name of the node.
func : function
Activation function.
inputs : list
Accumulates input values to the node.
out_edges : list
Outgoing edges of the node.
"""
def __init__(self, idx, func):
self.idx = idx
self.func = func
self.inputs = []
self.out_edges = []
def add_outedge(self, edge):
"""Adds an outgoing edge to the node.
Parameters
----------
edge : Edge object
Edge to add.
"""
self.out_edges.append(edge)
def add_input(self, x):
"""Adds an input to the list.
Parameters
----------
edge : float
New input value.
"""
self.inputs.append(x)
def propagate(self):
"""Propagate inputs forward and refresh inputs list.
Returns
--------
x : float
Apply activation to the sum of the inputs.
"""
x = self.func(sum(self.inputs))
self.inputs = []
return x
def __str__(self):
return "{}-{}".format(self.idx, str(self.func.__name__))
class Edge(object):
"""An edge between nodes.
It adds its weight to the parent
activation value and adds its own weight to it.
Parameters
----------
idx : str
Name of the node.
parent : Node object
Node from which this edge is outgoing.
child : Node object
Node to which this edge is ingoing.
weight : float
Weight to add to the activation of the parent.
Attributes
----------
idx : str
Name of the node.
parent : Node object
Node from which this edge is outgoing.
child : Node object
Node to which this edge is ingoing.
weight : float
Weight to add to the activation of the parent.
"""
def __init__(self, idx, parent, child, weight):
self.idx = idx
self.parent = parent
self.child = child
self.weight = weight
def propagate(self):
"""Propagate activation from parent to child."""
x = self.parent.propagate()
x += self.weight
self.child.add_input(x)
class Network(object):
def __init__(self):
self.layers = [[], [], []]
self.nodes = {}
self.edges = []
self.networkx_graph = None
def gen_weight(self, mu=0, sigma=1):
w = random.gauss(mu, sigma)
return w
def gen_node(self, layer):
node_idx = gen_name("neuron-")
f = random.choice(activation_functions)
return Node(node_idx, f)
def add_node(self, node, layer):
self.nodes[node.idx] = node
self.layers[layer].append(node)
def add_edge(self, parent, child):
w = self.gen_weight()
idx = gen_name("edge-")
edge = Edge(idx, parent, child, w)
parent.add_outedge(edge)
self.edges.append(edge)
def add_layer(self):
place = random.randint(1,
len(self.layers) - 1)
layers = [[]] * (len(self.layers) + 1)
for i, l in enumerate(self.layers[:-1]):
layers[i] = l
layers[-1] = self.layers[-1]
layers[place], layers[-2] = layers[-2], layers[place]
self.layers = layers
def add_random_node(self):
# Generate random node and add it to the list
l = random.randint(1, len(self.layers) - 1)
n = gen_node(l)
self.add_node(n, l)
# Connect it to the layer above
target = random.choice(self.layers[l+1])
self.add_edge(n, target)
# Connect it to lower layer
source = random.choice(self.layers[l-1])
self.add_edge(source, n)
# if the source and target were connected
# put the new node in between them
for e in source.out_edges:
if e.child == target:
# Create new edge
source.disconnect(e.idx)
self.add_edge(source, n)
def add_random_edge(self, weight=False):
if not weight:
weight = gen_weight()
# Child layer
layer2 = random.randint(0, len(self.layers) - 2)
# Parent layer
layer1 = random.randint(0, layer2)
edge_idx = "{}-{}-{}".format(layer1,
layer2,
len(self.edges))
parent = random.choice(self.layers[layer1])
child = random.choice(self.layers[layer2])
edge = Edge(edge_idx, parent, child, weight)
parent.add_outedge(edge)
self.edges.append(edge)
# Add Input nodes, hidden nodes and an output node
# Each hidden node is connected to the output
# Each input node can be either connected to the hidden or output or both.
# Make sure each hidden node has at least one input node connected
def initialize(self):
# Add output node, calues between 0-1
output_node = Node('output', sigmoid)
self.add_node(output_node, 2)
# Add input nodes
input_nodes = []
for i, idx in enumerate(['input-x', 'input-y', 'input-r']):
n = Node(idx, random.choice(activation_functions))
self.add_node(n, 0)
# Add hidden nodes and connect to output
hidden_node = self.gen_node(1)
self.add_node(hidden_node, 1)
self.add_edge(hidden_node, output_node)
#Connect each input node to the hidden node and maybe to output
for n in self.layers[0]:
self.add_edge(n, hidden_node)
if random.choice([0, 1]) == 1:
self.add_edge(n, output_node)
def forward_propagate(self, x, y, r):
self.layers[0][0].add_input(x)
self.layers[0][1].add_input(y)
self.layers[0][2].add_input(r)
for l in self.layers:
for n in l:
for idx, e in n.out_edges.items():
e.propagate()
return self.layers[-1][0].propagate()
# Might never even do this :D
def backward_propagate():
raise NotImplementedError
if __name__=="__main__":
network = Network()
network.initialize(n_hidden=12)
for i, l in enumerate(network.layers):
for j, n in enumerate(l):
print(i, j, n)
for i, l in enumerate(network.layers):
for j, n in enumerate(l):
for e in n.out_edges:
print(e.parent, e.weight, e.child)
network.forward_propagate(0.1,0.2,0.3)
img_size = 256
image = np.zeros((img_size, img_size))
scale = 0.2
factor = img_size/scale
for i in range(img_size):
for j in range(img_size):
x = i/factor - 0.5 * scale
y = j/factor - 0.5 * scale
r = math.sqrt(x**2 + y**2)
image[i,j] = network.forward_propagate(x, y, r)
print(image)
|
8015a79c1bc20fdfd8b90719ce4e5efc5cf096d5 | Allard-Timothy/algorithm-design-and-analysis | /algorithm-design-and-analysis/Week3/min_cut.py | 1,887 | 3.796875 | 4 | """Your task is to code up and run the randomized contraction algorithm for the min cut problem
and use it on the above graph to compute the min cut (i.e., the minimum-possible number of crossing edges).
"""
from random import choice
from copy import deepcopy
def contract(v1, v2, G):
"""Contracts two vertices from random edge in graph G into single vertex
:param vert1: first vertex
:param vert2: second vertex
:param G: input graph
"""
G[v1].extend(G[v2]) # add v2's list to v1's
for adj_v in G[v2]: # look at every adjacent node of v2
new_l = G[adj_v]
for i in range(0, len(new_l)): # scan and swap v1 for v2
if new_l[i] == v2:
new_l[i] = v1
while v1 in G[v1]: # remove loop in v1
G[v1].remove(v1)
del G[v2] # remove v2 from graph
def find_min_cut(G):
"""Find the minimum cut in graph G using Karger's algorithm
:param G: input graph
"""
while len(G) > 2: # while more than two vertices in G
v1 = choice(list(G.keys())) # first random vertex
v2 = choice(G[v1]) # second random vertex
contract(v1, v2, G) # contract v2 into v1
return len(G.popitem()[1]) # pop item and return len, which is min cut
def run_find_mincut(cut_range, file_path):
"""Find the minimum cut in G using Karger's algorithm.
"""
f = open(file_path, 'r')
lines = f.readlines()
G = {int(line.split()[0]): [int(v) for v in line.split()[1:] if v] for line in lines if line}
min_cut = float("inf")
for i in range(cut_range):
curr = find_min_cut(deepcopy(G))
if curr < min_cut:
min_cut = curr
print "The min cut is:", min_cut
if __name__ == '__main__':
cut_range = ''
file_path = '/users/timallard/git_repo/coursera_design_analysis_algorithms/Week3/kargerMinCut.txt'
run_find_mincut(cut_range, file_path) |
df7f0c9091e1b9d37ef406f044cce34e81941050 | EnzDev/GiveMeSomeArtBaby | /utils.py | 557 | 3.984375 | 4 | def average(c1, c2, w=0.5):
'''Compute the weighted average of two colors. With w = 0.5 we get the average.'''
(r1, g1, b1) = c1
(r2, g2, b2) = c2
r3 = w * r1 + (1 - w) * r2
g3 = w * g1 + (1 - w) * g2
b3 = w * b1 + (1 - w) * b2
return (r3, g3, b3)
def rgb(r, g, b):
'''Convert a color represented by (r,g,b) to a string understood by tkinter.'''
u = max(0, min(255, int(128 * (r + 1))))
v = max(0, min(255, int(128 * (g + 1))))
w = max(0, min(255, int(128 * (b + 1))))
return '#%02x%02x%02x' % (u, v, w)
|
1958de37e9376c874b0b19feec831728fc4e6679 | Daniel-Benzion/codingbat_python | /logic-2/make_chocolate.py | 161 | 3.671875 | 4 | def make_chocolate(small, big, goal):
if goal > (big * 5): result = goal - (big * 5)
else: result = goal % 5
if small >= result: return result
return -1
|
56a4d56f8c9efc19cf201ba0fb688a2a46c55691 | Neriitox/Portfolio | /Missing Multipliers.py | 180 | 3.859375 | 4 | num = int(input("Times table: "))
step = int(input("Step: "))
for a in range(1, 13, step):
answer = a * num
print(f"{num} x [] = {answer}")
#Shows your time tables |
e812c365bde987674d46da2389b14c210021096f | sctu/sctu-ds-2019 | /1806101074赵贤雯/day20190423/test02.py | 239 | 3.625 | 4 | class Node:
def __init__(self,data,next):
self.data = data
self.next = None
# 有三个结点
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
# n1的下一个结点是n2
n1.next = n2
# n2的下一个结点是n3
n2.next = n3
|
455205c166f7eff829242ca90bca39cd88a62735 | meenakshisl/Cryptography | /Cryptography/AES/AES_ECB/padding.py | 1,029 | 4.0625 | 4 |
#----------functions to pad , unpad and check_padding---------
def unpad(cipher_text,block_size) :
#---------unpads parameter string after checking for padding---------
assert check_pad(cipher_text,block_size)=="Ok",check_pad(cipher_text,block_size)
ch=ord(cipher_text[-1])
plain_text=cipher_text[:-ch]
return plain_text
def pad(plain_text,block_size) :
#---------pads the string given as parameter------------------
tmp=block_size-(len(plain_text)%block_size) return plain_text+chr(tmp)*tmp
def check_pad(cipher_text,block_size) :
#----------checks for padding of the string-----------------
ch=ord(cipher_text[-1])
if ch > 16 : # if padding character is within the block range
r="Padding incorrect 1"
return r
else :
for i in range(ch) : #checks if all padded characters are same
if(cipher_text[(-i-1)]!=chr(ch)) :
r= "Padding incorrect 2"
else :
r="Ok"
return r
|
dbbf9e3b24b633a821fcf75acb3098d86c846dbc | oujieying/airlines_prices_ongoing | /airlines-sinkUtils/Jsonutils.py | 822 | 3.609375 | 4 | import json
class MyClass(object):
def __init__(self):
self.a = 2
self.b = 'bb'
if __name__ == '__main__':
# 创建MyClass对象
myClass = MyClass()
# 添加数据c
myClass.c = 123
myClass.a = 3
# 对象转化为字典
myClassDict = myClass.__dict__
# 打印字典
print(myClassDict)
# 字典转化为json
myClassJson = json.dumps(myClassDict)
# 打印json数据
print(myClassJson)
print("##############json转化为字典############")
# json转化为字典
myClassReBuild = json.loads(myClassJson)
# 打印重建的字典
print(myClassReBuild)
# 新建一个新的MyClass对象
myClass2 = MyClass()
# 将字典转化为对象
myClass2.__dict__ = myClassReBuild;
# 打印重建的对象
print(myClass2.a)
|
e1c5f070876f5079b14020ad2d568acf6d919151 | guiw07/leetCode | /448_FindAllNumbersDisappearedInAnArray.py | 931 | 3.953125 | 4 | """
448. Find All Numbers Disappeared in an Array
Given an array of integers where 1 <= a[i] <= n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
"""
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
arrayToCheck = [0] * (len(nums) + 1)
arrayResult = []
for i in range(0, len(nums)):
arrayToCheck[nums[i]] += 1
for i in range(1, len(arrayToCheck)):
if arrayToCheck[i] == 0:
arrayResult.append(i)
return arrayResult
print(findDisappearedNumbers("a",[4,3,2,7,8,2,3,1])) |
0813ecb0aa139633ad96ceb734e6fcf9bfc0e771 | DamianNery/Tecnicas-De-Programacion | /5Mayo/18/CalculadoraFechas.py | 1,179 | 4.0625 | 4 | #!/usr/bin/env python3
#Intentá hacer una calculadora para fechas. Podrías empezar con una que sume y
#reste fechas (año-mes-día) Se puede ir agregando otras funciones: (ej. sumar
#o restar teniendo en cuenta horario, etc.)
import datetime
def CalculadoraFechas():
dia1=int(input("dia1: "))
mes1=int(input("mes1: "))
anio1=int(input("anio1: "))
dia2=int(input("dia2: "))
mes2=int(input("mes2: "))
anio2=int(input("anio2: "))
operacion=str(input("s=suma r=resta: "))
fecha1=datetime.datetime(anio1,mes1,dia1)
fecha2=datetime.datetime(anio2,mes2,dia2)
if operacion=="s":
suma=(fecha1+fecha2)
print("La suma entre las fechas en años es: ",suma.days/30/365)
print("La suma entre las fechas en meses es: ",suma.days/30)
print("La suma entre las fechas en dias es: ",suma.days)
elif operacion=="r":
resta=(fecha1-fecha2)
print("La diferencia entre las fechas en años es: ",resta.days/30/365)
print("La diferencia entre las fechas en meses es: ",resta.days/30)
print("La diferencia entre las fechas en dias es: ",resta.days)
else:
pass
CalculadoraFechas()
|
15f2f09ec701d96cef8bf30a9df794fff4cb7ded | KKhushhalR2405/AlgoNOOB | /product-sum.py | 221 | 3.59375 | 4 | def productsum(arr,l,s):
for i in arr:
if type(i) is list:
s+=productsum(i,l+1,0)
else:
s+=i
return s*l
arr=[5,2,[7,-1],3,[6,[-13,8],4]]
print(productsum(arr,1,0)) |
e3825da8ba45dc086452544e7de29f2e3b98d4c7 | ming-log/MetaClass | /03 自定义元类.py | 1,616 | 3.765625 | 4 | # __author__:"Ming Luo"
# date:2020/9/28
# 原始类
class fun(object):
age = 18
gender = "男"
# 假想一个很傻的例子,你决定在你的模块里所有的类的属性都应该是大写形式。
# 如何通过元类来实现
def upper_all_attr(class_name, class_parent, class_attr):
for k, v in class_attr.items():
if not k.startswith("__"):
del class_attr[k]
class_attr[k.upper()] = v
return type(class_name, class_parent, class_attr)
class func1(object, metaclass=upper_all_attr): # metaclass:指定元类, 默认为type
age = 18
gender = "男"
# 真正的class来当做元类。
class upper_attr(type):
def __new__(cls, class_name, class_parent, class_attr):
for k, v in class_attr.items():
if not k.startswith("__"):
del class_attr[k]
class_attr[k.upper()] = v
return type(class_name, class_parent, class_attr)
class func2(object, metaclass=upper_attr):
age = 18
gender = "男"
# 采用type重写
def __new__(cls, class_name, class_parent, class_attr):
print(class_attr)
for k, v in class_attr.items():
if not k.startswith("__"):
del class_attr[k]
class_attr[k.upper()] = v
print(class_attr)
return type(class_name, class_parent, class_attr)
upper_attr = type("upper_attr", (type, ), {"__new__": __new__})
class func3(object, metaclass=upper_attr):
age = 18
gender = "男"
# 就元类本身而言,它们其实是很简单的:
# 1. 拦截类的创建
# 2. 修改类
# 3. 返回修改之后的类
|
9b25e755d3c30974d81a9581534ddfcd24d125a8 | Aasthaengg/IBMdataset | /Python_codes/p03698/s351814909.py | 142 | 3.53125 | 4 | S = input()
tmp = []
ans = "yes"
for i in range(len(S)):
if (S[i] in tmp):
ans = "no"
break
else:
tmp.append(S[i])
print(ans) |
7f7f6cc5e3489c7f84137f8e5c2a2b564c1c9744 | Flor246/PythonFlor | /Modulo1/scripts/ingreso_datos.py | 483 | 3.90625 | 4 | # control + n - > abro un nuevo file
# control + s -> guardar cambios
# Terminal: cls -> limpiar terminal
# ejecutar python : python nombre_archivo.py
# 1. Solicitando numero
x = int(input('Por favor ingrese un dato numerico: '))
# 2. elevando numero al cubo
potencia = x ** 3
# 3. Mostrando resultado
# print('El numero elevado al cubo es : ' + str(x))
# print(f'El numero {x} elevado al cubo es: {potencia}')
print('El numero {} elevado al cubo es: {}'.format(x, potencia))
|
3de62f716e23bfed25dcc134efdd8ddade184667 | UJurkevica/python-course | /homework/week1/exercise3.py | 414 | 4.40625 | 4 | #3a
floating_var = 8.98
integer_var = 4
string_var = 'Jam'
#3b
print(f'This item is an integer: {floating_var.is_integer()}')
#test if variable is integer
print(f'Ratio of this integer is: {integer_var.as_integer_ratio()}')
#it provides ratio for the variable (in this case for the integer)
print(f'Given variable begins with a letter J : {string_var.startswith("J")}')
#checks if variable begins with given value |
8954621d65258d4dac39d9aced7771b069c143d8 | 87chevytruck/All_Labs | /Python and Network Labs/Performance Labs/Lab5A_Packaged/Calculator_Functions/Lab5A_definitions.py | 2,138 | 3.875 | 4 | """ Ricky Smith, Lab5A: Modules & Packages, 12 Sep 2018
Lab5A Definitions
"""
# def multi function
def multi(x, y):
return x * y
# def divide function
def divide(x, y):
return x / y
# def power function
def power(x, y):
return x ** y
# def fibonacci function (itterative version for fast result)
def fib(n):
a = 0
b = 1
c = 0
for i in range(n):
if c < 100:
a, b = b, a + b
c += 1
return a
# def factorial function
def fac(userNum):
staticNum = userNum
factNum = userNum
# loops through while userNum is greater than 1
## (userNum changes value by -1 each loop)
while userNum > 1:
userNum -= 1
factNum *= userNum
return factNum
# Input validation for integer
def inputInt(n):
while True:
try:
inputNum = int(raw_input(n))
except ValueError:
print("ERROR: Input is not a whole integer, try again.")
else:
return inputNum
break
# Input validation for float
def inputFloat(n):
while True:
try:
inputNum = float(raw_input(n))
except ValueError:
print("ERROR: Input is not a float, try again.")
else:
return inputNum
break
def printTop():
print("\n******************************")
print("* *")
print("* *")
# print("* *")
def printMid():
print("* *")
print("* *")
def printBot():
print("* *")
print("* *")
print("******************************\n")
# variable evaluation function
def equals(n):
"""Handles the math for the equation when the user presses
equals
"""
#The try except here catches if the user inputs anything that
#wouldn't make sense IE putting letters in
try:
total = str(eval(n))
return total
except:
print("ERROR ERROR ERROR")
|
a4ace0e0e1d63b53b1612bc70d725f6e03e8fa34 | DanielSoaresFranco/Aulas.py | /exercícios/ex094.py | 1,161 | 3.734375 | 4 | mulheres = []
pessoas = []
pessoa = {}
s = m = 0
while True:
pessoa.clear()
pessoa['nome'] = str(input('Nome: ')).capitalize()
pessoa['idade'] = int(input('Idade: '))
pessoa['sexo'] = str(input('Sexo: ')).strip().lower()[0]
while pessoa['sexo'] not in 'mf':
print('Erro! Digite M ou F.')
pessoa['sexo'] = str(input('Sexo: ')).strip().lower()[0]
cont = str(input('Quer continuar? ')).strip().lower()[0]
s += pessoa['idade']
pessoas.append(pessoa.copy())
if pessoa['sexo'] == 'f':
mulheres.append(pessoa['nome'])
if cont == 'n':
print('-=' * 40)
break
while cont not in 'sn':
print('Erro! Responda S ou N.')
cont = str(input('Quer continuar? ')).strip().lower()[0]
m = s / len(pessoas)
print(f"""- O grupo tem {len(pessoas)} pessoas
- A média de idade é de {m:.0f} anos
- As mulheres cadastradas foram {mulheres}
-lista das pessoas que estão acima da média de idade: """)
for a in range(0, len(pessoas)):
if pessoas[a]['idade'] >= m:
for d, e in pessoas[a].items():
print(f'{d} = {e},', end=' ')
print()
print('<<ENCERRADO>>')
|
d06067d919884f5cd2246ab09159f126f929b1b5 | MardanovTimur/propeller | /main.py | 574 | 3.609375 | 4 | import platform, os
from spell_checker import search
from trie import Trie
WORDS_PATH = "/usr/share/dict/words"
if platform.system().lower() in 'linux':
WORDS = os.path.abspath(WORDS_PATH)
else:
raise SystemError("linux devices only")
def create_tree(words: str=WORDS_PATH):
tree = Trie()
file = open(words, 'r')
list(map(lambda w: tree.insert(w), file.readlines()[:5000]))
file.close()
return tree
if __name__ == "__main__":
tree = create_tree()
word = input("type the word:")
results = search(tree, word)
print(results)
|
33a83a7f4d3654dd19264056ca5de211d5b7c0cf | ChanningC12/PythonLearning | /Python_Codecademy/List and Function.py | 1,070 | 4.03125 | 4 | #battleship
board=[]
for i in range(0,5):
board.append(["0"]*5)
def print_board(board):
for row in board:
print (" ".join(row))
#Hide
from random import randint
board=[]
for i in range(0,5):
board.append(["0"]*5)
def print_board(board):
for row in board:
print (" ".join(row))
def random_row(board):
return randint(0,len(board)-1)
def random_col(board):
return randint(0,len(board)-1)
ship_row= random_row(board)
ship_col= random_col(board)
guess_row=int(input("Guess Row: "))
guess_col=int(input("Guess Col: "))
print (ship_row)
print (ship_col)
for turn in range(4):
print ("Turn",turn+1)
if guess_row==ship_row and guess_col==ship_col:
print ("Congrats!")
else:
print ("You missed my battleship!")
if guess_row not in range(5) or guess_col not in range(5):
print ("Oops!")
elif board[guess_row][guess_col]:
print ("You guessed one that one already")
else:
print ("You missed my battleship!")
board[guess_row][guess_col]="X"
print (print_board(board))
if turn==3:
print ("Game Over")
|
23ffb66fdd98943463fc3ec60611aae6ceeaec31 | ZhengyangXu/LintCode-1 | /Python/Implement Queue by Two Stacks.py | 986 | 4.25 | 4 | """
As the title described, you should only use two stacks to implement a queue's actions.
The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
"""
class Queue:
def __init__(self):
# use to hold the newly inserted element
self.stack1 = []
# use as a queue
self.stack2 = []
def push(self, element):
# write your code here
self.stack1.append(element)
def top(self):
# write your code here
# return the top element
if len(self.stack2) == 0:
while self.stack1:
self.stack2.append(self.stack1[-1])
self.stack1.pop()
return self.stack2[-1]
def pop(self):
# write your code here
# pop and return the top element
element = self.top()
self.stack2.pop()
return element
|
751bf0dd19d4c77093ddee2e9d80226cb1ee499b | dengdaiyemanren/python | /yield.py | 704 | 3.59375 | 4 | # -*- coding: utf8 -*-
def fab(max):
n,a,b = 0,0,1
while n < max:
print b
a,b = b,a+b
n = n +1
#fab(5)
def fabx0(max):
n,a,b = 0,0,1
L = []
while n < max:
L.append(b)
a,b = b , a+b
n = n + 1
return L
def fab01(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b = b,a+b
n = n +1
for xx in fab01(5):
print xx
f = fab01(5)
print f.next()
## 使用 isgeneratorfunction 判断 ##
from inspect import isgeneratorfunction
print isgeneratorfunction(fab01)
import types
print isinstance(fab01, types.GeneratorType)
print isinstance(fab01(5), types.GeneratorType)
|
3b05fa83a9c2fba61761fa7208a9e17076dc8b97 | a-morev/Python_Algos | /Урок 1. Практическое задание/task_4.py | 1,844 | 3.71875 | 4 | """
Задание 4. Написать программу, которая генерирует в указанных пользователем границах:
случайное целое число;
случайное вещественное число;
случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f', то вводятся эти символы.
Программа должна вывести на экран любой символ алфавита от 'a' до 'f' включительно.
Подсказка:
Нужно обойтись без ф-ций randint() и uniform()
Использование этих ф-ций = задание не засчитывается
Функцию random() использовать можно
Опирайтесь на пример к уроку
"""
from random import random
print('Генерация случайного целого числа')
LEFT = int(input('Минимальная граница: '))
RIGHT = int(input('Максимальная граница: '))
NUMB = int(random() * (RIGHT - LEFT + 1)) + LEFT
print(NUMB)
print('Генерация случайного вещественного числа')
LEFT = float(input('Минимальная граница: '))
RIGHT = float(input('Максимальная граница: '))
NUMB = random() * (RIGHT - LEFT) + LEFT
print(round(NUMB, 3))
print('Генерация случайного символа')
LEFT = ord(input('Начальный символ: '))
RIGHT = ord(input('Конечный символ: '))
SYMBOL = int(random() * (RIGHT - LEFT + 1)) + LEFT
print(chr(SYMBOL))
|
b8dbdb5071bccdb9473b4730461d831684b291cc | 01090841589/ATM | /그외/08 4주/타일 붙이기.py | 398 | 3.578125 | 4 | import sys
sys.stdin = open("타일붙이기.txt")
def inf_sec(N, num):
global total
if N == 0:
total += num
return
if N >= 1:
inf_sec(N-1, num)
if N >= 2:
inf_sec(N-2, num*2)
if N >= 3:
inf_sec(N-3, num)
T = int(input())
for tc in range(1, T+1):
N = int(input())
total = 0
inf_sec(N, 1)
print('#{} {}'.format(tc, total)) |
f961155622dd24fcc38cd3e5d9046a876098caa4 | nguyenbac5299/LearnPython | /condition/while.py | 907 | 3.8125 | 4 | i = 0
while i < 10:
print(i)
i += 1
else:
print('end')
i = 0
while i < 10:
print(i)
i += 1
break
else:
print('end') # not execute because has break
# while True:
# response = input('Say something: ')
# if response == 'bye':
# break
for i in [1, 2, 3]:
if i == 2:
continue
print(i)
# exercise
picture = [
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0]
]
for image in picture:
for pixel in image:
if pixel:
print('*', end='')
else:
print(' ', end='')
print('')
# exercise: Check for duplicates in list
my_list = ['a', 'b', 'c', 'b', 'm', 'n', 'n']
duplicates=[]
for i in my_list:
if (my_list.count(i)>1) and (i not in duplicates):
duplicates.append(i)
print(duplicates)
|
d04806c75e39147c5f663d28a5e2a578607daa35 | taufanmw/repo01 | /tipedatalist.py | 844 | 3.640625 | 4 | #tipe data list
#tipe data sederhana
anak1 = 'Eko'
anak2 = 'Dwi'
anak3 = 'Tri'
anak4 = 'Catur'
print(anak1)
print(anak2)
print(anak3)
print(anak4)
#tipe data array
print('\ntipe data array')
anak = ['Eko', 'Dwi', 'Tri', 'Catur']
print(anak)
#kalau menambahkan variabel baru
print('\ntambah var baru')
anak.append('Lima')
print(anak)
#sapa anak ke dua (urutan angka di pemrograman dimulai dari angka 0)
print('\nsapa anak ke 2')
print(f'Halo {anak[1]} ! ')
#cara menyapa semua anak
print('\nsapa semua anak cara gampang')
for a in anak:
print(f'Halo {a} ! ')
#sapa cara ribet
print('\nsapa anak cara ribet')
for a in range(0, len(anak)):
print(f'hai {anak[a]}')
#dengan memakai ribet dgn nomor
print('\nsapa ribet dengan nomor')
for a in range(0, len(anak)):
print(f'{a+1}. Halo {anak[a]}')
#len = panjang variabel / array |
dbb025e2c3efe62028c5d5bdf2e8df50154cf3bb | arpitbbhayani/recursion | /03-sum-of-digits.py | 384 | 4.21875 | 4 | #
# Perform sum of digits using recursion
# sum_digits(123) = 1 + 2 + 3 = 6
#
def _sod(number: int) -> int:
if number == 0:
return 0
units_digit = number % 10
remaining_number = number // 10
return units_digit + _sod(remaining_number)
def sum_digits(number: int) -> int:
return _sod(number)
if __name__ == '__main__':
print(sum_digits(12321))
|
0b7cc39e8150b2c13b86fc1f211569702bf7d50c | shifty049/LeetCode_Practice | /Medium/652. Find Duplicate Subtrees.py | 1,187 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
self.ans = []
self.visited = {}
def helper(r):
if r:
left = helper(r.left)
right = helper(r.right)
record = '.'.join([str(r.val), left, right])
if record not in self.visited:
self.visited[record] = 1
else:
self.visited[record] += 1
if self.visited[record] == 2:
self.ans.append(r)
return record
else:
return ''
helper(root)
return self.ans
#Runtime: 56 ms, faster than 98.42% of Python3 online submissions for Find Duplicate Subtrees.
#Memory Usage: 22.1 MB, less than 71.51% of Python3 online submissions for Find Duplicate Subtrees.
#Fu-Ti, Hsu
#shifty049@gmail.com |
e5bbfbc97e8b4359a7b74da2af777cf269722939 | saiwho/learn-python-the-hardway | /ex34.py | 345 | 3.875 | 4 | animals = ['bear', 'python3.6', 'peacock', 'kangaroo', 'whale', 'platypus']
print("\nAll the list members:")
print(animals)
print("\nLast item of the list:")
print(animals[-1])
print("\nFirst two items of the list:")
print(animals[0:3])
print("\nItems from 2 to last but one:")
print(animals[1:-1])
print("\nLast two items")
print(animals[4:])
|
ca81ebaf74aeaf0b8f764ad4542a9d7d1b1ae1a2 | 127-vitor/python_fundamentals | /Aulas/estrutura_repetição.py | 1,192 | 3.828125 | 4 | # -*- coding: UTF-8 -*-
# from __future__ import print_function
# x = 1
# while x < 10:
# print(x)
# x += 1
# print('fim do while')
# x = 1
# while True:
# print(x)
# x +=1
# usuários = dict(renato='ninja12', vitor='ninjutsu34', lucas='kinjutsu87', lia='doujutsu09', erik='taijutsu123')
# for users in usuários:
# print(users)
# bloqueados = []
# tentativas = 0
# while True:
# login = input('Digite o seu usuário: ')
# if login in usuários:
# senha = input('Digite sua senha: ')
# if senha == usuários[login]:
# print('login efetuado')
# break
# elif tentativas < 3:
# print('Senha incorreta!')
# tentativas += 1
# continue
# else:
# print('Usuário bloqueado, contate o administrador')
# bloqueados.append(login)
# usuários.pop(login)
# break
# else:
# print('Usuário não cadastrado')
# continue
# print(f'usuários: {usuários}')
# print(f'usuários bloquados: {bloqueados}')
# frutas = ['uva', 'banana', 'laranja']
# for i, f in enumerate(frutas):
# print(i, f)
|
43e1b48dc194eadba3cd700770169ba41236c11d | RamyaRamasubramaniyan/PythonProjects | /HackerRankSolutions/ShopperDelight.py | 3,627 | 4.09375 | 4 | # HackerRank - Shopper's Delight
# A Shopaholic wants to buy a pair of jeans, a pair of shoes, a skirt, and a top but has a limited budget in dollars. Given different pricing options for each product, determine how many options our customer has to buy 1 of each product. You cannot spend more money than the budgeted amount.
#
# Example
# priceOfJeans = [2, 3]
# priceOfShoes = [4]
# priceOfSkirts = [2, 3]
# priceOfTops = [1, 2]
# budgeted = 10
#
# The customer must buy shoes for 4 dollars since there is only one option. This leaves 6 dollars to spend on the other 3 items. Combinations of prices paid for jeans, skirts, and tops respectively that add up to 6 dollars or less are [2, 2, 2], [2, 2, 1], [3, 2, 1], [2, 3, 1]. There are 4 ways the customer can purchase all 4 items.
#
# Function Description
#
# Complete the getNumberOfOptions function in the editor below. The function must return an integer which represents the number of options present to buy the four items.
#
# getNumberOfOptions has 5 parameters:
# int[] priceOfJeans: An integer array, which contains the prices of the pairs of jeans available.
# int[] priceOfShoes: An integer array, which contains the prices of the pairs of shoes available.
# int[] priceOfSkirts: An integer array, which contains the prices of the skirts available.
# int[] priceOfTops: An integer array, which contains the prices of the tops available.
# int dollars: the total number of dollars available to shop with.
#
# Constraints
#
# 1 ≤ a, b, c, d ≤ 103
# 1 ≤ dollars ≤ 109
# 1 ≤ price of each item ≤ 109
# Note: a, b, c and d are the sizes of the four price arrays
import itertools, bisect
def getNumberOfOptions(priceOfJeans, priceOfShoes, priceOfSkirts, priceOfTops, budgeted):
# Write your code here
priceOfJeansAndSkirts = [i + j for i, j in itertools.product(priceOfJeans, priceOfSkirts)]
priceOfShoesAndTops = [i + j for i, j in itertools.product(priceOfTops, priceOfShoes)]
result = 0
cost_limit = 0
priceOfJeansAndSkirts.sort()
priceOfShoesAndTops.sort()
for price in priceOfJeansAndSkirts:
remaningDollar = budgeted - price
if price >= budgeted:
break
trial_count = bisect.bisect_right(priceOfShoesAndTops, remaningDollar)
result += trial_count
return result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
priceOfJeans_count = int(input().strip())
priceOfJeans = []
for _ in range(priceOfJeans_count):
priceOfJeans_item = int(input().strip())
priceOfJeans.append(priceOfJeans_item)
priceOfShoes_count = int(input().strip())
priceOfShoes = []
for _ in range(priceOfShoes_count):
priceOfShoes_item = int(input().strip())
priceOfShoes.append(priceOfShoes_item)
priceOfSkirts_count = int(input().strip())
priceOfSkirts = []
for _ in range(priceOfSkirts_count):
priceOfSkirts_item = int(input().strip())
priceOfSkirts.append(priceOfSkirts_item)
priceOfTops_count = int(input().strip())
priceOfTops = []
for _ in range(priceOfTops_count):
priceOfTops_item = int(input().strip())
priceOfTops.append(priceOfTops_item)
budgeted = int(input().strip())
result = getNumberOfOptions(priceOfJeans, priceOfShoes, priceOfSkirts, priceOfTops, budgeted)
fptr.write(str(result) + '\n')
fptr.close()
# SAMPLE INPUT1 : 2 2 3 1 4 1 2 3 1 2 3 10
# SAMPLE OUTPUT1 : 3
# SAMPLE INPUT2 : 1 4 3 3 4 1 2 3 2 1 4 12
# SAMPLE OUTPUT 2: 2
# SAMPLE INPUT 3 : 1 1 1 4 1 3 1 1 3
# SAMPLE OUTPUT 3 : 0
|
222815a5462a828a7e712c35693d713e2f7a885a | BC-csc226-masters/a03-fall-2021-master | /a03_emilbekuuluy.py | 4,223 | 3.640625 | 4 | ######################################################################
# Author: Yryskeldi Emilbek uulu
# Username: emilbekuuluy
#
# Assignment: A03: Fully Functional Gitty Psychedelic Robotc Turtles
# Purpose: To continue practicing creating and using functions, more practice on using the turtle library,
# learn about how computers represent colors,
# learn about source control and git.
######################################################################
# Acknowledgements:
# # I heavily relied on the code modified by Dr. Jan Pearce. Original code:
# http://openbookproject.net/thinkcs/python/english3e/hello_little_turtles.html
# I also modified a code to create the fire flame. Original code:
# https://learn.wecode24.com/animation-with-turtle-graphics/
#
#
# licensed under a Creative Commons
# Attribution-Noncommercial-Share Alike 3.0 United States License.
#################################################################################
import turtle # allows us to use the turtles library
def make_a_tree(pos1, pos2):
"""
Draws a beautiful tree with green leaves
:param pos1: x coordinate
:param pos2: y coordinate
:return: None
"""
# Draws the first tree "triangle":
shape = turtle.Turtle()
wn = turtle.Screen()
shape.speed(9)
shape.penup()
shape.setpos(pos1, pos2)
shape.pendown()
shape.color("#32CD32")
shape.begin_fill()
for i in range(3):
shape.forward(150)
shape.left(120)
shape.end_fill()
# Draws the second tree "triangle":
shape.penup()
shape.left(90)
shape.forward(120)
shape.right(90)
shape.forward(20)
shape.pendown
shape.color("#7CFC00")
shape.begin_fill()
for i in range(3):
shape.forward(110)
shape.left(120)
shape.end_fill()
# Draws the tree branch:
shape.penup()
shape.right(90)
shape.forward(120)
shape.left(90)
shape.forward(45)
shape.color("#8B4513")
shape.begin_fill()
for i in range(2):
shape.forward(20)
shape.right(90)
shape.forward(40)
shape.right(90)
shape.end_fill()
shape.hideturtle()
def some_text(text, pos1, pos2):
"""
Writes a slogan in the middle
:param text: Text that shows up on screen
:param pos1: x coordinate of the text
:param pos2: y coordinate of the text
:return: None
"""
shape = turtle.Turtle()
shape.color("#FF0000")
shape.size = 30
shape.penup()
shape.setpos(pos1, pos2)
shape.pendown()
shape.hideturtle()
shape.write(text, move=False, align='center', font=("Georgia",20, ("bold", "normal")))
def background_for_text(pos1, pos2):
"""
Gives the text a readable background
:param pos1: x coordinate
:param pos2: y coordinate
:return: None
"""
shape = turtle.Turtle()
shape.color("#F5F5F5")
shape.penup()
shape.setposition(pos1, pos2)
shape.pendown()
shape.begin_fill()
for i in range(2):
shape.forward(226)
shape.left(90)
shape.forward(70)
shape.left(90)
shape.end_fill()
shape.hideturtle()
def fires_and_flames(pos1, pos2):
"""
Creates a moving fire flame, representing the destruction of the Amazon forest
:param pos1: x coordinate of the fire flame
:param pos2: y coordinate
:return: None
"""
screen = turtle.Screen()
shape = turtle.Turtle()
screen.tracer(0)
screen.addshape("fireball.gif")
shape.speed(0.01)
shape.shape("fireball.gif") # now set the turtle's shape to it
shape.penup()
shape.goto(pos1, pos2)
while True:
screen.update()
shape.forward(0.1)
if shape.position() == (-100, -50):
break
def main():
"""
The "boss" function - consolidates all functions together, and determines and alters background pictures.
:return: None
"""
wn = turtle.Screen()
wn.bgpic("cool_background.gif")
make_a_tree(-250, -127)
make_a_tree(-170,-135)
make_a_tree(-200, -140)
background_for_text(-30, 50)
wn.bgpic("forest_fire.gif")
some_text("STOP AMAZON \n DESTRUCTION!", 80, 50)
fires_and_flames(-170, -50)
wn.exitonclick()
main()
|
eef42a182ff592e498fc36c4b9e869dfa6548e5e | vcatafesta/chili | /python/sena.py | 447 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
num1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
num2 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
# random.shuffle(num2)
sorteados = "Dezenas sorteadas: "
i = 0
while i < 5:
dezena = "00"
while dezena == "00":
random.shuffle(num1)
random.shuffle(num2)
dezena = num1[0] + num2[0]
sorteados += dezena + " "
i += 1
print(sorteados)
|
b668affd63049e4d1f8c6688ef5bf60ce042f432 | Aasthaengg/IBMdataset | /Python_codes/p03289/s196878305.py | 98 | 3.96875 | 4 | from re import match
if match("^A[a-z]+C[a-z]+$", input()):
print('AC')
else:
print('WA') |
f3778a4abfdeed4145bc6104d1f6ecfb5b2be18d | tglanz/codes | /python/tests/test_heap.py | 999 | 3.546875 | 4 | from structures.heap import Heap
def test_default_constructor():
heap = Heap()
assert heap is not None, "shouldn't be None"
def test_min_heap_builder():
heap = Heap.create_min_heap()
assert heap is not None, "shouldn't be None"
def test_max_heap_builder():
heap = Heap.create_min_heap()
assert heap is not None, "shouldn't be None"
def test_descending_sort():
# arrange
array = [4, 2, 7, 1, 3]
heap = Heap.create_min_heap()
# act
for value in array:
heap.add(value)
for _ in array:
heap.pop()
# assert
assert all([x == y for (x, y) in zip(heap.values, sorted(array, key=lambda x: x * -1))])
def test_ascending_sort():
# arrange
array = [4, 2, 7, 1, 3]
heap = Heap.create_max_heap()
# act
for value in array:
heap.add(value)
for _ in array:
heap.pop()
# assert
assert all([x == y for (x, y) in zip(heap.values, sorted(array, key=lambda x: x))]) |
e2e0781f43f432f0bdcabc27b7af9b3349b20f2b | devendraingale2/PythonPrograms | /pattern26.py | 192 | 3.515625 | 4 | '''
+ = + =
+ = +
+ =
+
'''
a="+"
b="="
for i in range(4,0,-1):
for j in range(i):
if j%2!=0:
print(a,end=" ")
else:
print(b,end=" ")
print()
|
0917b77f509c8c2841c64933a38613cf091be7e3 | mwinn53/Euler | /Problem 4 - Largest Palindrome Product/Problem4.py | 1,944 | 4.28125 | 4 | # coding=utf-8
"""
PROBLEM 4:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers
is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
APPROACH:
(1) Iterate through two ranges, each from 100-999. Compute the product of each pair.
(2) Determine if each product is a palindrome. If not, continue to the next product pair
(3) If the product is a palindrome, compare it to the currently stored highest palindrome. If it's greater than,
store the value (e.g., overwrite) in the highest palindrome variable. If not, continue to the next product pair
(4) Return the highest palindrome variable
"""
import time
def is_palindrome(s):
'''
Evaluates whether a string is a palindrome
:param s: A string
:return: True (is palindrome) or False (is not palindrome)
'''
s = str(s)
start = 0
end = len(s) - 1
while start < end:
if s[start] != s[end]:
return False
start = start + 1
end = end - 1
return True
def main():
## Testing the is_palindrome function
# testlist = [9009, 10101, 3456, 34567, 'moon', 'noob', 'noon']
# for item in testlist:
# print 'Testing palindrome: {0} is {1}'.format(item, is_palindrome(item))
#
range_start = 100
range_stop = 999
max_palindrome = 0
for i in range(range_start, range_stop+1):
for j in range(range_start, range_stop+1):
product = i * j
test = is_palindrome(product)
if test:
print 'Product of {0}*{1} = {2} [{3}\t{4}]'.format(i, j, product, test, max_palindrome)
if product > max_palindrome:
max_palindrome = product
# time.sleep(1)
print 'Process complete. Max Palindrome is {0}'.format(max_palindrome)
if __name__ == '__main__':
main()
|
772c39c84eb4a4265db3fd9940ef5ae2f05813a3 | Youngwook-Jeon/python-ds-algos | /ds/QueueWithCapacity.py | 2,046 | 4.1875 | 4 | class Queue:
def __init__(self, max_size):
self.items = max_size * [None]
self.max_size = max_size
self.start = -1
self.top = -1
def __str__(self):
values = [str(x) for x in self.items]
return ' '.join(values)
def is_full(self):
if self.top + 1 == self.start:
return True
elif self.start == 0 and self.top + 1 == self.max_size:
return True
else:
return False
def is_empty(self):
if self.top == -1:
return True
else:
return False
def enqueue(self, value):
if self.is_full():
return "The queue is full"
else:
if self.top + 1 == self.max_size:
self.top = 0
else:
self.top += 1
if self.start == -1:
self.start = 0
self.items[self.top] = value
return "The element is inserted at the end of Queue"
def dequeue(self):
if self.is_empty():
return "There is not any element in the Queue"
else:
first_element = self.items[self.start]
start = self.start
if self.start == self.top:
self.start = -1
self.top = -1
elif self.start + 1 == self.max_size:
self.start = 0
else:
self.start += 1
self.items[start] = None
return first_element
def peek(self):
if self.is_empty():
return "There is not any element in the Queue"
else:
return self.items[self.start]
def delete(self):
self.items = self.max_size * [None]
self.top = -1
self.start = -1
if __name__ == '__main__':
custom_queue = Queue(3)
custom_queue.enqueue(1)
custom_queue.enqueue(2)
custom_queue.enqueue(3)
custom_queue.dequeue()
print(custom_queue)
print(custom_queue.is_full()) |
d2e2351c7f006ebdf83a5719b8205d0bcdae9989 | mchlstckl/blog | /PrimusNaivus/PrimusNaivusPy.py | 426 | 3.71875 | 4 | import time
def is_prime(x, primes):
return not any(x % p == 0 for p in primes)
def find_primes(index):
primes = []
candidate = 2
while len(primes) < index:
if is_prime(candidate, primes):
primes.append(candidate)
candidate += 1
return primes
# warm-up
find_primes(500)
tic = time.clock()
primes = find_primes(5555)
toc = time.clock() - tic
print "Elapsed time: ", str(toc * 1000), "msecs"
print primes.pop()
|
38521c500ab6a95fad685ae48af6fe10e021c707 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/2694.py | 685 | 3.515625 | 4 | tests = int(raw_input())
for test in range(1, tests+1):
count = 0
arr, k = raw_input().split(" ")
arr = list(arr)
k = int(k)
index = 0
while index+k-1 < len(arr):
if arr[index] == '-':
count += 1
for i in range(index, index+k):
if arr[i] == '+':
arr[i] = '-'
else:
arr[i] = '+'
#print arr, arr[index]
index += 1
while index < len(arr):
if arr[index] == "-":
print "Case #%s: IMPOSSIBLE"%(str(test))
break
index += 1
if index == len(arr):
print "Case #%s: %s"%(str(test), str(count))
|
87520c6b5544b678bfe817b48435658c72a15b5d | Htrams/Leetcode | /two_sum.py | 649 | 3.65625 | 4 | # My Rating = 6
# https://leetcode.com/problems/two-sum/
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# You can return the answer in any order.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
record={}
arrLen=len(nums)
for i in range(arrLen):
if target-nums[i] in record:
return [record[target-nums[i]],i]
else:
record[nums[i]]=i
|
808f7e1ab95187468e9904ea83525b673ffe16db | enio-infotera/VernamCipher | /py/encrypt.py | 441 | 3.640625 | 4 | #
#
# Use: encrypt("hello", "XMCKL")
# => "eqnvz"
#
#
def encrypt(st, key):
if len(st) != len(key):
return "Text and Key have to be the same length."
alphabet = list("abcdefghijklmnopqrstuvwxyz")
nText = []
kText = []
for i in range(len(st)):
nText.append(alphabet.index(st[i].lower()))
kText.append(alphabet.index(key[i].lower()))
out = ""
for i in range(len(nText)):
out += alphabet[(nText[i] + kText[i]) % 26]
return out;
|
39558bfb792f6e0627e0237fe7051e0f1979b305 | JavierCamposCuesta/repoJavierCampos | /1ºDaw/ProgramacionPython/Python/NumerosPrimos/Primos.py | 862 | 3.75 | 4 | '''
Created on 11 Nov 2020
@author: estudiante
'''
'''Esta funcion devueove True si el valor introducido como argumento es un numero primo y False en caso contrario'''
'''Crea un programa que pida al usuario un entero mayor que 0 y muestre por la saida estanr todos los numeros primos
comprendidos entre el numero 1 y el facilitado por el usuario. Devuelve los resultados en una estructura de lista y haz uso
de la funcion desarrollada previamente'''
def esNumeroPrimo(numero):
for i in range(2, numero):
if numero%i==0:
return False
return True
def pideNumeros(number):
lista=[]
for i in range(1, number+1):
if esNumeroPrimo(i):
lista.append(i)
print(lista)
pideNumeros(int(input("Introduce un numero para saber si es primo")))
|
cabf4b5032463878f9dcce1cbb9ab5a891011ca6 | Zlstg/py | /廖雪峰基础知识/1.变量.py | 570 | 3.609375 | 4 | #一个变量存储一个值
message = "bixu,hello word!"
print(message)
#一个变量存储一个值,可以任何时候改变这个值
message = "chouxifu"
print(message)
message = "xifujiudezou"
print(message)
'''
变量名只能包含字母,数字和下划线。且只能以字母或下划线开头。
空格不允许出现在变量名中。
不能用Python关键字作为变量名。
变量名应当是有意义的。不能过短或过长。
小心使用小写的l和大小的O,容易与1和0混淆。
'''
print("xifushi")
zl = "pangzi"
print("xifushi:",zl) |
965cc00c38e894736ad19e0fb3cfa44b2f104e5b | PFurtak/PythonExerciseSetOne | /madlib.py | 948 | 3.546875 | 4 | # prompt user for inputs to place inside of a madlib
adjective_one = input("Please provide an adjective. ")
place_one = input("Please provide a city name. ")
fluid_one = input("Please name a type of fluid. ")
martial_arts_movie = input("Please provide your favorite martial arts movie. ")
print("It was a " + adjective_one + " showdown between the competing dojos. The red clan and the blue clan had been at war for centuries. This fight took place in " +
place_one + ", ""and much " + fluid_one + " was spilled. Only members of the red clan came out alive. They will live to do " + martial_arts_movie + " style kata's another day.")
# Sentance template:
# "It was a fierce showdown between the competing dojos. The red clan and the blue clan had been at war for centuries. This fight took place in Tokyo, and much blood was spilled. Only members of the red clan came out alive. They will live to do bloodsport style kata's another day."
|
0c18a5a1c0f6a1c709cea2d08a244b0d4afc2acc | pdruck/Name-Generator | /NameGenerator.py | 5,280 | 4.15625 | 4 | # opens a file that contains a list of either male or female names
def openFile(gender):
names_in_file = []
if(gender == 'M' or gender == 'MALE'):
# opens a list of boys names contained in the cwd
file = open('namesBoys.txt', 'r')
elif(gender == 'F' or gender == 'FEMALE'):
# opens a list of girls names contained in the cwd
file = open('namesGirls.txt', 'r')
for line in file:
line = line.strip('\n')
line = line.lower()
names_in_file.append(line)
file.close()
return names_in_file
# gets input from the user and returns their chosen gender
def get_gender():
while(True):
gender = input('Male or Female: ')
gender = gender.upper()
if(gender != 'M' and gender != 'F' and gender != 'MALE' and gender != 'FEMALE'):
print('Error: Please enter either (M)ale or (F)emale')
else:
return gender
# gets input from the user and returns their chosen minimum generated name length
def get_min_length():
while(True):
try:
min_length = int(input('Min Name Length: '))
except ValueError:
print('Error: Please enter a number')
else:
return min_length
# gets input from the user and returns their chosen maximum generated name length
def get_max_length():
while(True):
try:
max_length = int(input('Max Name Length: '))
except ValueError:
print('Error: Please enter a number')
continue
if(max_length < min_length):
print('Error: Please enter a number greater than or equal to minimum name length')
elif(max_length == 1 and min_length == 1):
print('Error: Cannot generate a name with only 1 letter')
sys.exit()
else:
return max_length
# gets input from the user and returns their chosen number of generated names
def get_num_names():
while(True):
try:
num_names = int(input('Number of Names: '))
except ValueError:
print('Error: Please enter a number')
else:
return num_names
# goes through the list of names in the file and processes each name 2 letters at a time
# returns a dictionary that holds those 2 letters and the letter that follows them
def create_rules(names_in_file):
# creates an empty dictionary that contains the following ruleset
# key = 2 consecutive characters in a name
# value = the character that follows those 2 characters
rules = {}
for name in names_in_file:
current_name = '__' + name + '__'
start_index = 0
end_index = 1
while(True):
# the 2 letters that are currently being processed
processing = current_name[start_index:end_index+1]
if(start_index != 0 and processing == '__'):
break
else:
next_char = current_name[end_index+1]
if(processing not in rules):
rules[processing] = [next_char]
else:
rules[processing].append(next_char)
start_index += 1
end_index += 1
return rules
# uses rules to randomly generate a name
# if the generated name is already contained in the list, generate a new name
def generate_name(names_in_file, rules, min_length, max_length):
current_sequence = '__'
generated_name = ''
while(True):
rand_index = random.randint(0, len(rules[current_sequence])-1)
current_char = (rules[current_sequence])[rand_index]
if(current_char == '_'):
if(is_proper_length(generated_name, min_length, max_length) and is_unique(generated_name, names_in_file)):
return generated_name
else:
#if the generated name is already in the list of names or not in between min and max length, try again
current_sequence = '__'
generated_name = ''
continue
else:
# capitalize first letter of generated name
if(current_sequence == '__'):
generated_name += current_char.upper()
else:
generated_name += current_char
current_sequence = current_sequence[1] + current_char
# checks if the generated name is already in the list of names
def is_unique(generated_name, name_list):
for name in name_list:
if(generated_name.lower() == name.lower()):
return False
return True
# checks if the generated name is between min and max length
def is_proper_length(generated_name, min_length, max_length):
if(len(generated_name) >= min_length and len(generated_name) <= max_length):
return True
return False
def print_list(name_list):
print()
print('Here are the generated names:'),
for generated_name in name_list:
print(generated_name),
print()
if __name__ == '__main__':
import random
import sys
done = False
while(not done):
print('\n---Name Generator---\n')
name_list = []
# gets user input and stores it
gender = get_gender()
min_length = get_min_length()
max_length = get_max_length()
num_names = get_num_names()
# creates a list of all the names in the file
names_in_file = openFile(gender)
rules = create_rules(names_in_file)
# creates a list of names
while(len(name_list) < num_names):
name = generate_name(names_in_file, rules, min_length, max_length)
# if generated name is not already in the list, add name to the list
if(is_unique(name, name_list)):
name_list.append(name)
print_list(name_list)
while(True):
response = input('Again? Y or N: ')
response = response.upper()
if(response != 'Y' and response != 'N' and response != 'YES' and response != 'NO'):
print('Error: Invalid response')
else:
if(response == 'N' or response == 'NO'):
done = True
break
|
601a1d881d4e6dcc75070d807af01aaf3e99391a | heartbeat180/LeetCode_practice | /leetcode/editor/cn/[283]Move Zeroes.py | 1,694 | 3.515625 | 4 | #给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
#
# 示例:
#
# 输入: [0,1,0,3,12]
#输出: [1,3,12,0,0]
#
# 说明:
#
#
# 必须在原数组上操作,不能拷贝额外的数组。
# 尽量减少操作次数。
#
# Related Topics 数组 双指针
from typing import List
#leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
### 解法一:双指针,快指针指向部位0的元素的位置,然后交换快慢指针的值。 i 遍历数组, j按顺序保存非零,
# j = 0
# for i in range(len(nums)):
# if nums[i] != 0:
# nums[j], nums[i] = nums[i], nums[j]
# j+=1
# return nums
### 解法二:暴力搜,当碰到0,开始在当前位置之后的元素里搜索不为0的数,找到后交换数值,继续向后遍历。
# 解答成功:
# 执行耗时: 48ms, 击败了98.59 % 的Python3用户
# 内存消耗: 13.8MB, 击败了99.25 % 的Python3用户
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j] = nums[i]
j +=1
for i in range(j,len(nums)):
nums[i] = 0
### 更简洁的,用remove(0),append(0)
#leetcode submit region end(Prohibit modification and deletion)
### 自建本地测试函数
# if __name__ == '__main__':
# nums = Solution.moveZeroes(Solution,[1,2,0,0,4])
# print(nums) |
bff3e5308603964d4cac565320447a4e2af2d577 | alankrit03/Problem_Solving | /Balanced_Brackets_1.py | 666 | 4 | 4 | """'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Following Code contains only a single type of brackets
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''"""
def show_brackets(st, left, right):
if left + right == 2 * n:
print(st)
return 0
if left == right:
show_brackets(st + '(', left + 1, right)
else:
if left == n:
show_brackets(st + ')', left, right + 1)
else:
show_brackets(st + '(', left + 1, right)
show_brackets(st + ')', left, right + 1)
n = int(input())
str1 = ''
show_brackets(str1, 0, 0)
|
cce3f013f7bf5243b7aa669774d9071b154cfd02 | lermon2000/PythonBasics_HSEU | /week_1/maximum.py | 657 | 3.703125 | 4 | # Напишите программу, которая считывает два целых числа A и B
# и выводит наибольшее значение из них. Числа — целые от 1 до 1000.
a, b = [int(input()) for i in range(2)]
# підносимо різницю в ступінь, щоб позбутися мінусу:
diff_positive = (a - b) ** 2
diff_sqrt = diff_positive ** .5
# додаємо до меншого числа його різницю з більшим
# в результаті отримуємо суму двох більших чисел:
result = sum([a, diff_sqrt, b]) / 2
print(int(result))
|
73b792722fac09f643fc4bff62c952b7f4714af9 | PapaGede/globalCode | /loops.py | 1,327 | 4 | 4 | # A code for loops
#
# x=2
# for x in range(2,20):
# if x%2==0:
# print(x)
# def even(x,y):
# for x in range(x+1,y):
# if x%2==0:
# print (x)
# x=int(input("Please enter the first number \n"))
# y=int(input("Please enter the second number \n"))
# even(x,y)
# def even(x,y):
# for y in range(y+1,x-1,-1):
# if y%2==0:
# print (y)
# y=int(input("Please enter the second number \n"))
# x=int(input("Please enter the first number \n"))
# even(x,y)\
# def star():
# for i in range(0,4):
# aster=" "
# for j in range(0,4):
# aster+="*"
# print(aster)
# star()
# Descending star
# for i in range(0,4):
# for j in range(0,i+1):
# print("*", end=' ')
# print("\r")
# for i in range(4,0,-1):
# for j in range(0,i-1):
# print("*", end=' ')
# print("\r")
# for i in range(0,5):
# print("*"*i)
# reversed= range(5,0,-1)
# for i in reversed:
# print("*" * i)
def sentence(sent,char):
for i in range(len(sent),0,-1):
if sent[len(sent)-i]== char:
return "true"
break
if i==1:
return "false"
sent=input("Please enter a sentence: \n")
char=input("Please enter a character you want to find in the sentence: \n")
print(sentence(sent,char))
|
d9ee96d3067d912518e286eb5d87c506e177f269 | XUEMANoba/python-jichu | /18-day/3连用.py | 418 | 3.53125 | 4 | list = [13,6,10,21,30,50,4,89,2]
for i in range(len(list)):
for j in range(i+1,len(list)):
if list[i] > list[j]:
list[i],list[j] = list[j],list[i]
print(list)
num = 4
center = int(len(list)/2)
if num in list:
while True:
if list[center] > num:
center = center-1
elif list[center] < num:
center = center+1
elif list[center] == num:
print("要找的数字是%d索引是%d"%(num,center))
break
|
af3a747efb78c658a79d18de351ee1ea11c1551f | LiveAlone/pythonDemo | /3.7/advance/Functionable.py | 4,595 | 3.71875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
description: 函数式编程, 支持高阶函数方式
"""
# 高阶函数执行方式
# def add(x, y, f):
# return f(x) + f(y)
#
# print(add(-100, -200, abs))
# map reduce filter sorted 过滤执行方式
#
# def f(x):
# return x*x
#
# map 的结果 是一个 Iterator 需要遍历执行方式
# print(list(map(f, [1, 2, 3, 4, 5])))
# reduce 不同, map 是 iterator, reduce 是 立即执行方式
# from functools import reduce
# def add(x, y):
# return x + y
#
# print(reduce(add, [1, 2, 3, 4, 5]))
# map reduce 通过 lambda 简洁的表达方式
#
# from functools import reduce
#
# # def fn(x, y):
# # return x + 10 + y
# #
# # def char2num(s):
# # digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
# # return digits[s]
# #
# # print(reduce(fn, map(char2num, '13579')))
#
# # 简介版本支持
# DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
#
# print(reduce(lambda x, y: x+y, map(lambda x:DIGITS[x], '13579')));
# filter 支持过滤的配置方式, filter 也是 iterator 的过滤方式
# print(list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7])))
# # demo 素数生产工厂
# def _odd_iter():
# n = 1
# while True:
# n += 2
# yield n
#
# def primes():
# yield 2
# it = _odd_iter()
# while True:
# n = next(it)
# yield n
# it = filter(lambda x: x%n>0, it)
#
# # 上面就是 primes 优化器, 会吧 每个 prime, 合数过滤掉
# 不知道 prime 函数底层实现方式
# sort 支持排序方式
# print(sorted([36, 5, -12, 9, -21], key=abs))
# 类似 compare 方式, 通用转换方式, 通过转换后 排序方式。
# 函数返回值, 返回待执行的 fun
# def lazy_sum(*args):
# def sum():
# ax = 0
# for n in args:
# ax = ax + n
# return ax
# return sum
# f = lazy_sum(1, 3, 5, 7, 9)
# f2 = lazy_sum(1, 3, 5, 7, 9)
# print(f)
# print(f())
# print(f == f2)
# 闭包的原因,引用函数原始, 知道 f1, f2, f3 执行时候, 引用外部 i,
# def count():
# fs = []
# for i in range(1, 4):
# def f():
# return i*i
# fs.append(f)
# return fs
#
# f1, f2, f3 = count()
# print(f1(), f2(), f3())
# g1 g2 g3,指向的 f, f -> i, 每次执行 对应 i 保存,
# def count():
# def f(j):
# def g():
# return j*j
# return g
# fs = []
# for i in range(1, 4):
# fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
# return fs
#
# g1, g2, g3 = count()
# print(g1(), g2(), g3())
# 匿名函数 lambda 类是上面的表达方式
# 修饰器 wrapper, 对应函数执行了一层封装
#
#
# def log(func):
# def wrapper(*args, **kw):
# print('call %s():' % func.__name__)
# return func(*args, **kw)
# return wrapper
#
#
# @log
# def now():
# print('2015-3-25')
#
#
# now()
# print(now.__name__)
# 对应 修饰器的封装方式
# def log(text):
# def decorator(func):
# def wrapper(*args, **kw):
# print('%s %s():' % (text, func.__name__))
# return func(*args, **kw)
# return wrapper
# return decorator
#
#
# @log('execute')
# def now():
# print('2015-3-25')
#
# # 类似方式 now = log('execute')(now)
#
# now()
# print(now.__name__) # wrapper 方式
# func wrapper
# import functools
#
# def log(func):
# @functools.wraps(func)
# def wrapper(*args, **kw):
# print('call %s():' % func.__name__)
# return func(*args, **kw)
# return wrapper
#
# @log
# def now():
# print('2015-3-25')
#
# now()
# # wrapper.__name__ = func.__name__
# print(now.__name__) # 因为注解封装, 是 wrapper 方法 functions.wraps() 对应分装 __name__ 还是 now
# import functools
#
#
# def log(text):
# def decorator(func):
# @functools.wraps(func)
# def wrapper(*args, **kw):
# print('%s %s():' % (text, func.__name__))
# return func(*args, **kw)
# return wrapper
# return decorator
#
#
# @log('execute')
# def now():
# print('2015-3-25')
#
#
# # 通过 function tools 方式, 封装对应 func 执行, 返回原生函数的信息。
# now()
# print(now.__name__)
# 偏函数, 类是函数默认参数转换
# def add_plus(x, y, c):
# return x * c + y
#
# print(add_plus(9, 5, 100))
#
# import functools
#
# add_plus_10 = functools.partial(add_plus, c = 10)
# print(add_plus_10(9, 5))
|
86c961bcdb36d9398d450652e4b80df7a06f8cb7 | joaabjb/curso_em_video_python_3 | /desafio003_somando_dois_numeros.py | 148 | 3.875 | 4 | n1=int(input('Digite o primeiro número: '))
n2=int(input('Digite o segundo número: '))
print('A soma entre {} e {} é {}'.format(n1, n2, n1 + n2)) |
e3233fa9aef57f4edeade9f4917e85ad3dcea0a7 | kylecombes/ComputationalArt | /recursive_art.py | 7,983 | 3.703125 | 4 | """ Generates "random" artwork using sine, cosine, sigmoid, products, averaging,
squaring, and cubing functions. """
import random
import math
from PIL import Image
functions = ['prod', 'sigmoid', 'squared', 'cubed', 'avg', 'cos_pi', 'sin_pi']
function_count = len(functions)
def build_random_function(min_depth, max_depth):
""" Builds a random function of depth at least min_depth and depth
at most max_depth (see assignment writeup for definition of depth
in this context)
min_depth: the minimum depth of the random function
max_depth: the maximum depth of the random function
returns: the randomly generated function represented as a nested list
(see assignment writeup for details on the representation of
these functions)
"""
# Hit bottom node
if max_depth < 2:
# Randomly pick x or y
return 'x' if random.random() > 0.5 else 'y'
# Generate new functions
f = functions[random.randrange(0,function_count,1)]
# Pick a random maximum depth
max_depth_1 = min_depth + math.ceil(random.random() * (max_depth - min_depth)) - 1
# print('min_depth =',min_depth,'r =',r,'max_depth_1 =',max_depth_1)
if f == 'sin_pi' or f == 'cos_pi' or f == 'sigmoid':
return [f, build_random_function(min_depth-1, max_depth_1)]
# Pick second random maximum depth
max_depth_2 = min_depth + math.ceil(random.random() * (max_depth - min_depth)) - 1
# print('Min depth:',min_depth,'New max depths:', max_depth_1, max_depth_2)
return [f, build_random_function(min_depth-1, max_depth_2), build_random_function(min_depth-1, max_depth_2)]
def evaluate_random_function(f, x, y):
""" Evaluate the random function f with inputs x,y
Representation of the function f is defined in the assignment writeup
f: the function to evaluate
x: the value of x to be used to evaluate the function
y: the value of y to be used to evaluate the function
returns: the function value
>>> evaluate_random_function(["x"],-0.5, 0.75)
-0.5
>>> evaluate_random_function(["y"],0.1,0.02)
0.02
"""
# print("f[0] ==",f[0])
if f[0] == 'prod':
# print("Evaluating product of",f[1],'and',f[2])
return evaluate_random_function(f[1],x,y) * evaluate_random_function(f[2],x,y)
if f[0] == 'sigmoid':
# print("Evaluating sigmoid of",f[1])
return 1/(1+math.exp(-evaluate_random_function(f[1],x,y)))
if f[0] == 'squared':
# print("Evaluating",f[1],'squared')
return math.pow(evaluate_random_function(f[1],x,y),2)
if f[0] == 'cubed':
# print("Evaluating",f[1],'cubed')
return math.pow(evaluate_random_function(f[1],x,y),3)
if f[0] == 'avg':
# print("Evaluating average of",f[1],'and',f[2])
return (evaluate_random_function(f[1],x,y) + evaluate_random_function(f[2],x,y)) / 2
if f[0] == 'cos_pi':
# print("Evaluating cosine of",f[1])
return math.cos(evaluate_random_function(f[1],x,y)*math.pi)
if f[0] == 'sin_pi':
# print("Evaluating sine of",f[1])
return math.sin(evaluate_random_function(f[1],x,y)*math.pi)
if f[0] == 'x':
# print("Returning x")
return x
if f[0] == 'y':
# print("Returning y")
return y
# A constant
# print("Returning",f[0])
return f[0]
def remap_interval(val,
input_interval_start,
input_interval_end,
output_interval_start,
output_interval_end):
""" Given an input value in the interval [input_interval_start,
input_interval_end], return an output value scaled to fall within
the output interval [output_interval_start, output_interval_end].
val: the value to remap
input_interval_start: the start of the interval that contains all
possible values for val
input_interval_end: the end of the interval that contains all possible
values for val
output_interval_start: the start of the interval that contains all
possible output values
output_inteval_end: the end of the interval that contains all possible
output values
returns: the value remapped from the input to the output interval
>>> remap_interval(0.5, 0, 1, 0, 10)
5.0
>>> remap_interval(5, 4, 6, 0, 2)
1.0
>>> remap_interval(5, 4, 6, 1, 2)
1.5
"""
# Calculate values needed for normalizing
in_range = input_interval_end - input_interval_start
in_med = in_range / 2 + input_interval_start
out_range = output_interval_end - output_interval_start
out_med = out_range / 2 + output_interval_start
scalar = in_range / out_range
# Center our value about zero
val -= in_med
# Scale it down to our new range
val /= scalar
# Shift it back to have the correct midpoint
val += out_med
return val
def color_map(val):
""" Maps input value between -1 and 1 to an integer 0-255, suitable for
use as an RGB color code.
val: value to remap, must be a float in the interval [-1, 1]
returns: integer in the interval [0,255]
>>> color_map(-1.0)
0
>>> color_map(1.0)
255
>>> color_map(0.0)
127
>>> color_map(0.5)
191
"""
# NOTE: This relies on remap_interval, which you must provide
color_code = remap_interval(val, -1, 1, 0, 255)
return int(color_code)
def test_image(filename, x_size=350, y_size=350):
""" Generate test image with random pixels and save as an image file.
filename: string filename for image (should be .png)
x_size, y_size: optional args to set image dimensions (default: 350)
"""
# Create image and loop over all pixels
im = Image.new("RGB", (x_size, y_size))
pixels = im.load()
for i in range(x_size):
for j in range(y_size):
x = remap_interval(i, 0, x_size, -1, 1)
y = remap_interval(j, 0, y_size, -1, 1)
pixels[i, j] = (random.randint(0, 255), # Red channel
random.randint(0, 255), # Green channel
random.randint(0, 255)) # Blue channel
im.save(filename)
def generate_art(filename, x_size=350, y_size=350):
""" Generate computational art and save as an image file.
filename: string filename for image (should be .png)
x_size, y_size: optional args to set image dimensions (default: 350)
"""
# Functions for red, green, and blue channels - where the magic happens!
red_function = build_random_function(7, 9)
green_function = build_random_function(7, 9)
blue_function = build_random_function(7, 9)
# Create image and loop over all pixels
im = Image.new("RGB", (x_size, y_size))
pixels = im.load()
for i in range(x_size):
for j in range(y_size):
x = remap_interval(i, 0, x_size, -1, 1)
y = remap_interval(j, 0, y_size, -1, 1)
pixels[i, j] = (
color_map(evaluate_random_function(red_function, x, y)),
color_map(evaluate_random_function(green_function, x, y)),
color_map(evaluate_random_function(blue_function, x, y))
)
im.save(filename)
if __name__ == '__main__':
import doctest
#doctest.run_docstring_examples(remap_interval, globals())
# doctest.testmod()
# Create some computational art!
# TODO: Un-comment the generate_art function call after you
# implement remap_interval and evaluate_random_function
generate_art("myart.png")
# Test that PIL is installed correctly
# TODO: Comment or remove this function call after testing PIL install
#test_image("noise.png")
|
0bff7e4b751143beec14faebcf248d5ab375aab9 | khurram-saeed-malik/ARDrone | /com/group/1/ConceptTesting/pyimagesearch/shapedetector.py | 518 | 3.5 | 4 | # import the necessary packages
import cv2
class ShapeDetector:
def __init__(self):
pass
def detect(self, c):
# initialize the shape name and approximate the contour
shape = "unidentified"
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.04 * peri, True)
# if the shape is a triangle, it will have 3 vertices
# otherwise, we assume the shape is a circle
if len(approx) != 3 or len(approx) != 4 or len(approx) != 5:
shape = "circle"
# return the name of the shape
return shape |
fab70a5ac29623a84d14ed15762f7d2ecde6a394 | WilliamslifeWayne/python_practice | /practice_4_3.py | 1,107 | 3.75 | 4 | #coding = utf-8
#1⃣️。使用一个for循环打印数字1-20
for num in range(1, 21):
print(num)
#创建一个数字列表,其中包含数字1-1000000使用 max min
# numbers = []
# for numb in range(1, 1000000):
# numbers.append(numb)
# print("numbers的最大值是:", max(numbers))
# print("numbers的最小值是:", min(numbers))
# print("numbers的总和是:", sum(numbers))
#4-6通过给函数range()指定第三个参数来创建一个列表,其中包含1-20的奇数,在使用一个for循环将这些数字都打印出来
jishu_list = []
for jishu in range(1, 20, 2):
jishu_list.append(jishu)
print(jishu_list)
#4-7 3的倍数 创建一个列表,其中包含3-30中能被整除的数字;再使用for循环将这个列表中的数字都打印出来
chu_3_list = []
for value in range(3, 30):
if(value % 3 == 0):
chu_3_list.append(value)
print(chu_3_list)
#4-8 立方 请创建一个列表,其中包含前10个整数的立方,再使用一个for循环将这些立方数都打印出来
lifang = [value ** 3 for value in range(1, 11)]
print(lifang)
|
6e3346b01402aff11ebc8f12cff6e1fdc9374025 | chu-he/rosalind | /015_locating_restriction_sites/recom.py | 737 | 3.625 | 4 | reverse = {}
reverse['A'] = 'T'
reverse['T'] = 'A'
reverse['C'] = 'G'
reverse['G'] = 'C'
def ReverseComplement(string):
revcom = ''
for ch in reversed(string):
revcom += reverse[ch]
return revcom
# Read the dataset
file = open('dataset.txt', 'r')
data = file.read()
file.close()
result = ''
data_length = len(data)
for start in range(data_length-4):
for end in range(start+4, start+9):
if end <= data_length:
substring = data[start:end]
if substring == ReverseComplement(substring):
result += str(start+1) + ' ' + str(end-start) + '\n'
print result
# Write result to file
file = open('result.txt', 'w')
file.write(result)
file.close() |
114a5b6f2e2575ad6bf5076f5d09183fee0f5376 | HeberCooke/Python-Programming | /Chapter2/exercise10.py | 644 | 4.15625 | 4 | """
Heber Cooke 10/3/2019
Chapter 2 exercise 10
This program calculates the total pay for time and overtime
the program takes an input of the hourly wage
an input of the regular pay hours
an input of the overtime pay hours
the program calculates the overtime pay by multiplying wage by 1.5
the reg pay and the overtime pay are added together
the program prints out the totla pay
"""
payRate = float(input("Enter the payRate: "))
regHours = float(input("Enter regular hours worked "))
overTimeHours = float(input("Enter overtime hours worked "))
totalPay = (payRate * regHours) + (overTimeHours * payRate * 1.5)
print("Total Pay is $",totalPay)
|
d6ab2493bcbf0a2dd60cff72fb84dc28583db59b | SafwanSa/monkey-writing-Shakespeares-phrases | /Main.py | 503 | 3.984375 | 4 | from Population import Population
target = "Abduelah Hajjar"
population_num = 1000
mutation_rate = 0.01
population = Population(target, mutation_rate, population_num)
while(not population.finished):
# Will stop the loop if it found the target
population.evaluate()
# Will calculate the fitness for each DNA (Individual)
population.calcFitness()
# Will print the best fitness for each generation
population.printBest()
population.naturalSelection()
population.generate()
|
4b216eeba1f418e3855382feda00181d2b0a6911 | Dolantinlist/DolantinLeetcode | /51-100/78_subsets.py | 356 | 3.578125 | 4 | class Solution(object):
def subsets(self, nums):
nums.sort()
res, tmp = [], []
self.dfs(nums, 0, tmp, res)
return res
def dfs(self, nums, index, tmp, res):
res.append(tmp)
for i in range(index, len(nums)):
self.dfs(nums, i + 1, tmp + [nums[i]], res)
print(Solution().subsets([1,2,3])) |
c4dcec91fd66194bce0cee3c5e3b2a5a1f5d870d | temirlanr/tkinter | /tkinter basic.py | 3,729 | 4.09375 | 4 | from tkinter import *
root = Tk()
root.title("CalculatOR!!!!")
entry = Entry(root, width=40, borderwidth=3)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
def button_click(number):
current = entry.get()
entry.delete(0, END)
entry.insert(0, str(current)+str(number))
def clearButton():
entry.delete(0, END)
def addButton():
first_number = entry.get()
global first
global action
action = "add"
first = int(first_number)
entry.delete(0, END)
def subtractButton():
first_number = entry.get()
global first
global action
action = "subtract"
first = int(first_number)
entry.delete(0, END)
def multiplyButton():
first_number = entry.get()
global first
global action
action = "multiply"
first = int(first_number)
entry.delete(0, END)
def divideButton():
first_number = entry.get()
global first
global action
action = "divide"
first = int(first_number)
entry.delete(0, END)
def equalButton():
global action
second_number = entry.get()
entry.delete(0, END)
if action == "add":
entry.insert(0, first + int(second_number))
elif action == "subtract":
entry.insert(0, first - int(second_number))
elif action == "multiply":
entry.insert(0, first * int(second_number))
elif action == "divide":
entry.insert(0, first / int(second_number))
button_0 = Button(root, width=9, text=str(0), pady=10, command=lambda: button_click(0))
button_1 = Button(root, width=9, text=str(1), pady=10, command=lambda: button_click(1))
button_2 = Button(root, width=9, text=str(2), pady=10, command=lambda: button_click(2))
button_3 = Button(root, width=9, text=str(3), pady=10, command=lambda: button_click(3))
button_4 = Button(root, width=9, text=str(4), pady=10, command=lambda: button_click(4))
button_5 = Button(root, width=9, text=str(5), pady=10, command=lambda: button_click(5))
button_6 = Button(root, width=9, text=str(6), pady=10, command=lambda: button_click(6))
button_7 = Button(root, width=9, text=str(7), pady=10, command=lambda: button_click(7))
button_8 = Button(root, width=9, text=str(8), pady=10, command=lambda: button_click(8))
button_9 = Button(root, width=9, text=str(9), pady=10, command=lambda: button_click(9))
button_clear = Button(root, width=9, text="clear", pady=10, command=clearButton, fg="white", bg="grey").grid(row=4, column=0)
button_add = Button(root, width=9, text="+", pady=10, command=addButton).grid(row=1, column=3)
button_equal = Button(root, width=9, text="=", pady=10, command=equalButton).grid(row=4, column=2)
button_subtract = Button(root, width=9, text="-", pady=10, command=subtractButton).grid(row=2, column=3)
button_multiply = Button(root, width=9, text="*", pady=10, command=multiplyButton).grid(row=3, column=3)
button_divide = Button(root, width=9, text="/", pady=10, command=divideButton).grid(row=4, column=3)
# don't judge me...
for i in range(10):
if(i==0):
globals()["button_"+str(i)].grid(row=4, column=1)
elif(i==1):
globals()["button_"+str(i)].grid(row=3, column=0)
elif(i==2):
globals()["button_"+str(i)].grid(row=3, column=1)
elif(i==3):
globals()["button_"+str(i)].grid(row=3, column=2)
elif(i==4):
globals()["button_"+str(i)].grid(row=2, column=0)
elif(i==5):
globals()["button_"+str(i)].grid(row=2, column=1)
elif(i==6):
globals()["button_"+str(i)].grid(row=2, column=2)
elif(i==7):
globals()["button_"+str(i)].grid(row=1, column=0)
elif(i==8):
globals()["button_"+str(i)].grid(row=1, column=1)
elif(i==9):
globals()["button_"+str(i)].grid(row=1, column=2)
root.mainloop() |
00ca9147f64c557db62a4593107dae820e6a3af3 | JeffHoogland/weathertrek | /gmaps/geocoding.py | 2,466 | 3.734375 | 4 | # -*- coding: utf-8 -*-
from gmaps.client import Client
class Geocoding(Client):
GEOCODE_URL = "geocode/"
def geocode(self, address=None, components=None, region=None,
language=None, bounds=None, sensor=None):
"""Geocode given address. Geocoder can queried using address and/or
components. Components when used with address will restrict your query
to specific area. When used without address they act like more precise
query. For full details see
`Google docs <https://developers.google.com/maps/documentation/geocoding/>`_.
:param address: address string
:param components: ditc of components
:param region: region code specified as a ccTLD ("top-level domain")
two-character value, influences but not restricts query result
:param language: the language in which to return results. For full list
of laguages go to Google Maps API docs
:param bounds: two-tuple of (latitude, longitude) pairs of bounding
box. Influences but not restricts result (same as region parameter)
:param sensor: override default client sensor parameter
""" # noqa
parameters = dict(
address=address,
components=components,
language=language,
sensor=sensor,
region=region,
)
if bounds:
parameters['bounds'] = "%f,%f|%f,%f" % (
bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1])
return self._make_request(self.GEOCODE_URL, parameters, "results")
def reverse(self, lat, lon, language=None, sensor=None):
"""Reverse geocode with given latitude and longitude.
:param lat: latitude of queried point
:param lon: longitude of queried point
:param language: the language in which to return results. For full
list of laguages go to Google Maps API docs
:param sensor: override default client sensor parameter
.. note:: Google API allows to specify both latlng and address params
but it makes no sense and would not reverse geocode your query, so
here geocoding and reverse geocoding are separated
"""
parameters = dict(
latlng="%f,%f" % (lat, lon),
language=language,
sensor=sensor,
)
return self._make_request(self.GEOCODE_URL, parameters, "results")
|
fa7669a799a7cad62b49403f09199291d3684533 | arnav1993k/Denoising | /patter/models/activation.py | 1,131 | 3.625 | 4 | import torch
from torch.nn import Module, functional as F
class Swish(Module):
"""Implementation of Swish: a Self-Gated Activation Function
Swish activation is simply f(x)=x⋅sigmoid(x)
Paper: https://arxiv.org/abs/1710.05941
Shape:
- Input: :math:`(N, *)` where `*` means, any number of additional
dimensions
- Output: :math:`(N, *)`, same shape as the input
Examples::
>>> m = nn.Swish()
>>> x = autograd.Variable(torch.randn(2))
>>> print(x)
>>> print(m(x))
"""
def forward(self, input_):
return input_ * torch.sigmoid(input_)
def __repr__(self):
return self.__class__.__name__ + '()'
class InferenceBatchSoftmax(Module):
""" Implementation of the Softmax activation, that is only
run during inference. During training, the input is
returned unchanged.
"""
def forward(self, input_, dim=-1):
if not self.training:
return F.softmax(input_, dim=dim)
else:
return input_
def __repr__(self):
return self.__class__.__name__ + '()'
|
78ef998fd40ffa4bb03caac5e2f1f9f0ab5a32a8 | zhjr2019/PythonWork | /01_Python_Basis/Python_Karon/03_循环/jr_07_continue.py | 347 | 4.09375 | 4 | i = 0
while i < 10:
# comtinue 某一条件满足时,不执行后续重复的代码
if i == 3:
# 注意:在循环中,如果使用 continue 这个关键字
# 在使用关键字之前,需要确定循环的计数是否修改,否则可能会导致死循环
i += 1
continue
print(i)
i += 1 |
ed4233b9cdef94ea4a353d9872a0aa948c7a43e6 | rishabh0509/python_first | /list_example.py | 204 | 3.8125 | 4 | fruits = ['apple', 'pear'] #can store diff. datatypes in a list
print (fruits)
fruits.append('strawberry')
print(fruits)
fruits[1]='blueberry'
print(fruits)
color=(255,255,255)
print(type(color))
|
6d95bb477b57e200423b2fc897f5ef4cca5482f3 | JulesNunez/python-jumpstart-course-demos | /apps/02-guess-number-app/you_try/program.py | 1,378 | 4.25 | 4 | import random
import os
print('-----------------------------------')
print(' GET IT RIGHT, OR YOU DIE! ')
print('-----------------------------------')
print()
def say_it(text):
s = 'say "{}"'.format(text)
os.system(s)
the_number = random.randint(0, 100)
guess = -1
tell_name = 'WELCOME TO THE FABULOUS AMAZING NUMBER GAME COMING TO EVERY CONSOLE ON THE MARKET.' \
' THE RULE IS SIMPLE, YOU SCREW UP YOU DIE. YOU MUST GUESS A NUMBER BETWEEN 1 AND 100.' \
' BUT FIRST, TYPE IN YOUR NAME...'
print(tell_name)
say_it(tell_name)
name = input('Enter your name:' )
while guess != the_number:
guess_message = 'GUESS A NUMBER BETWEEN 0 and 100: '
say_it(guess_message)
guess_text = input(guess_message)
guess = int(guess_text)
if guess < the_number:
low = "TOO BAD {}, YOUR GUESS OF {} WAS TO LOW, PIG. HA HA HA.".format(
name, guess)
print(low)
say_it(low)
elif guess > the_number:
high = 'TOO BAD {}, YOUR GUESS OF {} WAS TO HIGH, HA YOU ARE A LOSER.'.format(name, guess)
print(high)
say_it(high)
else:
correct = 'Oh wow {}, you actually did it. I guess {} was right, cool.'.format(name, guess)
print(correct)
say_it(correct)
final = "You're done! Go outside, you fat potato!"
print()
print(final)
say_it(final)
|
054dcd1e28c12427a9673e9b4789c66a6bb643a6 | Fernandoramos24/ejercicios-parcial-1-fundamentos | /ejercicio tiendas don pepe.py | 279 | 3.671875 | 4 | descuento=0
precio = float(input("digite precio: "))
dia = input("ingrese dia de la semana")
if dia=="martes" or dia=="jueves":
descuento = precio * 0.15
preciofinal = precio - descuento
print("el precio final a pagar es de $0, preciofinal,""con un descuento de",descuento) |
3648aa9ef6146046f7f095bcd08b092948063df8 | fatawesome/StructProgramming | /Practice2.2/task6.py | 222 | 3.8125 | 4 | import math
print('Give me X')
x = float(input())
print('Give me Y')
y = float(input())
c = math.sqrt(math.pow(x,2) + math.pow(y,2))
if ((x <= 1) and (y <= 1)) and (c >= 1):
print("Good!")
else:
print("Bad :(")
|
6da808e231903be6b5b5f3889b0772417428fec8 | NitishShandilya/CodeSamples | /maximumSumSubArray.py | 672 | 3.8125 | 4 | """
Given a 1D array, find the maximum sum obtained from a sub-array with sequential elements.
The program utilizies Kadane's algorithm.
Time complexity is O(n), where n is the size of the array.
"""
class MaximumSumSubarray(object):
def __init__(self, arr):
self.arr = arr
self.length = len(self.arr)
def findMaxSumKadane(self):
max_curr = max_sum = self.arr[0]
for i in range(1, self.length):
max_curr = max(self.arr[i]+max_curr, self.arr[i])
max_sum = max(max_sum, max_curr)
return max_sum
#Test
arr = [-2,-3,-2,-1]
maxSumSubarray = MaximumSumSubarray(arr)
print maxSumSubarray.findMaxSumKadane() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.