blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c47f21ccf47585759700aec437968bbff11c0ae2 | Rodo2005/condicionales_python | /ejercicios_practica.py | 14,030 | 4.1875 | 4 | #!/usr/bin/env python
'''
Condicionales [Python]
Ejercicios de práctica
---------------------------
Autor: Inove Coding School
Version: 1.1
Descripcion:
Programa creado para que practiquen los conocimietos adquiridos durante la semana
'''
__author__ = "Inove Coding School"
__email__ = "alumnos@inove.com... |
57d9d25fe134eff49886a76ba6d8ea91f9498073 | nikhilpatil29/AlgoProgram | /algo/MenuDriven.py | 2,442 | 4.125 | 4 | '''
Purpose: Program to perform all sorting operation like
insertion,bubble etc
@author Nikhil Patil
'''
from utility import *
class MenuDriven:
x = utility()
choice = 0
while 1:
print "Menu : "
print "1. binarySearch method for integer"
print "2. binarySearch method for String... |
390fe2f7fb1ee8ee47365ad962ebcc34f65d83fa | VPDeb/LambData | /lambdata_vdeb/.ipynb_checkpoints/oop_examples-checkpoint.py | 2,449 | 3.71875 | 4 | """OOP Eaxamples for module 2 """
import pandas as pd
class MyDataFrame(pd.DataFrame):
def num_cells(self):
return self.shape[0] * self.shape[1]
class BareMinimumClass:
pass
class Complex:
def __init__(self, realpart, imagpart): #constructor
"""
Constructor for Complex numbers.
... |
1651cd7f95534bc9710fddba9d052733cd62ae8e | gfbenatto/Simple-tests-in-Python | /reverse.py | 136 | 4.03125 | 4 | array = []
x = 1
while x <= 10:
v = float(input("Digite o valor: "))
array.append(v)
x += 1
array.reverse()
print(array) |
c569284e3f4a64ff2c27c01052a8be9f23f82fd8 | gfbenatto/Simple-tests-in-Python | /vcarro.py | 168 | 3.953125 | 4 | v = int(input("Digite a velocidade do carro."))
if v > 110:
m = 5 * (v - 110)
print("Voce foi multado no valor de ", m)
else:
print("Voce nao foi multado.") |
013d6c5744ac525562ab838d17c2ce8eaf327f6c | gfbenatto/Simple-tests-in-Python | /triangulo.py | 369 | 3.953125 | 4 | a = int(input("Digite o lado a."))
b = int(input("Digite o lado b."))
c = int(input("Digite o lado c."))
if a > b + c or b > a + c or c > a + b:
print("Nao pode ser um triangulo")
print("Um lado não pode ser maior que a soma dos outros dois lados.")
elif a == b == c:
print("Equilatero")
elif a != b != c:
... |
3b2b2949b78caf861b7385b22e151ae671cc9650 | gfbenatto/Simple-tests-in-Python | /telefonia.py | 266 | 3.734375 | 4 | minutos = int(input("Digite os minutos."))
if minutos <200:
preco=0.20
else:
if minutos <= 400:
preco=0.18
else:
if minutos <= 800:
preco=0.15
else:
preco=0.08
print("Valor: ", minutos * preco) |
67f15d6ebff94c2240d2728f7eec42ac6186e785 | sreevidyachintala/Student-Report-Generation-With-Encryption-and-decryption-using-Keys | /dataGen.py | 879 | 3.8125 | 4 | import random
import csv
import datetime
#pre-defined list of names included in names.py
import names
#filename with current time
dt = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
filename = 'StudentData'+dt+'.csv'
#By default gave it to generate 4000 students data
num = int(input("Howmany students data neede... |
597b83e87de912ae37e8e16200259a5a06f16154 | sthephmaldonado/PFDM | /Exercises for Reflections/Wek2&3Excercice6.4.py | 173 | 3.578125 | 4 | #%%
#
# keyword : def
def add(value1,value2,value3):
return value1 + value2 + value3
#%%
# keyword : def
Value1= 4
Value2= 2
Value3= 10
print(add(4,2,10))
#%%
|
f9ef24ce6280cbb3ee946cfaf7e28b3e56b69726 | dimostht/Salesman-Problem-with-Genetic-Algorithm | /main.py | 5,316 | 3.671875 | 4 | import copy
import random
import matplotlib.pyplot as plt
# to random create N points within X and Y limits
def createPoints(n,maxX,maxY):
points = [[0 for _ in range(2)] for _ in range(n)]
# first point is 0 , 0
# the rest are randoms
for i in range(1,n):
while True:
point = [rand... |
6040de0d0f7174d576cb5d370c9d90dfe65c97aa | noite-m/nlp2020 | /chart1/practice04.py | 881 | 4.03125 | 4 | '''
“Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.”という文を単語に分解し,
1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭の2文字を取り出し,
取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
'''
text = "Hi He Lied Because Boron Could Not Oxidize Fluorine... |
953f3587f7cba8d48585a093ce5e0c8e2942d35f | noite-m/nlp2020 | /chart1/practice09.py | 1,876 | 4.125 | 4 | '''
スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
ただし,長さが4以下の単語は並び替えないこととする.
適当な英語の文
(例えば”I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .”)
を与え,その実行結果を確認せよ.
'''
import random
'''
ランダムに複数の要素を選択(重複なし): random.sample()
randomモジュールの関数s... |
52419857d6f11ad7e2881f772e96b360336f3895 | noite-m/nlp2020 | /chart2/practice17/practice17.py | 350 | 3.921875 | 4 | #1列目の文字列の種類(異なる文字列の集合)を求めよ.確認にはcut, sort, uniqコマンドを用いよ.
#https://note.nkmk.me/python-pandas-value-counts/
import pandas as pd
df = pd.read_table('chart2/popular-names.txt',header=None,names=['name','sex','number','year'])
col1 = df['name']
print(sorted(list(set(col1))))
|
b82e7411b13dbad1c88ba6f73ca285733cee8fa1 | Mbank8/DojoAssignments | /Python/Fundamentals/names_pyth.py | 1,106 | 3.765625 | 4 | students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
... |
311b4cc1c9701a42c896bfddd6751d0b045e2b60 | Mbank8/DojoAssignments | /Python/Fundamentals/stars.py | 276 | 3.5 | 4 |
x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
def draw_stars(x):
total = 0
for value in x:
if isinstance(value, int):
print value * "*"
elif isinstance(value, str):
print value[0] * len(value)
print draw_stars(x) |
41c9e1e4e2196ae66bd80f936b7339b569df9df9 | ap9035/scientific-computing | /Ch6/Newton.py | 987 | 4.03125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
"""
Newton's method find root
參考:https://en.wikipedia.org/wiki/Newton%27s_method
"""
"""
對函數進行微分
Input:
func:
要微分的函數
x:
nparray or float number
dx(optional):
float number
Output:
在x點的微分值,type視輸入而定,可為float number 或 nparray
"""
def df(... |
c354efb5adc7332549e2a2e16c009084eaf7e59a | ap9035/scientific-computing | /Ch6/bisection.py | 716 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
bisection method
在一給定區間找根,如兩者之間有奇數根,則f(x1)*f(x2)<0
"""
from math import fabs
def bisection(func, x1, x2):
eps = 1e-10
if func(x1)*func(x2) > 0:
return 0
while fabs(x2-x1) > eps:
xm = (x1+x2)/2
fxm = func(xm)
fx1 = func(x1)
fx2 = func(x2)
... |
a8a515e8e66e150efa89fba6ea85184d137ee7d7 | singhpartap/Assignments | /assignment2.py | 305 | 3.890625 | 4 | #Q1:
print("Hello my name is Patap Singh")
#Q2:
print("Partap" "Singh")
#Q3:
x=input("Enter the value of x")
y=input("Enter the value of y")
z=input("Enter the value of z")
print(x,y,z)
#Q4:
print('"let\'s get started"')
#Q5:
s="acadview"
course="python"
fee="5000"
print(('%s\n%s\n%s')%(s, course, fee)) |
3612041b108d71ebca535520f3eabf05177d0f88 | rajday19/Data-Structures | /DP.py | 3,246 | 3.734375 | 4 | import sys
class Solution:
def numDecodings(self, s):
memo = {}
def f(s):
print ("\nThe input string is:",s)
if s == "":
return 1 #if s is a empty string there is only one way to decode it
elif s[0] == "0":
return 0 #if s[0] is 0 then the string is invalid, since no letter maps to 0, e.g 01 does... |
67691dbfcfd0580f0ce7009e88f76925c5b7f7ad | imdurgadas/PyFrameworks | /SQLAlchemy/sql_basics.py | 1,178 | 3.8125 | 4 | import sqlalchemy
__author__ = 'durgadas_kamath'
from sqlalchemy import *
import os
print sqlalchemy.__version__
os.remove('example.db') #Removing the example.db since below create operations will fail if it already exists
db = create_engine('sqlite:///example.db') #this will create example.db in your working direc... |
a6784a24f9b212b58836b898720567de4885de2d | nhrade/image-similarity | /Project/sift_similarity.py | 2,213 | 3.6875 | 4 | import cv2
import numpy as np
import os
def similarity(des1, des2):
"""
The similarity between two image descriptors by finding the closest
neighbor for each vector in des1, and then averaging them. Then averaging this distance
to find the distance between des1 and des2.
:param des1: First list of... |
f488729bfef85934b4867abfce47f4d8ffab3662 | trnkatom/python_learning | /GitTest/PythonGitTest.py | 544 | 3.53125 | 4 | import random
# random fun code
class GitTest:
number = 0
def __init__(self):
print("This is python_learning no.{}\n".format(self.generate_git_test_number()) + str(self))
def generate_git_test_number(self):
GitTest.number += 1
return self.number
def __str__(self):
retur... |
69e6f4c4b02561dc00d736bebce9c890251387da | wvzxtc/p2-201611090 | /w6Main11.py | 141 | 4.15625 | 4 | year=input("User input year : ")
if (year%4==0 and year%100!=0) and (year%400==0) :
print "Leap year"
else:
print "Not Leap year"
|
544aa5bc849622caa4348454bee69fb6101ba9a2 | sonal1999/Intelligent-voice-recorder | /text_speech.py | 994 | 3.796875 | 4 | import os
import time
import playsound
import speech_recognition as sr
from gtts import gTTS
def speak(text):
tts = gTTS(text=text,lang='en') #text to speech
filename = 'voice.mp3'
tts.save(filename)
playsound.playsound(filename)
def get_audio():
r = sr.Rec... |
cbfa94e5ab45819bb1dd9ee3834ec98d1b826911 | webfarer/python_by_example | /Chapter2/016.py | 317 | 4.125 | 4 | user_rainy = str.lower(input("Tell me pls - is a rainy: "))
if user_rainy == 'yes':
user_umbrella = str.lower(input("It is too windy for an umbrella?: "))
if user_umbrella == 'yes':
print("It is too windy for an umbrella")
else:
print("Take an umbrella")
else:
print("Enjoy your day") |
59a1d217903a06de0594dabc7abb8843feea5479 | webfarer/python_by_example | /Chapter3/024.py | 67 | 3.578125 | 4 | user_name = input("Print your name: ")
print(str.upper(user_name)) |
da35768f26e1f51a715f1983bad67e935097e597 | webfarer/python_by_example | /Chapter2/018.py | 181 | 3.890625 | 4 | user_numb = int(input("Input your number pls: "))
if user_numb < 10:
print("Too low")
elif user_numb >= 10 and user_numb <= 20:
print("Correct")
else:
print("Too high") |
1fd3768b7333b6be11d16437d3ab59d8b424c50b | WeiKangJian/turtlePicture | /tutor.py | 1,066 | 3.90625 | 4 | import turtle
# Author WeiKangJian
# Date 2019/11/6
turtle.left(90)
turtle.back(300)
turtle.forward(100)
toplevel = 7 # 绘制的叶子的分叉数目,也是递归的层数
leftangle = 30 #一开始偏移的角度
rightangle = 30 #向另一边偏移的角度
turtle.speed('fastest') #画笔绘画的快慢
turtle.color('blue','blue')# 图画的颜色
#递归画图
def diguiTree(length, deep):
turtle.left(l... |
3f18cc05e3d43fee4cab89e0d5f29f74e072d738 | jewarner57/CS-1.1-Flower_Project | /test_app.py | 329 | 3.84375 | 4 | from app import Flower
def test_get_turn_degrees():
"""Tests if get turn degrees gets the number of degrees needed to rotate for each petal"""
flower = Flower(10, "red", 0, 0, 0, 0)
assert flower.get_turn_degrees(10) == 36
assert flower.get_turn_degrees(100) == 3.6
assert flower.get_turn_degrees(... |
4dfcd4aee55e71b078ea9d614de866f2c1f5457f | shchun/udacity_work | /freq.py | 283 | 3.53125 | 4 | #!/usr/bin/env python
def freq_analysis(message):
ret = []
len_message = len(message);
for i in range(0,26):
ret.append(0.0)
for ch in message:
ret[ord(ch) - ord('a')] += 1
for i in range(0,26):
ret[i] /= len_message
return ret
#Tests
print freq_analysis("abcd")
|
eaafd5ad99d9330ce73bb9064b08eb2be0aac193 | crawfonw/ChessPye | /chesspye/utils/Stack.py | 747 | 3.578125 | 4 | '''
Created on Mar 1, 2014
@author: Nick Crawford
'''
class Stack(object):
def __init__(self, initial_set=[]):
if isinstance(initial_set, list):
self.objs = initial_set
else:
self.objs = [initial_set]
def push(self, obj):
self.objs.append(obj)
... |
0fd60f60e7d27ad81641bcdb0b712e0510e43f41 | naamoonoo/leetcode | /sortArrayByParity/sortArrayByParity.py | 1,454 | 4.03125 | 4 | # class Solution:
# def sortArrayByParity(self, A: List[int]) -> List[int]:
class Solution:
def sortArrayByParity(self, A):
return list(filter(lambda x: x % 2 == 0, A)) + list(filter(lambda x: x % 2 == 1, A))
print(Solution().sortArrayByParity([3,1,2,4]))
#https://www.programiz.com/python-programming/metho... |
9afaf188cffc87d62a2aa530811046bc8b9abfe2 | perhamer/Find_Love_MusicCloud | /sql.py | 2,176 | 3.921875 | 4 | """
一般 Python 用于连接 MySQL 的工具:pymysql
"""
import pymysql.cursors
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='cloudmusic',
charset='utf8mb4',
c... |
eb8a31c26d7b087e7ff7e806d8869dcfefc34d04 | mmcintyre1/python_morsels-exercises | /orderedset.py | 1,908 | 3.765625 | 4 | from collections.abc import MutableSet
from itertools import zip_longest
class OrderedSet(MutableSet):
def __init__(self, items):
# with python 3.7, dicts are guaranteed to maintain insertion order
self.items = dict.fromkeys(items, None)
super().__init__()
def __len__(self):
r... |
fe3b3b55e4d537cab59c9c4943361b4714eabf64 | afeldman/sternzeit | /year/year.py | 2,904 | 4.78125 | 5 | #!/usr/bin/env python3
def is_leap_year(year):
""" if the given year is a leap year, then return true
else return false
:param year: The year to check if it is a leap year
:returns: It is a Leap leap year (yes or no).
"""
return (year % 100 == 0) if (year % 400 == 0) else (year % 4 == 0)
... |
ab78edacfb9e981771e94160431322b3b20f42a0 | nirmaldalmia/InterviewBit | /Binary Search/CountElementOccurence.py | 1,251 | 3.5 | 4 | def findCount(A,B):
A = list(A)
def findOccurence(Arr, B, searchFirst):
#A = list(A)
start = 0
end = len(A)
result = -1
while start <= end-1:
mid = (start + end) // 2
print(start, mid, end)
if A[mid] == B:
result = mid
... |
e5d06af566b672f70e1fa86541ade4d70d4fd8ee | nirmaldalmia/InterviewBit | /Arrays/generateMatrix.py | 1,091 | 3.75 | 4 | def generateMatrix(A):
matrix = [[0]*A for x in range(A)]
print(matrix)
top = 0
bottom = A - 1
left = 0
right = A - 1
num = 1
direction = 1
while top <= bottom and left <= right:
#direction = direction % 4
if direction == 1:
i = left
while i <=... |
fb13eb0ac8bbdf1b8e6f7b13e9ce35646ea9ef17 | nirmaldalmia/InterviewBit | /Arrays/SetMatrixZeroes.py | 411 | 3.515625 | 4 | def setZeroes(A):
listA = []
for i in range(len(A)):
for j in range(len(A[0])):
if A[i][j] == 0:
listA.append((i,j))
for x in listA:
#print(x[0], x[1])
A[x[0]] = [0]*len(A[0])
for j in range(len(A)):
A[j][x[1]] = 0
#print(listA)
... |
f0da693b6260b05f5985c080629f2ffdc7900fac | matteokg/PDXcodeguild-fullstack-night-03052018 | /helloworld.py | 74 | 3.984375 | 4 | name = input ("What is your name?")
hello = "Hello"
print (hello + name)
|
1ab8bc8785c7e830e1e010b2135fd335911673e9 | matteokg/PDXcodeguild-fullstack-night-03052018 | /numberguess.py | 488 | 3.9375 | 4 | import random
x=random.randint(1,10)
i=0
while i<10:
guess = int(input("guess the number between 1 and 10?"))
i= i+1
if guess > x:
print ("Too high, guess again")
elif guess < x:
print ("Too low, guess again")
elif guess == x:
break
if guess == x and i == 1:
print("... |
0082218ec1f81d0161f2d59a5451d08b30454fb2 | ani03sha/potd | /Python/UncommonWordsFromTwoSentences.py | 909 | 3.9375 | 4 | """
Given two strings representing sentences, return the words that are not common to both strings
(i.e. the words that only appear in one of the sentences). You may assume that each sentence is
a sequence of words (without punctuation) correctly separated using space characters.
"""
from typing import List
class U... |
c16f7de3de24eb693d24fc3ec777b51039a62445 | ani03sha/potd | /Python/IntersectionOfTwoArrays.py | 603 | 3.78125 | 4 | """
Given two arrays, write a function to compute their intersection.
"""
from typing import List
class IntersectionOfTwoArrays:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
# Set for storing elements of first array
set1 = set(nums1)
# This set will store the el... |
f502a1187eedc1885f47e2e11a9da38e5cff4b71 | ani03sha/potd | /Python/ValidAnagram.py | 1,019 | 3.84375 | 4 | """
Given two strings s and t return whether or not s is an anagram of t.
Note: An anagram is a word formed by reordering the letters of another word.
"""
class ValidAnagram:
def isAnagram(self, s: str, t: str) -> bool:
# Base condition
if len(s) != len(t):
return False
# Count... |
a7d7644bb975a5fed15249d69821d64077028729 | ramonVDAKKER/mortgage_calculus | /mortgage_calculus/interest_and_redemption.py | 3,291 | 3.96875 | 4 | """This module provides functions related to redemptions and interest."""
from typing import Optional, Union, Tuple
import pandas as pd
import numpy as np
def determine_annuity(
months_to_legal_maturity: int, outstanding_balance: float, interest_rate:
float) -> float:
"""Calculate the (mont... |
19a4eec72c959963e8b9159b608facd021a487e9 | zdgriffith/exercism | /python/word-count/word_count.py | 371 | 3.75 | 4 | def word_count(phrase):
spaced_phrase = ''
for c in phrase:
if c.isalnum():
spaced_phrase += c.lower()
else:
spaced_phrase += ' '
words = {}
for word in spaced_phrase.split():
if word not in words.keys():
words[word] = 1
else:
... |
a283f8985295973b49feb41db7cc75bfd0729179 | zdgriffith/exercism | /python/isogram/isogram.py | 325 | 4.0625 | 4 | def is_isogram(word):
char_list = []
for char in word.lower(): #make all letters lowercase to avoid mixed cases
if char.isalpha(): #only care about letters in the phrase
if char in char_list:
return False
else:
char_list.append(char)
return T... |
965fd4b67e626cdedb5013e9ed2b9cd20238d738 | dheerajgss/onlineCodingProblems | /Coding Blocks/uglyNumber.py | 414 | 4.09375 | 4 | """Find out the nth ugly number. Ugly numbers are positive numbers whose prime factors only
include 2, 3, 5.
Ex: i/p -> n = 10
o/p -> 12
Explanation: 1 2 3 4 5 6 8 9 10 12 is the sequence of 1st 10 ugly numbers. So 10th ugly number is 12."""
n = int(input())
count = 1
i = 1
while(count < ... |
89e569fdefc8d5ae00c7fe33caef19039580757b | dheerajgss/onlineCodingProblems | /Coding Blocks/sortedSquaredArray.py | 621 | 3.78125 | 4 | """Given a sorted array of integers, print the sorted array of squares of the given integers.
Ex: i/p = [-5, -3, 0, 1, 2, 4]
o/p = [0, 1, 4, 9, 16, 25]
Constraints:
1 <= n <= 100000
-100000 <= a[i] <= 100000
Note:
Input will be always given in sorted order. """
... |
126ba2113fe13cb7a8008b772793718001df3c94 | KacperKubara/USAIS_Workshops | /Clustering/k-means.py | 1,734 | 4.1875 | 4 | # K-NN classification with k-fold cross validation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Read Data
dataset = pd.read_csv("Mall_Customers.csv")
# Choose which features to use
x = dataset.iloc[:, 3:5].values # Features - Age, annual income (k$)
"""
K-Means clustering is unsupervise... |
40bda47b522a9e360f849fb9c5dea651f55e5da0 | Chitrank-Dixit/PyAlgo | /build/lib/pyalgo.py | 479 | 4.03125 | 4 | """
This is the operations.py module that has all the basic operations specified that will be used frquently in programming
"""
class Swap(object):
"""
Takes two values and swaps them
Basic Usage:
swap_obj = Swap(1,2)
value2, value1 = swap_obj.get_swap_values()
"""
def __ini... |
8b05426a7d8b2caa7544ac22231a3952aba13f67 | Chitrank-Dixit/PyAlgo | /algos/searching/linear_search.py | 732 | 3.875 | 4 | """
This is the operations module that has all the searching operations that will be used frequently in programming
"""
class LinearSearch(object):
"""
Takes two values and swaps them
Basic Usage:
>>> instance = LinearSearch([12,34,23,56,45,67])
>>> item_index = instance.search_item(23)
... |
3adc3dc9ee49075fe30386b9d5364a64ae404042 | rishabh78sharma/BasicCoding | /geekcoders/prime.py | 191 | 3.6875 | 4 | a=int(input("enter first no."))
b =int(input("enter second no."))
c=0
for i in range(a,b+1):
for j in range(2,i):
if (i%j==0):
break
else:
print(i) |
27fc3284eee75420fca4efa411874dd04218536a | rishabh78sharma/BasicCoding | /geekcoders/intfunction.py | 123 | 3.921875 | 4 | number_=int(input("enter first number"))
number_2=int(input("enter second number"))
print("total is"+str(number_+number_2)) |
ba167f75d6c29f9346b3ed6378c2f945b767a0ed | rishabh78sharma/BasicCoding | /geekcoders/functionlist.py | 224 | 3.625 | 4 | global t
n=input("enter the number till the loop is work ")
t=int(n)
user=list(range(1,t))
def squalist(l):
square=[]
for i in l:
user =square.append(i**2)
return square
print(user)
print(squalist(user)) |
ffa28ca598e21a39dc5383b52d767b75ce5f1cc5 | rishabh78sharma/BasicCoding | /geekcoders/list.py | 150 | 3.734375 | 4 | list =['mango',"graped",1,1,1]
# print(list)
# list[0:]=["mango"]
# print(list)
# list.append("red")
# print(list)
list.insert(1,"hariom")
print(list) |
5145d5d6d484e1a564c31e0718e9675f889918c4 | liuxiang0/pi | /iteration_pi.py | 3,366 | 3.8125 | 4 | #!/usr/bin/python
# -*- encoding: UTF-8 -*-
"""
代数几何迭代算法, 迭代逼近单位圆的半周长 $\pi$, 从而得到圆周率 π
初始状态:取单位圆的内接正六边形,其变成为 1.
从正六边形得到正十二边形的半周长,以此类推,迭代以此,边数增加一倍。
求边长的迭代函数为 f(x)=sqrt(2-sqrt(4-x**2))
迭代次数:n
对应半周长:6*2**(n-1)*f(x)
采取:迭代生成器方法,和符号运算法则,得到迭代序列。需要时再计算某个迭代值。
讨论:如何通过相邻几个迭代值,计算出迭代误差值,或结果的精度。
好像只能字符判断,不能用浮点数判断。
... |
29499975de28aeab41267755656eab4fd9862682 | eborche2/aoc2019 | /day12/day12.py | 3,122 | 3.5 | 4 | from itertools import combinations
import copy
def adjust_velocity(moon_pair):
first_moon = moon_pair[0]
second_moon = moon_pair[1]
for x in range(3):
if first_moon['p'][-1][x] > second_moon['p'][-1][x]:
first_moon['v'][-1][x] -= 1
second_moon['v'][-1][x] += 1
elif f... |
cbd801cabdf6e7bba1ae2620557533d557e25b83 | hborawski/dailyprogrammer | /243Deficient/deficient | 445 | 3.90625 | 4 | #!/usr/bin/env python3
def main():
num = int(input("Input number:"))
sig = sigma(num)
if sig < num*2:
print("{} deficient".format(num))
elif sig > nm*2:
print("{} abundant by {}".format(num, sig-(num*2)))
else:
print("{} ~~neither~~".format(num))
def sigma(n):
sig = 0
... |
bbc0e8be78cfa289bd48b7f34f49d001483c9d48 | hborawski/dailyprogrammer | /217SpaceCode/space | 1,066 | 3.546875 | 4 | #!/usr/bin/env python3
def main():
words = [line.strip() for line in open('/usr/share/dict/words')]
for line in open("input.txt"):
line = line.strip().replace("\"","").split()
results = [earth(line), ryza(line), hoth(line), omicron(line)]
for result in results:
if result.spl... |
ef176517aef87306214a52f1ef0ab37e89b0d269 | ganenchaoshi/PythonExercises | /100exercises/ex005.py | 484 | 3.5625 | 4 | # 输入三个整数x,y,z,请把这三个数由小到大输出。
# numbs = input('输入三个整数并以空格分隔')
# numbslist = numbs.split(' ')
# print(sorted(numbslist))
input1 = int(input('输入第一个整数'))
input2 = int(input('输入第二个整数'))
input3 = int(input('输入第三个整数'))
x = y = z = input1
ls = [input1, input2, input3]
for i in ls:
if i > x:
x = i
elif i < z:
... |
d993224020c27d65d748c9cbef2b05eba84b78bb | ganenchaoshi/PythonExercises | /100exercises/ex025.py | 233 | 3.59375 | 4 | # 求1+2!+3!+...+20!的和。
sum = 0
for i in range(1,21):
count = 1
for j in range(i,0,-1):
count *= j
sum += count
print(sum)
n = 0
s = 0
t = 1
for n in range(1,21):
t *= n
print(t)
s += t
print(s) |
0956ee7a737706c0362ef1c43c5cee24c673c448 | ganenchaoshi/PythonExercises | /lpthw3/projects/gothonweb/gothonweb/planisphere.py | 2,295 | 3.515625 | 4 | class Room(object):
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def go(self, direction):
return self.paths.get(direction, None)
def add_paths(self, paths):
self.paths.update(paths)
central_corridor = Room... |
db5b1c33e04483ed3737725011bc9ad2516a7f76 | ganenchaoshi/PythonExercises | /Calculate_Pi/calcu_Pi01.py | 525 | 3.546875 | 4 | # 使用蒙特卡洛方法求Pi
import random
turns = int(input('请输入试验点数:')) # 实验次数
counts = 0 # 落在半径为1的圆内的点数
area = 0 # 四分之一圆的面积
i = 0 # 累加数
while i < turns:
a = random.random()
b = random.random()
if a**2 + b**2 <= 1: # 判断点是否在圆内
counts += 1
i += 1
else:
area = counts / turns # 边长为1的正方形乘以落在圆内的比例求面积
pi ... |
f1437444cea1e8124849ed41f62ba4783afe5956 | ganenchaoshi/PythonExercises | /100exercises/ex002.py | 1,068 | 3.515625 | 4 | # 企业发放的奖金根据利润提成。
# 利润(I)低于或等于10万元时,奖金可提10%;
# 利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;
# 20万到40万之间时,高于20万元的部分,可提成5%;
# 40万到60万之间时高于40万元的部分,可提成3%;
# 60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,
# 从键盘输入当月利润I,求应发放奖金总数?
bonus = 0
i = float(input('输入当月利润(单位为万)'))
if i > 100:
bonus = (i - 100) * 0.0... |
cdb33f1546bf280ff205fe68e8f2b62e2fb2023b | Girech/Lista-2 | /Ex23.py | 122 | 3.765625 | 4 | metros = float(input("Digite o valor em jardas:"))
jardas = metros/0.91
print("o valor em jardas é de:{}".format(jardas)) |
d1ded0827b65a857206de62c9a5b419188290e10 | Girech/Lista-2 | /Ex4.py | 123 | 3.953125 | 4 | numero = float(input("Digite um numero real:"))
exp = numero**2
print("O quadrado de {} resulta em: {}".format(numero,exp)) |
ba4024c7bd3337e6e8495eb51c575aa9e2bba5b4 | charlie-boy/python | /prg.py | 359 | 3.890625 | 4 | def add(a,b):
return a+b
def mul(a,b):
return a*b
def sub(a,b):
return a-b
def div(a,b):
return a/b
a=int(raw_input("Enter first number:"))
b=int(raw_input("Enter second number:"))
x=raw_input("1.add\n2.mul\n3.sub\n4.div\nEnter your choice:")
if x=="1":
print(add(a,b))
elif x=="2":
print(mul(a,b))
elif x=="3":
... |
93811c68b09b9135e41a166ecf0b1d88d015b486 | charlie-boy/python | /battleship.py | 2,339 | 3.9375 | 4 | from random import randint
#from goto import goto, label
b1=[]
b2=[]
count = 0
s1 = int(raw_input("Enter size of first battleship: "))
s2 = int(raw_input("Enter size of second battleship: "))
for i in range(0,s1):
b1.append(["O"]*s1)
for j in range(0,s2):
b2.append(["O"]*s2)
def print_board(board):
for row... |
49d767e89a6ee8b815787451e5b509fc3a138884 | keyuzh/cs161 | /PS1/problem5.py | 850 | 3.65625 | 4 | def have_common_key(A: MaxHeap, B: MaxHeap, n: int) -> bool:
try:
while n > 0:
# get the max element of each max heap and compare them
max_A = A.max()
max_B = B.max()
if max_A == max_B:
# common key found
return True
... |
c92ba28a2db8538eed1376126fd30f9f156e5c15 | betty29/code-1 | /recipes/Python/573452_Assertithat_code_fragment_throws_particular/recipe-573452.py | 2,264 | 3.640625 | 4 | #!/usr/bin/env python
#-*- coding: iso-8859-1 -*-
###############################################################################
class expected:
def __init__(self, e):
if isinstance(e, Exception):
self._t, self._v = e.__class__, str(e)
elif isinstance(e, type) and issubclass(e, Excep... |
f0749405938e25a640b1955262887d8e5924397a | betty29/code-1 | /recipes/Python/52316_Dialect_for_sort_by_then_by/recipe-52316.py | 1,587 | 4.15625 | 4 | import string
star_list = ['Elizabeth Taylor',
'Bette Davis',
'Hugh Grant',
'C. Grant']
star_list.sort(lambda x,y: (
cmp(string.split(x)[-1], string.split(y)[-1]) or # Sort by last name ...
cmp(x, y))) # ... then by first name
print... |
bca0c6e7245fdea86fedf0b49e9243a3d4ee8187 | betty29/code-1 | /recipes/Python/302218_Joe_Strouts_chatserverpy_converted/recipe-302218.py | 7,170 | 3.8125 | 4 | #!/usr/bin/env python
# A simple 94(*) lines of code "chat" server. Creates a server on port 4000.
# Users telnet to your machine, at port 4000, and can chat with each other.
# Use "quit" to disconnect yourself, and "shutdown" to shut down the server.
#
# Adapted from J. Strout version at
# http://www.strout.net/inf... |
da7d9b543243c19783719c409b67347ce4b126a3 | betty29/code-1 | /recipes/Python/304440_Sorting_dictionaries_value/recipe-304440.py | 843 | 4.21875 | 4 | # Example from PEP 265 - Sorting Dictionaries By Value
# Counting occurences of letters
d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}
# operator.itemgetter is new in Python 2.4
# `itemgetter(index)(container)` is equivalent to `container[index]`
from operator import itemgetter
# Items sorted by key
# The new built... |
81a9c92401b4c7e36861eb61b7337e65ac9d904e | betty29/code-1 | /recipes/Python/577679_naive_natural_sort/recipe-577679.py | 483 | 3.671875 | 4 | def keynat(string):
'''A natural sort helper function for sort() and sorted()
without using regular expression.
'''
r = []
for c in string:
if c.isdigit():
if r and isinstance(r[-1], int):
r[-1] = r[-1] * 10 ... |
93942d481a8b6be961f5fcb6f23a0ac6667e482e | betty29/code-1 | /recipes/Python/299777_Simplified_Mutable_Instances/recipe-299777.py | 351 | 3.65625 | 4 | class MutableInstance(dict):
def __init__(self):
self.__dict__ = self
# This makes common tasks easier, not by much but conceptually it unifies things
Foo = MutableInstance()
Foo.x = 5
assert Foo['x'] == 5
Foo.y = 7
assert Foo.keys() == ['x', 'y']
assert Foo.values() == [5, 7]
# And now you can pass it to anythin... |
eb5f5d1f627ae6e822a7a133c498395b64b558bf | betty29/code-1 | /recipes/Python/306865_Observer_pattern_scalar/recipe-306865.py | 6,770 | 4.0625 | 4 | """
Implement an observer pattern for attribute access.
Assumes that each attribute is used (exclusivly) for either scalar
values, lists or maps.
It does not work if you store a scalar in an attribute, and then later
a map or list.
A scalar attribute is an attribute whose values do not have internal
structure. Scal... |
28f414c966b639ce76b138c54dd7026b5e194db8 | betty29/code-1 | /recipes/Python/579115_Recognizing_speech_speechtotext_Pythspeech/recipe-579115.py | 246 | 3.8125 | 4 | import string
import speech
while True:
print "Talk:"
phrase = speech.input()
speech.say("You said %s" % phrase)
print "You said {0}".format(phrase)
#if phrase == "turn off":
if phrase.lower() == "goodbye":
break
|
00db2c8c3ed972b7163d98736f55e12ede747a2c | betty29/code-1 | /recipes/Python/577538_Poor_Man_unit_tests/recipe-577538.py | 3,826 | 3.734375 | 4 | #! /usr/bin/env python
######################################################################
# Written by Kevin L. Sitze on 2010-12-03
# This code may be used pursuant to the MIT License.
######################################################################
import sys
import traceback
from types import FloatType, ... |
809a2e466bf5784e776a0249cf43460147cb14e0 | betty29/code-1 | /recipes/Python/578935_Garden_Requirements_Calculator/recipe-578935.py | 2,723 | 4.21875 | 4 | '''
9-16-2014
Ethan D. Hann
Garden Requirements Calculator
'''
import math
#This program will take input from the user to determine the amount of gardening materials needed
print("Garden Requirements Calculator")
print("ALL UNITS ENTERED ARE ASSUMED TO BE IN FEET")
print("____________________________________________... |
a5f84a55c7614def6497c4376b26ad7469a6a13e | betty29/code-1 | /recipes/Python/194371_Case_Insensitive_Strings/recipe-194371.py | 1,847 | 3.703125 | 4 | class iStr(str):
"""Case insensitive strings class.
Performs like str except comparisons are case insensitive."""
def __init__(self, strMe):
str.__init__(self, strMe)
self.__lowerCaseMe = strMe.lower()
def __repr__(self):
return "iStr(%s)" % str.__repr__(self)
def __eq__(s... |
d122b9e1caf600e4ebb59aa4abb8bf2ded1c40a1 | betty29/code-1 | /recipes/Python/577691_Validate_ACNs_AustraliCompany/recipe-577691.py | 2,451 | 4 | 4 | def isacn(obj):
"""isacn(string or int) -> True|False
Validate an ACN (Australian Company Number).
http://www.asic.gov.au/asic/asic.nsf/byheadline/Australian+Company+Number+(ACN)+Check+Digit
Accepts an int, or a string of digits including any leading zeroes.
Digits may be optionally separated with... |
ba92c3b1aa0f10c9a178db17fb368b60e10d49f1 | betty29/code-1 | /recipes/Python/498233_weighted_choice_short_easy_numpy/recipe-498233.py | 603 | 3.859375 | 4 | from numpy import *
from numpy.random import random
def toss(c, sh):
"""Return random samples of cumulative vector (1-D numpy array) c
The samples are placed in an array of shape sh.
Each element of array returned is an integer from 0 through n-1,
where n is the length of c."""
y = random(sh) ... |
28bbef757c905b8dda3a072af32a850ded041ba4 | betty29/code-1 | /recipes/Python/498261_Deeply_applying_str_across/recipe-498261.py | 7,252 | 3.5625 | 4 | """Utilities for handling deep str()ingification.
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
Casual Usage:
from deepstr import deep_str
print deep_str(["hello", "world"])
Very unusual usage:
import deepstr
import xml.sax.saxutils
def handle_list(obj, deep_str):
if isinstance(obj, lis... |
8889a1b811be8518702998a0485651e0e1d435de | betty29/code-1 | /recipes/Python/577182_Apparent_InfectiRate/recipe-577182.py | 1,141 | 3.640625 | 4 | # Created by Donyo Ganchev, Agricultural University, town of Plovdiv, Bulgaria
# donyo@abv.bg
import math
import datetime
choice=None
def air():
f_y, f_m, f_d=input('Enter first date in format "year, month, day": ')
s_y, s_m, s_d=input('Enter second date in format "year, month, day": ')
f_pd... |
6fe36c6057450f367c510e40fade01474ef53d7c | betty29/code-1 | /recipes/Python/576613_Easy_State_Pattern__support_implementing_state/recipe-576613.py | 15,873 | 3.84375 | 4 | """
Supports implementation of state pattern.
State Machine is defined a class containing one or more StateTable objeects,
and using decorators to define Events and Transitions that are handled by the
state machine. Individual states are Subclasses of the state machine, with
a __metaclass__ specifier.
Author: Rod... |
e2f6af7d70e34e1fd89e1239bcbac0709810dc25 | betty29/code-1 | /recipes/Python/577344_Maclaurinsseriescos2x/recipe-577344.py | 1,458 | 4.15625 | 4 | #On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 03/008/10
#version :2.6
"""
maclaurin_cos_2x is a function to compute cos(x) using maclaurin series
and the interval of convergence is -inf < x < +inf
cos... |
773f3b389a7163d46c81503d44a8be6d530cc346 | betty29/code-1 | /recipes/Python/65445_Decorate_output_stream_printlike/recipe-65445.py | 801 | 3.953125 | 4 | class PrintDecorator:
"""Add print-like methods to any file-like object."""
def __init__(self, stream):
"""Store away the stream for later use."""
self.stream = stream
def Print(self, *args, **kw):
""" Print all arguments as strings, separated by spaces.
Take an option... |
b87a83bc4939269c32b7b78aeb2dd9b81451f2f6 | betty29/code-1 | /recipes/Python/457661_Generate_SQL_insertatiintable_dictionary/recipe-457661.py | 648 | 3.671875 | 4 | def insertFromDict(table, dict):
"""Take dictionary object dict and produce sql for
inserting it into the named table"""
sql = 'INSERT INTO ' + table
sql += ' ('
sql += ', '.join(dict)
sql += ') VALUES ('
sql += ', '.join(map(dictValuePad, dict))
sql += ');'
return sql
def dictValu... |
732f2f0ff4a663fd79fb15e387482b1222153781 | betty29/code-1 | /recipes/Python/266480_popPeekpy/recipe-266480.py | 1,153 | 3.578125 | 4 | #!/usr/bin/python
import sys
import getpass
import poplib
def popPeek(server, user, port=110):
try:
P = poplib.POP3(server, port)
P.user(user)
P.pass_(getpass.getpass())
except:
print "Failed to connect to server."
sys.exit(1)
deleted = 0
try:
l = P.l... |
7ad891da593e2d3f3577051454c5e6f496e75e04 | betty29/code-1 | /recipes/Python/197530_Merging_two_sorted_iterators_insingle/recipe-197530.py | 2,471 | 4.09375 | 4 | #!/usr/bin/env python
"""An extended example of generators in action. Provides a function
called mergeiter that merges two iterators together.
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
"""
from __future__ import generators
def mergeiter(i1, i2, cmp=cmp):
"""Returns the "merge" of i1 and i2. i1 and i2 must be i... |
839b5f031ae104f4dd07345eb25556e7cdb5d8cc | betty29/code-1 | /recipes/Python/473844_Sudoku_solver/recipe-473844.py | 8,928 | 3.828125 | 4 | #!/usr/bin/env python
"""Sudoku solver
usage: python sudoku.py <file> [<depth>]
The input file should contain exactly 81 digits, with emtpy fields marked
with 0. Optionally, dots (.) may be used for empty fields if better
readability is required. All other characters are discarded.
The default guessing depth is 2.
... |
391f0d3caa4402672e50a4bd596db8660a35ea06 | betty29/code-1 | /recipes/Python/163968_Generator_arbitrary/recipe-163968.py | 247 | 3.65625 | 4 | def peel(iterable, arg_cnt=1):
"""Use ``iterable`` to return ``arg_cnt`` number of arguments
plus the iterator itself.
"""
iterator = iter(iterable)
for num in xrange(arg_cnt):
yield iterator.next()
yield iterator
|
1f70e9aa9b8d60e390d035a078dfc4cef4359c34 | betty29/code-1 | /recipes/Python/580767_Unix_teelike_functionality/recipe-580767.py | 3,201 | 3.953125 | 4 | # tee.py
# Purpose: A Python class with a write() method which, when
# used instead of print() or sys.stdout.write(), for writing
# output, will cause output to go to both sys.stdout and
# the filename passed to the class's constructor. The output
# file is called the teefile in the below comments and code.
# The ... |
327190b83ab01bda8e558dad150588420541e6c3 | betty29/code-1 | /recipes/Python/334621_List_Dictionaries_Memory/recipe-334621.py | 1,602 | 3.671875 | 4 | #!/usr/bin/python2.4
import types
class Table(object):
"""A structure which implements a list of dict's."""
def __init__(self, *args):
self.columns = args
self.rows = []
def _createRow(self, k,v):
return dict(zip(k, v))
def append(self, row):
if type(row) =... |
43ba466012629085524d93e37f309a343401d116 | betty29/code-1 | /recipes/Python/363783_InverseExtend/recipe-363783.py | 3,059 | 3.796875 | 4 | """Iterate downward through a hierarchy calling a method at each step."""
__docformat__ = "restructuredtext"
def inverseExtend(boundMethod, *args, **kargs):
"""Iterate downward through a hierarchy calling a method at each step.
boundMethod -- This is the bound method of the object you're interested in.
... |
25e974baee920b8a33eadc100ebb42bf26cfca36 | betty29/code-1 | /recipes/Python/389639_Default_Dictionary/recipe-389639.py | 515 | 3.78125 | 4 | import copy
class DefaultDict(dict):
"""Dictionary with a default value for unknown keys."""
def __init__(self, default):
self.default = default
def __getitem__(self, key):
if key in self:
return self.get(key)
else:
## Need copy in case self.default is some... |
e26d4366ef53ccb0f3167905dffeb83d814dd918 | betty29/code-1 | /recipes/Python/577220_Decimal_binary_prefix/recipe-577220.py | 550 | 3.984375 | 4 | def binary_prefix(value, binary=True):
'''Return a tuple with a scaled down version of value and it's binary prefix
Parameters:
- `value`: numeric type to trim down
- `binary`: use binary (ICE) or decimal (SI) prefix
'''
SI =... |
e15306a1a7d6cae5419ed295cdfe5eeb245b320b | betty29/code-1 | /recipes/Python/578589_Poker_Hands/recipe-578589.py | 2,861 | 3.84375 | 4 | #!/usr/bin/env python3
import collections
import itertools
import random
SUIT_LIST = ("Hearts", "Spades", "Diamonds", "Clubs")
NUMERAL_LIST = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
class card:
def __init__(self, numeral, suit):
self.numeral = numeral
self.su... |
72c7d9c0053f142daa1f4bc97fc7400e5f921f18 | betty29/code-1 | /recipes/Python/363782_InverseExtendGenerators/recipe-363782.py | 4,019 | 3.765625 | 4 | """Iterate downward through a hierarchy calling a method at each step."""
__docformat__ = "restructuredtext"
import types
def inverseExtend(boundMethod, *args, **kargs):
"""Iterate downward through a hierarchy calling a method at each step.
boundMethod -- This is the bound method of the object you're inte... |
3a4eb198807f7867802a3f47c58abbb0dc6d1552 | betty29/code-1 | /recipes/Python/577350_Synchronizing_worker_threads_using_comminput/recipe-577350.py | 2,762 | 3.984375 | 4 | import threading
class WorkersLounge(object):
def __init__(self, total_workers_number):
"""
@param total_workers_number: the maximum number of worker threads
"""
self.total_workers_number = total_workers_number
self.waiting_place = threading.Condition()
self.work_done_event = threading.Event()
def r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.