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 |
|---|---|---|---|---|---|---|
ac98777c509e0e92d030fd29f9fc9e33e175d948 | morvanTseng/paper | /TestDataGeneration/data_generation.py | 2,653 | 4.125 | 4 | import numpy as np
class DataGenerator:
"""this class is for two dimensional data generation
I create this class to generate 2-D data for testing
algorithm
Attributes:
data: A 2-d numpy array inflated with 2-D data
points has both minority and majority class
labels: A 1-D nu... |
3e58c41838f39ca67722df2ad1f40acdd7b77f93 | TheChanRProject/SannaAnnaTutoring | /science/sanna/physics/scripts/motion/motion_graphs_project.py | 377 | 3.546875 | 4 | import numpy as np
import pandas as pd
x = np.array([float(i) for i in range(0,11)])
print(x)
y = np.array([0.00, 2.25, 4.38, 6.30, 8.30, 10.26, 12.30, 14.22, 16.43, 18.35, 20.00])
print(y)
import matplotlib.pyplot as plt
plt.title("Motion Graph")
plt.xlabel("Distance (meters)")
plt.ylabel("Time (seconds)")
plt.plot... |
8f443818982c5bfff91ee91487b9515145354c7e | Shiru99/Learning-Python | /1.02.py | 4,743 | 4.40625 | 4 | #!/bin/python3
##########################################################################################################
# ### String formatting ###
# name ,favNum = "John" , 99
# print("Hello {}!!! ur fav num is {}.".format(name,favNum+900)) # Python3
# print(f"Hello {na... |
a7cf4e1825830bbb6972819cc73c090b07b09396 | Shiru99/Learning-Python | /3.03.py | 6,566 | 3.90625 | 4 | ##########################################################################################################
############## Errors #############
##########################################################################################################... |
7ed7803455cd895ff5040589a1267afc42e9c55d | Shiru99/Learning-Python | /4.07.py | 2,397 | 3.515625 | 4 |
############## MenuBar :
#
###########################################################################################################
import tkinter as tk
from tkinter import ttk
win = tk.Tk()
win.title(' 米^_^米 MenuBar 米^_^米 ')
###########---------Simple menubar----------- :
# menubar = tk.Menu(win... |
193ba136e0c667b84dcff683355aee443607c556 | olessiap/glowing-journey-udacity | /6_drawingturtles.py | 1,179 | 4.15625 | 4 | # import turtle
#
# def draw_square():
# window = turtle.Screen()
# window.bgcolor("white")
#
# brad = turtle.Turtle()
# brad.shape("turtle")
# brad.color("green")
# brad.speed(2)
# count = 0
# while count <= 3:
# brad.forward(100)
# brad.right(90)
# count = count... |
820b6dc8f092a7128bfd1b55d0db7f3b239d3f9a | olessiap/glowing-journey-udacity | /2_daysold.py | 2,007 | 4.375 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
##breaking down the problem ##
#PSEUDOCOD... |
a56d3515a593b1de39678c86becf657b33073b61 | s3rvac/blog | /en-2014-10-11-indexing-python-lists-with-integer-or-object-name/named_object_list.py | 1,827 | 3.921875 | 4 | """
named_object_list
~~~~~~~~~~~~~~~~~
A list of objects indexable with an integer or object's name.
:copyright: © 2014 by Petr Zemek <s3rvac@gmail.com>
:license: BSD, see LICENSE for more details
"""
class NamedObjectList(list):
"""A list of objects indexable with an integer or object's na... |
c5d77b545b742410db5a56ffb35a8b4a25eb3f9b | Josepe75/pvlab | /src/pvlab/io/dictmaker.py | 4,817 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# License: BSD 3-clause
"""Generate python dictionaries from multiple files and data types.
New functions are intended to read files of parameters and convert each
data file into a python dictionary. Different type of parameters should be
located in different files, for a better perform... |
57b1b101bf217d863ac81aec1a916e0260bcce2c | tianyi33/Python | /country_cases.py | 383 | 3.5 | 4 | users={"aziz":{'country':'turkey','city':'A','food':'rice'},
"tianyi":{'country':'china','city':'B','food':'noodle'},
"bruce":{'country':'us','city':'C','food':'burger'}}
for name, details in users.items():
print('\nUsername: '+name)
home=details['country']+' '+details['city']
food=details['food']
print('Came fro... |
de922ab0471fc5b6976933148f4fcf09ff205cf2 | tianyi33/Python | /river_cases.py | 419 | 4.15625 | 4 | river={'chang jiang':'china',
'huang he':'china',
'qian tang jiang':'china',
'nile':'egypt'}
for name,location in river.items():
if location!="china":
print(name.title()+" is not in my country.")
else:
print(name.title()+' is from my country!')
for name,location in river.items():
print('\nthis river called '... |
aaf559b38540fe9e8417e962260c97d902baa593 | tianyi33/Python | /tiantask1.2_cases.py | 462 | 3.84375 | 4 | import random
random.random()
number=random.randint(1,30)
guess="Guess what number it is?"
guess+="\nIf you want to know the answer just put 'please'."
message=""
active=True
while active:
message=input(guess)
if message<number:
print("Guess bigger one, have some balls.")
if message>number:
print('Nonono too bi... |
cb67165d23de15cbfb22506446b14accb8d1e544 | Lim0nchik/kzlcrbq_kursach | /data.py | 1,752 | 3.5 | 4 | import pandas as pd
import config
actor_columns = [
'actor_name',
'actor_year_of_birth',
'actor_country',
'actor_played_movies',
'actor_best_movie_id'
]
movie_columns = [
'movie_id',
'movie_name',
'movie_score'
]
def join_from_csv() -> pd.DataFrame:
"""
Left-joined actors x ... |
58ebf530dfe60102bdd623ba72fd686354e95287 | ravikailash/leetcode_solutions | /find_min_in_rotated_sorted_array.py | 710 | 3.9375 | 4 | import doctest
def find_min(nums, low=None, high=None):
"""
Testing finding minimum in rotated array
>>> nums = [4, 5, 6, 7, 0, 1, 2]
>>> print(find_min(nums))
0
"""
if low is None and high is None:
low, high = 0, len(nums)-1
if low > high:
return 0
if low == high:
return arr[low]
mid = (low + high)... |
ff61771ad9aea58bbef228c3fe448975e84daaae | cordeiroraylle/URI | /Python/1008.py | 120 | 3.53125 | 4 | n = int(input())
h = int(input())
sal = float(input())
print("NUMBER =",n)
print("SALARY = U$ {:.2f}".format(h*sal)) |
b42fc15c46bc74b9d4ad06c85fd1d530d3396e7d | brianstoiber/Python-THW | /ex10.py | 689 | 4 | 4 | # Defines variables
tabby_cat = "\tI'm tabbed in." # Defines the string tabbed in
persian_cat = "I'm split\non a line." # Defines the string on 2 lines using \n escape sequence
backslash_cat = "I'm \\ a \\ cat." # Defines the string escaping backslashes
# Defines variable and writes string (list) on multiple lines
# "... |
126d28674d208ed464f874e1a79fec2b73174b6a | brianstoiber/Python-THW | /ex15b.py | 316 | 4.09375 | 4 | # Asks for the filename you want to open and assigns it to "filename"
print "Type the filename you are looking for."
filename = raw_input("> ")
# Passes filename as txt
txt = open(filename)
# Prints Line 9 and then prints file
print "Here's your file %r:" % filename
print txt.read()
# Closes the file
txt.close() |
15393aabb250c0edadffd77b9b6cc5801c0f4001 | shnhrtkyk/ldgcnn | /utils/tf_util.py | 42,032 | 3.546875 | 4 | """ Wrapper functions for TensorFlow layers.
Author: Charles R. Qi
Date: November 2016
Upadted by Yue Wang and Yongbin Sun
"""
import numpy as np
import tensorflow as tf
def _variable_on_cpu(name, shape, initializer, use_fp16=False, trainable=True):
"""Helper to create a Variable stored on CPU memory.
Args:
... |
a9ab2e591e65123d33deb79ffc5467f5199a2f39 | TeeGeeDee/adventOfCode2020 | /Day4/day4.py | 2,221 | 4.125 | 4 |
from typing import List
def parse_records(records_raw:List[str]):
"""Turn list of raw string records (each record across multiple list entries)
to list of dict structured output (one list entry per record)
Parameters
----------
records_raw : List[str]
List of records. Records are se... |
ad3564d330aba2b298de30d2f8b41ab2ca6891da | TeeGeeDee/adventOfCode2020 | /Day3/day3.py | 1,066 | 4.125 | 4 |
from typing import List
from math import prod
def traverse(down: int,right: int,terrain: List[str]):
""" Counts number of trees passed when traversing terrane with given step sizes
Parameters
----------
down: int
number of steps to take down each iteration
right: int
number o... |
9e72a3b63a392aff565a4cd4bbad93a433a4a29f | matthijskrul/ThinkPython | /src/Fourth Chapter/Exercise7.py | 375 | 4.1875 | 4 | # Write a fruitful function sum_to(n) that returns the sum of all integer numbers up to and including n.
# So sum_to(10) would be 1+2+3...+10 which would return the value 55.
def sum_to(n):
s = 0
for i in range(1, n+1):
s += i
return s
def sum_to_constant_complexity(n):
return ((n*n)+n)/2
to... |
a045639c84c2406c26df9f3360f62d71301563a4 | matthijskrul/ThinkPython | /src/Fourteenth Chapter/Example4.py | 1,377 | 3.65625 | 4 | def text_to_words(the_text):
""" return a list of words with all punctuation removed,
and all in lowercase.
"""
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these
... |
1a8fccb7fb13686e45d22fcd9bde0a590c86a09b | matthijskrul/ThinkPython | /src/Fourth Chapter/Example3.py | 434 | 3.984375 | 4 | def final_amt(p, r, n, t):
"""
Apply the compound interest formula to p
to produce the final amount.
"""
a = p * (1 + r/n) ** (n*t)
return a # This is new, and makes the function fruitful.
# now that we have the function above, let us call it.
toInvest = float(input("How much do... |
dda935f6da4a8cbfec906da0aba2a401699ebeeb | matthijskrul/ThinkPython | /src/Eleventh Chapter/Exercise2.py | 884 | 3.71875 | 4 | # Write a function scalar_mult(s, v) that takes a number, s, and a list, v and returns the scalar multiple of v by s.
import sys
def scalar_mult(s, v):
newlist = []
for i in range(len(v)):
scalarmult = s * v[i]
newlist.append(scalarmult)
return newlist
def test(did_pass):
""" Print... |
1c386c05eedd6eb6a974309e94f6d9de014dc3c4 | matthijskrul/ThinkPython | /src/Fourteenth Chapter/Exercise5.py | 3,380 | 4.15625 | 4 | # Every week a computer scientist buys four lotto tickets. She always chooses the same prime numbers,
# with the hope that if she ever hits the jackpot, she will be able to go onto TV and Facebook
# and tell everyone her secret. This will suddenly create widespread public interest in prime numbers,
# and will be the tr... |
3183b55c7af7676967030c9a448ee96058425105 | matthijskrul/ThinkPython | /src/Eighteenth Chapter/Exercise6.py | 607 | 4.09375 | 4 | # Rewrite the fibonacci algorithm without using recursion.
# Can you find bigger terms of the sequence?
# Can you find fib(200)?
import time
def fibonacci(n):
fibonaccinumber1 = 0
fibonaccinumber2 = 1
if n > 1:
for i in range(2, n+1):
fibonaccinumber3 = fibonaccinumber1 + fibonaccinumb... |
90e3aa20ceca89debc99ef5b009ad413dd57c625 | matthijskrul/ThinkPython | /src/Seventh Chapter/Exercise15.py | 2,718 | 4.5 | 4 | # You and your friend are in a team to write a two-player game, human against computer, such as Tic-Tac-Toe
# / Noughts and Crosses.
# Your friend will write the logic to play one round of the game,
# while you will write the logic to allow many rounds of play, keep score, decide who plays, first, etc.
# The two of you... |
6214f1f255b27ebc7f66772224695f41ec9cc4fd | matthijskrul/ThinkPython | /src/Third Chapter/Exercise6.py | 226 | 3.984375 | 4 | #write a program to draw a pentagram
import turtle
wn = turtle.Screen()
gardner = turtle.Turtle()
gardner.shape("turtle")
for i in range(5):
gardner.forward(100)
gardner.right(144)
gardner.hideturtle()
wn.mainloop()
|
422711de41ff156ba5034ccf165c06f905642867 | matthijskrul/ThinkPython | /src/Eighteenth Chapter/Example5.py | 829 | 3.9375 | 4 | import os
def get_dirlist(path):
"""
Return a sorted list of all entries in path.
This returns just the names, not the full path to the names.
"""
dirlist = os.listdir(path)
dirlist.sort()
return dirlist
def print_files(path, prefix = ""):
""" Print recursive listing of contents ... |
465614cb680e8e8104937dad56f62595fe49d974 | matthijskrul/ThinkPython | /src/Seventh Chapter/Exercise1.py | 263 | 4.0625 | 4 | # Write a function to count how many odd numbers are in a list.
def count_odds(list):
oddscount = 0
for i in (list):
if i % 2 == 0:
continue
oddscount += 1
print(oddscount)
# (test) count_odds([1, 3, 5, 8, 10, 12, 23])
|
71c54434f7de2d264857273567eb5fed0f7b6605 | matthijskrul/ThinkPython | /src/Twentysixth Chapter/Exercise3.py | 1,383 | 4 | 4 | # Reversing linked list.
class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
class SimpleLinkedList:
def __init__(self, init_values=[]):
self.length = 0
self.head = None
if ... |
1799b0bb483129d3d11973ad9a9962e939c231ba | matthijskrul/ThinkPython | /src/Eighth Chapter/Exercise10.py | 1,011 | 4.0625 | 4 | # Write a function that removes the first occurrence of a string from another string.
import sys
def remove(substring, string):
index = string.find(substring)
if substring not in string:
return string
else:
before_occurrence = string[:index]
after_occurrence = string[index+len(sub... |
0163af3019a25b3b07e23835453b8c7d27d78db0 | matthijskrul/ThinkPython | /src/Twentyseventh Chapter/Example2.py | 1,241 | 3.734375 | 4 | def yes(ques):
ans = input(ques).lower()
return ans[0] == "y"
def animal():
# Start with a singleton
root = Tree("bird")
# Loop until the user quits
while True:
print()
if not yes("Are you thinking of an animal? "): break
# Walk the tree
tree = root
whi... |
a447c212c0ec0c52056bf9c8eb0158cd37ba75c8 | matthijskrul/ThinkPython | /src/Fourteenth Chapter/Exercise2.py | 3,687 | 4.1875 | 4 | # Adapt the merge algorithm to write each of these functions, as was suggested there:
#
# Return only those items that are present in the first list, but not in the second.
import random
def return_xs_unique(xs, ys):
""" merge sorted lists xs and ys. Return only those items that are present in the first list,
... |
93e70437b320b15e8a88bfec0e04d486e29b6f5c | matthijskrul/ThinkPython | /src/Eighth Chapter/Example2.py | 876 | 3.515625 | 4 | import sys
def find(strng, ch, start=0, end=None):
ix = start
if end is None:
end = len(strng)
while ix < end:
if strng[ix] == ch:
return ix
ix += 1
return -1
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Ge... |
7b396428993eb16097829ab1e46e145c1eca5af0 | matthijskrul/ThinkPython | /src/Fourth Chapter/Example1.py | 401 | 3.953125 | 4 | import turtle
def draw_square(t, sz):
"""Make turtle t draw a square of sz."""
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen() # Set up the window and its attributes
wn.bgcolor("lightgreen")
wn.title("Alex meets a function")
alex = turtle.Turtle() # Create alex... |
abfe8faf636a7497db1dba5d03ba0a747c9f7f71 | ummerfaisal/MovieRatingSystemConsoleApplication | /Movies.py | 1,189 | 3.984375 | 4 | import main
movie_list = [
{"name": "Inception", "genre": "Fiction", "rating": "PG", "year": 1954}]
def add(movie_list):
name = input("Name: ")
genre = input("genre: ")
rating = input("rating: ")
release_year = input("Year: ")
movie = {}
movie["name"] = name
movie["genre"] = genr... |
d237ddfede7a7995d45c495d24edffaba4a1fc7a | Indrajeet71/FDS-Programs | /A2.py | 1,243 | 3.84375 | 4 | def length(x) :
len =0
for _ in x :
len +=1
return len
def avg(x):
total = 0
for i in x:
total += i
avg = total/length(x)
return avg
def sorting(x):
n=length(x)
for i in range(n):
for j in range (i+1,n):
if x[i] > x[j] :
x[i],x[j... |
0ecf7ac93ac1397c7e710f4538039fa86357bb89 | Xiangtuo/leetcode | /python/JZ10_矩形覆盖.py | 534 | 3.8125 | 4 | # 题目描述
# 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
#
# 比如n=3时,2*3的矩形块有3种覆盖方法:
class Solution(object):
def rectCover(self, number):
dp = [0 for _ in range((number+1))]
if number <= 1:
return number
dp[1] = dp[0] = 1
for i in range(2, number+1):... |
ca6c5b8a2459cc1cd0404ede4b0d447983e9f959 | Xiangtuo/leetcode | /python/JZ23_二叉搜索树的后序遍历序列.py | 674 | 3.625 | 4 | # 题目描述
# # 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。
class Solution:
def VerifySquenceOfBST(self, sequence):
if len(sequence) == 0:
return False
n = len(sequence)-1
count = 0
while n:
while sequence[count] < sequence[n]:
... |
b9bfd515bdb8191c8528318b2046cae01b92d528 | armankhalili/golden | /4-rainbowAttack.py | 398 | 3.671875 | 4 | import hashlib,random
randomHashedPassword = hashlib.sha256(chr(random.randrange(0000,9999)).encode("utf-8")).hexdigest() # hashed a random number in range 0000 to 9999 by encode utf-8 and hexdigest
for i in range(0000,9999) :
guess = hashlib.sha256(chr(i).encode("utf-8")).hexdigest()
if guess == randomHas... |
f801c62af74bd3df4db3f993e9f37ff6f7712a56 | ap1124/pytrain | /func_assign/q6.py | 194 | 3.515625 | 4 | import random
def inRange(num,range1):
if (num in range1):
return True
else:
return False
num = random.randint(-10,16)
range1 = range(-2,7)
print(inRange(num,range1))
|
9c4ddfac4128dd5f94ea3e7da23b2cbba41ba9f0 | madhu8888/Python_DS | /HandleText.py | 988 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 27 23:00:46 2021
@author: madhusharma
"""
message = "Hello madhu"
print(message)
message = 'madhu \'s madhu'
print(message)
m3 = "madhu's madhu"
print(m3)
m4 = """ my name is madhu
I am a good girl"""
print(m4)
print(len(m4))
print(m4[0:5])... |
d10daa79dd8ded0588e0f8c1cafb6d6c4e57d0bd | Buscandouncamino/curso-python-jp | /ejercicio3.py | 429 | 3.828125 | 4 | #creacion de una función
def saludo():
nombre = input("ingrese su nombre:")
apellido = input("ingrese su apellido:")
sexo = input("ingrese su sexo(masculino o femenino):")
if(sexo == "masculino"):
print("Hola Sr.",nombre,apellido)
elif(sexo == "femenino"):
print("Hola Sra.",nombre,a... |
9755c6bb0904f80cb116515d1e0bc4985003c913 | worbit/compas | /src/compas/geometry/primitives/arc.py | 4,156 | 3.5625 | 4 | import math
from compas.geometry import close
from compas.geometry.primitives import Frame
from compas.geometry.primitives import Primitive
class Arc(Primitive):
"""Represents a portion of a circle's arc.
Parameters
----------
frame : :class:`~compas.geometry.Frame`
Coordinate frame at the c... |
15bb8d9b23942112105a55f5f46162e4da52347f | jerowilko/MathProgram | /Logic/IntegrityChecker.py | 573 | 3.828125 | 4 | opposing_pairs = [["{","}"],["[","]"],["<",">"]]
openers = list(zip(*opposing_pairs))[0]
closers = list(zip(*opposing_pairs))[1]
stack = []
line = input("Enter code here: ")
for c in line:
if c in openers:
stack.append(c)
if c in closers:
if len(stack) == 0:
print("... |
b8e767e7feb40dfc945b0ed21950ed8d2432ad67 | andrewkimber/gongboys | /python/mit_ocw/intro_to_programming/fibo.py | 744 | 3.578125 | 4 | global slowNumCall
global fastNumCall
slowNumCall=0
fastNumCall=0
def slowFibonaci(n):
global slowNumCall
slowNumCall += 1
if n==1 or n==2:
return 1
else:
return slowFibonaci(n-1)+slowFibonaci(n-2)
def fastFibonaci(n,memo={}):
global fastNumCall
fastNumCall +=1
if n==1 or... |
726d89d479f1bacde8f9eef4216e1e76fa73e182 | andrewkimber/gongboys | /python/heap.py | 1,456 | 3.84375 | 4 | class Heap:
def __init__(self):
self.queue = [0]
self.currentSize = 0
def __str__(self):
return str(self.queue)
def push_up(self, i):
while i // 2 > 0:
if self.queue[i] < self.queue[i / 2]:
temp = self.queue[i / 2]
self.queue[i //... |
95bf5a53f5b665dec11f4171b5b4877d2f241f08 | mohapsat/python-abspy | /tuples.py | 592 | 4.15625 | 4 | #!/usr/bin/python
# tuple are immutable lists, whose values cannot be changed
tup1 = (1,2,3)
try:
tup1.pop()
except AttributeError:
print "'tuple' object has no attribute 'pop':" + "Please pop from a list"
print tup1
tup2 = tup1 * 3
print "lenght: %d Values: %s" %(len(tup2),tup2)
tup3 = list(tup2)
print tup3
t... |
7fd97ad5e17c1174d09bec873dc7748d3a09291a | UnkwUsr/UsefulB | /tasks/MathProblem.py | 994 | 3.53125 | 4 | from random import randint
TASK_NAME = "MathProblem"
CONFIG = {
# config format: int
"min_number": 1,
# config format: int
"max_number": 50
}
class Task:
def __init__(self):
self.text = 0
self.solution = 0
def generateNew(self):
a = randint(CONF... |
4da17d0305a8c7473bd24624d04fb148a271bc7e | AbelCodes247/Google-Projects | /Calculator.py | 1,240 | 4.375 | 4 | #num1 = input("Enter a number: ")
#num2 = input("Enter another number: ")
#result = int(num1) + int(num2)
#print(result)
#Here, the calculator works the same way but the
#Arithmetic operations need to be changed manually
print("Select an operation to perform:")
print("1. ADD")
print("2. SUBTRACT")
print("3. MULTIPL... |
881fd93b70492eb124259c7e03d48c032f0c292d | samuaicc/Python | /课练八.py | 641 | 3.890625 | 4 | #-*-coding:utf-8-*-
#古典问题:有一对兔子,从出生后第三个月起每个月都生一对小兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,每个月每个月的兔子总数为
#分析:兔子的生长规律符合数列2*(1,1,2,3,5,8,13,21,,,)
a = int(input("输入要到第几个月:"))
a1 = 1
a2 = 1
for i in range(1,a+1):
if (i <= 2):
print("第%d个月,总数为2只" % i)
else:
if i == 3:
a1 = a2
... |
34f34673b9ab10d653e75b7c564289c5972c7c02 | samuaicc/Python | /课练三.py | 368 | 3.578125 | 4 | #-*-coding:utf-8-*-
#一个整数加上a后是一个完全平方数,加上b后是一个完全平方数,这个数为多少?
import math
a = int(input("输入a:"))
b = int(input("输入b:"))
for i in range(10000):
x = int(math.sqrt(i + a))
y = int(math.sqrt(i + b))
if x * x == i + a and y * y == i + b:
print("这个数字是:%d"%i)
|
3e57e1c28a68f74136cf37e0dfdcda57e9e42df8 | samuaicc/Python | /课练三十四.py | 349 | 3.609375 | 4 | #-*-coding:utf-8-*-
#输出一百以内的素数
def sushu(x,y):
list = []
for i in range(x,y + 1):
for a in range(2,i):
if i % a == 0:
break
else:
if i != 0 and i != 1:
list.append(i)
return list
if __name__ == '__main__':
print(sushu(1... |
49d4ae16fba58eaa1ebfeb45553eb575b6962b0a | EJohnston1986/100DaysOfPython | /DAY9 - Secret auction/practice/main.py | 1,283 | 4.65625 | 5 | # creating a dictionary
student = {}
# populating the dictionary with key value pairs
student = {"Name": "John",
"Age": 25,
"Courses": ["Maths", "Physics"]
}
# printing data from dictionary
print(student) # prints all key, value pairs
print(student["name"]) # prints only... |
5ce280173200e47e62e185dfaa4d4605a04bb044 | EJohnston1986/100DaysOfPython | /DAY9 - Secret auction/Auction/main.py | 700 | 3.828125 | 4 | from art import logo
# dictionary to store data
bidders = {}
proceed = True
highestBid = 0
print(logo)
while proceed:
name = input("What is your name? ")
bid = int(input("What is your bid? $"))
# add to dictionary
bidders[name] = bid
moreBidders = (input("Are there other users who want to bid, '... |
e48995ea5acb9ecd1692a717e288e3b02603646f | EJohnston1986/100DaysOfPython | /DAY10 - Calculator cont/Function/main.py | 347 | 4 | 4 | #functions with return types
def format_name(f_name, l_name):
if f_name == "" or l_name == "":
return "invalid input"
format_f_name = f_name.title()
format_l_name = l_name.title()
return f"{format_f_name} {format_l_name} "
format_string = format_name(input("What is your first name? "), input(... |
ed583b5475071835db5ac8067ccae943e10c432a | LavanyaJayaprakash7232/Python-code---oops | /line_oop.py | 844 | 4.40625 | 4 | '''
To calculate the slope of a line and distance between two coordinates on the line
'''
#defining class line
class Line():
def __init__(self, co1, co2):
self.co1 = co1
self.co2 = co2
#slope
def slope(self):
x1, y1 = self.co1
x2, y2 = self.co2
retu... |
301bf4b1144557f1dde920feaee07ca0a88d98a2 | JoaoGFarias/Projects | /Python/Classic Algorithms/CollatzConjecture.py | 1,266 | 3.53125 | 4 | ##This program is free software: you can redistribute it and/or modify
##it under the terms of the GNU General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##This program is distributed in the hope that it will be useful,
##b... |
07ee0ab4a133d2130a15cbdca52b5500a7b8f13f | a2606844292/vs-code | /慕课网/函数/4.py | 263 | 3.671875 | 4 | '''
参数
1.必须参数
2.关键词参数
'''
# def add(a, b): # 形式参数 形参
# result = a + b
# return result
def add(a=2, b=3): # 关键字参数
result = a + b
return result
c = add(a=3, b=2) # 关键字参数
|
40fa436b40b1158b0057e8f5b13208acc748dd5d | a2606844292/vs-code | /慕课网/面向对象/c4.py | 2,149 | 4.15625 | 4 |
class Student(): # 类方法
name = '' # 类变量
age = 0
sum = 0
def __init__(self, name, age): # self代表的是实例
self.name = name # 对实例变量进行赋值
self.age = age
self.__score = 0 # 加__变成私有变量
# print('student')
# print(self.name)
self.__class__.sum += 1
... |
5a59cb95bde5d778fe069ed6646ab5da1eb76af7 | a2606844292/vs-code | /慕课网/面向对象/c1.py | 599 | 3.953125 | 4 | # 面向对象
# 有意义的面向对象的代码
# 类、对象
# 实例化
# 类最基本的作用:封装
# 模板
class Student():
name = ''
age = 0
# 行为与特征
def do_homework(self):
print('homework')
class Printer(Student):
def print_file(self):
print('name' + self.name)
print('age'+str(self.age))
# 方法和函数的区别
... |
e30f37d0c9b24ec8403f066958d3440518bc0655 | a2606844292/vs-code | /test2/高阶内置函数/Lambda表达式介绍/lambda.py | 213 | 4.03125 | 4 | # def add(num1,num2):
# result=num1+num2
# return result
# print(add(1,2))
#相加
super_add=lambda num1,num2:num1+num2
#相乘
multiply=lambda a,b:a*b
print(super_add(1,2))
print(multiply(1,2)) |
7500757707741d9b85b2c04948f7ce376d289b63 | greggelong/python-songs | /pysong3.py | 179 | 3.8125 | 4 | x = set(["a","b","c","d"])
def running():
print("running")
while True:
print(x)
if x == set():
running()
break
else:
x.pop() |
f90641bca23f4c4990b557f7e1e89af3b2ec0fde | songlei1994/pythonlearning | /class.py | 268 | 3.65625 | 4 | # -*- coding:utf-8 -*-
class student(object):
def __init__(self,name,score):
self.name=name
self.score=score
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
lily=student('kama',30)
lily.score |
eaddee2ae93bffd0721fe97108f325befd4b28e4 | xiaoxiaoyao/MyApp | /PythonApplication1/自己的小练习/PythonExit.py | 1,834 | 3.609375 | 4 |
#代码如下,可以运行一下看效果
import os,sys
#%% os._exit(0)
try:
print('run: os._exit(0) # os._exit(n), 直接退出, 不抛异常, 不执行相关清理工作. 常用在子进程的退出')
os._exit(0) # os._exit(n), 直接退出, 不抛异常, 不执行相关清理工作. 常用在子进程的退出
except:
print('except:xiaoyao_os._exit(0)_知乎:小尧') # 不运行
finally:
print('xiaoyao_os._exit(0)quit_知乎:小尧') # 不运行
#%% ... |
004838c079f47d4c37ad96cbfea91888e5438b65 | xiaoxiaoyao/MyApp | /PythonApplication1/自己的小练习/for.py | 454 | 3.625 | 4 | # -*- coding: utf-8 -*-
counter=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
print('''
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
if you use for
it will be:''')
for item in counter:
print(item)
if item==5:
item=counter[8]
print(item)
print('''
you should use while
it will be:''')
i = 0
length = l... |
abed6cad2a6c2b774fa002d6c97d67f045522021 | xiaoxiaoyao/MyApp | /PythonApplication1/deeplearning/examples/recurrent.py | 6,822 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Recurrent network example. Trains a bidirectional vanilla RNN to output the
sum of two numbers in a sequence of random numbers sampled uniformly from
[0, 1] based on a separate marker sequence.
'''
from __future__ import print_function
import numpy as np
import thea... |
9d135639fbb39582b54a936213d8902b0ff0bc69 | fawazn/ABCs | /AssociativeArray.py | 708 | 3.515625 | 4 | '''Simple Associative Array class'''
''' This is a basic data structure allowing for constant time access
(of course, python has a built in dictionary type that is far more versatile
so you wouldn't actually need to use something like this.)'''
class Node:
def __init__(self,k,v):
self.key = k
self.... |
cced3cb263d1d43bb685603b1540377e1e20e403 | krnets/exercism-python | /armstrong-numbers/armstrong_numbers.py | 134 | 3.625 | 4 | def is_armstrong_number(number):
n = str(number)
n_digits = len(n)
return sum(pow(int(x), n_digits) for x in n) == number
|
11236ce82d8ebd8e9cb57b276cc8032e3ba988cd | krnets/exercism-python | /beer-song/beer_song_3.py | 867 | 3.859375 | 4 | def verse(n):
if n == 0:
return ('No more bottles of beer on the wall, no more bottles of beer.',
'Go to the store and buy some more, 99 bottles of beer on the wall.')
elif n == 1:
return ('1 bottle of beer on the wall, 1 bottle of beer.',
'Take it down and pass i... |
64bc449c49ffeab3c57126475af9d1747fc12040 | krnets/exercism-python | /robot-name/robot_name.py | 794 | 3.609375 | 4 | import random
import string
NAME_CACHE = set()
NAME_CACHE_LIMIT = 26**2 * 10**3
def generate_name():
if len(NAME_CACHE) > NAME_CACHE_LIMIT:
raise RuntimeError(
'All possible name combinations have been exhausted')
name = combine_prefix_suffix()
while name in NAME_CACHE:
name =... |
e1bd3323eedc57df48aaa80c8713e85782350d61 | krnets/exercism-python | /pig-latin/pig_latin_1.py | 2,420 | 3.984375 | 4 | import re
# if begins with a vowel sound, add an "ay" sound to the end of the word.
# Please note that "xr" and "yt" at the beginning of a word make vowel sounds (e.g. "xray" -> "xrayay", "yttria" -> "yttriaay").
# if begins with a consonant sound, move it to the end of the word
# and then add an "ay" sound to... |
272d66049f46f783fd3b12ccad7980b790648878 | krnets/exercism-python | /rotational-cipher/rotational_cipher_1.py | 855 | 3.890625 | 4 | def rotate(text, key):
res = []
for ch in text:
if ch.isalpha() and ch.upper() == ch:
x = chr((ord(ch) - 64 + key) % 26 + 64)
res.append(x)
elif ch.isalpha() and ch.lower() == ch:
x = chr((ord(ch) - 97 + key) % 26 + 97)
res.append(x)
elif n... |
4d386f77d415e5e9335763ebb49bc683af7c0fbf | pbeata/DSc-Training | /Python/oop_classes.py | 2,087 | 4.40625 | 4 | import turtle
class Polygon:
def __init__(self, num_sides, name, size=100, color="black", lw=2):
self.num_sides = num_sides
self.name = name
self.size = size # default size is 100
self.color = color
self.lw = lw
self.interior_angles_sum = (self.num_sides - 2) * 180
self.single_angle = self.interior_ang... |
2d840cb24543cc55b9cf78d8b5569286db52c510 | pbeata/DSc-Training | /02-Udemy-DS-Bootcamp/exercise_84.py | 1,097 | 4.15625 | 4 |
# Paul A. Beata
# January 29, 2021
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import skew
def compute_skewness(x):
n = len(x)
x_mean = x.mean()
a = x - x_mean
b = a ** 3
numer = (1 / n) * b.sum()
c = a ** 2
d = (1 / n) * c.sum()... |
0e087f65ba7b781cda0568712dee4975a49a1bd1 | OkelleyDevelopment/Caesar-Cipher | /caesar_cipher.py | 1,258 | 4.21875 | 4 | from string import ascii_letters
def encrypt(message, key):
lexicon = ascii_letters
result = ""
for char in message:
if char not in lexicon:
result += char
else:
new_key = (lexicon.index(char) + key) % len(lexicon)
result += lexicon[new_key]
return... |
f20d0d9a1083b1cce22713ebe9f53d487e44d384 | smaripadaga/PythonBasics | /nested.py | 140 | 3.640625 | 4 | #nested decisions
x = 42
if x > 2:
print('x is greater than 2')
if x > 45:
print('x is smaller than 45')
print ('all done')
|
3a8c352aa4c4c3aa86aefcd2dfaf5f2f0d89f76a | smaripadaga/PythonBasics | /EvenOdd.py | 182 | 4.21875 | 4 | Number = int(input("Enter Number\n"))
if Number%2 == 0:
print("This number " + str(Number) + " is Even")
elif Number%2 == 1:
print("This number " + str(Number) + " is Odd")
|
ec839c861e29ec4575993cebc391e1f2ab6357e0 | leogtzr/python-cookbook-code-snippets | /strings_and_text/re_replace1.py | 142 | 3.609375 | 4 | import re
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
new_text = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\2-\1', text)
print(new_text)
|
ea228f1a8ab8e5e45baf9931d2e964ed6aee38cb | leogtzr/python-cookbook-code-snippets | /strings_and_text/regex_findall1.py | 486 | 3.609375 | 4 | import re
# Be aware, though, that if you’re going to perform a lot of matching or searching,
# it usually pays to compile the pattern first and use it over and over again.
# The module-level functions keep a cache of recently compiled patterns, so there isn’t a
# huge performance hit, but you’ll save a few lookups an... |
4c3440de8200fca3a2cea0ce13861af61710d894 | leogtzr/python-cookbook-code-snippets | /strings_and_text/starts_ends_with_tuple1.py | 254 | 3.53125 | 4 | filenames = ['Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h']
for fn in [name for name in filenames if name.endswith(('.c', '.h'))]:
print(fn)
is_there_a_python_file = any(name.endswith('.py') for name in filenames)
print(is_there_a_python_file)
|
9517e08d57e3fdd9dece1f7da2090d78813a22ec | leogtzr/python-cookbook-code-snippets | /data_structures_and_algorithms/calculating_with_dictionaries2.py | 357 | 3.6875 | 4 | prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price_key = min(prices, key=lambda k: prices[k])
max_price_key = max(prices, key=lambda k: prices[k])
#print(min_price_key)
min_price_value = prices[min_price_key]
max_price_value = prices[max_price_key]
print(min... |
30d77c014f1e215c94c3394187c5a665a846735a | katiakata1/Codewars_python | /Find_the_odd_int.py | 490 | 4.03125 | 4 | # Given an array of integers, find the one that appears an odd number of times.
# There will always be only one integer that appears an odd number of times.
#EXAMPLE:
# [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5] return 5
# [1,1,2,-2,5,2,4,4,-1,-2,5] returns -1
def find_it(seq):
my_dict = {}
for num in seq:
... |
069bd2864b0069162f0583f5c13a377a89b52f16 | cdiam/my_python | /StoneRiverLearning/classes.py | 327 | 3.703125 | 4 | ##Classes
class calc:
def add(x,y):
answer = x + y
print(answer)
def sub(x,y):
answer = x - y
print(answer)
def mul(x,y):
answer = x * y
print(answer)
#calc.add(2,3)
import statistics
exList = [1,4,5,6,7,6,5,9,8,1]
x = statistics.median(exList)
pri... |
4d1b95b6a125229ffc2000cdaee7fe4db029484b | cdiam/my_python | /CodeAcademy_Learning/script_py_for_codeacademy.py | 13,220 | 4.125 | 4 | #!/usr/bin/python
#This is the scripts from codeacademy
#Set spam equal to 1 using modulo on line 3!
spam =3%2
span2 = 4%2
print "The first is %d and the second is %d" % (spam, span2)
# Tip Calculator!
meal = 44.50
tax = 0.0675
tip = 0.15
meal = meal + meal * tax
total = meal + (meal * tip)
print("%.2f" % tot... |
0e97eff70f33d88c920ff932f713445b86dc6fbc | dp2seC/Robot_framework | /RobotframeworkRepo/Custom_Lib/CSV.py | 658 | 3.734375 | 4 | import csv
import os.path
def read_csv_file(filename):
data = []
with open(filename, 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
data.append(row)
return data
def write_into_csv(filename, items):
file_exists = os.path.isfile(filename)
... |
2ffe6dce6530873a1ffa6b8c25414faf1608805c | raunakrathour/Monty_Python_Class | /Task_2/My_Files/filegenerator.py | 346 | 3.546875 | 4 | import os
import random
import string
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
# print(type(randomString(10)))
for i in range(100):
fd=open((randomString(10)+'... |
907cb2d0bdc0f6d504f26f66fae53da78ddce898 | rarezhang/ucberkeley_cs61a | /lecture/l9_fucnction.py | 3,545 | 4.65625 | 5 | """
lecture 9
function example
"""
# functional abstraction
## argument
## function
# function name
## meaning or purpose
## effect, behaviour, value returned
# test-driven development
## test: domain, range, behavior of a function
## tricky edge cases
## develop incrementally and test each piece before moving
##... |
f194918b18cd8728d7f5ec5854152b8d5bc4cc2e | rarezhang/ucberkeley_cs61a | /lecture/l15_inheritance.py | 987 | 4.46875 | 4 | """
lecture 15
inheritance
"""
# inheritance
# relating classes together
# similar classes differ in their degree of specialization
## class <name>(<base class>)
# example: checking account is a specialized type of account
class Account:
interest = 0.04
def __init__(self, account_holder):
self.balance = 0
... |
21964a6a9150ffc373599207402aef774f5917a8 | rarezhang/ucberkeley_cs61a | /lecture/l10_data_abstraction.py | 1,233 | 4.4375 | 4 | """
lecture 10
Data Abstraction
"""
# data
print(type(1))
## <class 'int'> --> represents int exactly
print(type(2.2))
## <class 'float'> --> represents real numbers approximately eg. 0.2222222222222222 == 0.2222222222222227 True
print(type(1+1j))
## <class 'complex'>
print(type(True))
## <class 'bool'>
print(1+1.2)... |
efd57652ea766f2eead4561e8d9737163de0ef8a | cIvanrc/problems | /ruby_and_python/2_condition_and_loop/check_pass.py | 905 | 4.1875 | 4 | # Write a Python program to check the validity of a password (input from users).
# Validation :
# At least 1 letter between [a-z] and 1 letter between [A-Z].
# At least 1 number between [0-9].
# At least 1 character from [$#@].
# Minimum length 6 characters.
# Maximum length 16 characters.
# Input
# W3r@100a
# Output
#... |
84cbfa338bbf4e04ed380839b5fa67237040451d | cIvanrc/problems | /ruby_and_python/python_oop/self.py | 386 | 3.796875 | 4 | class Employee:
def employeeDetaials(self):
self.name = "ivan"
print("Name: ", self.name)
age = 23
print("Age: ", age)
def printEmployeeDetails(self):
print("Printing in another method")
print("Name: ", self.name)
print("Age: ", age)
employee = Emplo... |
74d1f20b9a008084b1200a73a16d6e7d79866db0 | cIvanrc/problems | /ruby_and_python/8_math/binary_to_decimal.py | 484 | 4.40625 | 4 | # Write a python program to convert a binary number to a decimal number
class Convert():
def binary_to_decimal(self):
binary_num = list(input("Input a binary number: "))
value = 0
len_binary_num = len(binary_num)
for i in range(len_binary_num):
digit = binary_num.pop... |
fb9c0c70639a30d7522bd230e27ff7aa9386bf4b | cIvanrc/problems | /ruby_and_python/7_class/hotel.py | 480 | 3.625 | 4 |
class Hotel():
def __init__(self, nombre="*", ubicacion="*", puntaje=0, precio = float("inf")):
if Numeros().es_numero(puntaje) and Numeros().es_numero(precio):
self.puntaje = puntaje
self.precio = precio
else:
raise TypeError("Tipo de dato erradu")
if p... |
a3b19f02a72320a0f15e090ec5b63f9cc225beaa | cIvanrc/problems | /ruby_and_python/4_string/html_tag.py | 366 | 3.75 | 4 | # Write a Python function to create the HTML string with tags around the word(s).
# Sample function and result :
# add_tags('i', 'Python') -> '<i>Python</i>'
# add_tags('b', 'Python Tutorial') -> '<b>Python Tutorial </b>'
def add_tags(tag, message):
return "<{tag}>{message}</{tag}>".format(tag=tag, message=messag... |
e1626dd073f8339bfb17f7780ef670290f5b290a | cIvanrc/problems | /ruby_and_python/14_recursion/greatest_gcd.py | 269 | 4 | 4 | # Write a Python program to find the greatest common divisor (gcd) of two integers
def gcd(a, b):
low = min(a,b)
high = max(a,b)
if low == 0:
return high
elif low == 1:
return 1
return gcd(low, high%low)
print(gcd(12,14))
|
88552fac540e0fe8ae7e2930ea7527e2187b69ae | cIvanrc/problems | /ruby_and_python/14_recursion/binary_string.py | 627 | 3.84375 | 4 | import pdb
# generate all the binry strings with n bits. Assume A[0..n - 1] is an array of size n
# def append_at_beginning_front(x, L):
# return [ x + element for element in L ]
# def bit_strings(n):
# if n == 0: return []
# if n == 1: return ["0", "1"]
# return append_at_beginning_front("0", bit_st... |
5ca2ba498860e710f44477f96523c0413ed54cbe | cIvanrc/problems | /ruby_and_python/12_sort/merge_sort.py | 1,497 | 4.40625 | 4 | # Write a python program to sort a list of elements using the merge sort algorithm
# Note: According to Wikipedia "Merge sort (also commonly spelled mergesort) is an 0 (n log n)
# comparasion-baed sortgin algorithm. Most implementations produce a stable sort, which means that
# the implementation preserves the input or... |
0390a0195030ad0c08247141822c61a2407662c5 | cIvanrc/problems | /ruby_and_python/3_list/remove_duplicates.py | 404 | 3.90625 | 4 | # Write a Python program to remove duplicates from a list.
# Input a = [10,20,30,20,10,50,60,40,80,50,40]
# Output {40, 10, 80, 50, 20, 60, 30}
def remove_duplicates():
myArray = [10,20,30,20,10,50,60,40,80,50,40]
without_duplicates = []
for i in myArray:
if i not in without_duplicates:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.