blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0622a8a418e06b920759274259881fb2a4781b8d | MrRickSan/python3bootcamp | /section22 - modules/exercise74 - iskeyword.py | 229 | 3.8125 | 4 | from keyword import iskeyword
def contains_keyword(*args):
for x in args:
if iskeyword(x) == True: return True
return False
print(contains_keyword('rick', 'test'))
print(contains_keyword('rick', 'test', 'def')) |
2432f1c5e46507b0468abe8d9d53d48332e40273 | yfeng2018/IntroPython2016a | /students/JohnRudolph/session3/rot13.py | 1,528 | 4.40625 | 4 |
def getnumref(let):
'''
This function accepts any ASCII character
Function to create ASCII reference for ROT13 encryption
First if checks if letter is Upcase A-Z and performs ROT13
Second if checks if letter is Lowcase a-z and performs ROT13
If not Upcase or Lowcase A-Z or a-z then retain ordinal of character
'... |
ebb8c38815ff77757aadc8887155c04b6fa5ef8c | orbardugo/English_Exams_System | /src/Student.py | 5,516 | 3.78125 | 4 | import json
import os
import random
import time
class Student(object):
def __init__(self, name, ident):
self.name = name
self.ident = ident
self.correct_ans_counter = 0
def train(self):
""" train function will gives you all types of questions, when you answer you will receive ... |
0157fc50a376f4c79e3d37b041b85499a8d1db8f | ball4410/python-challenge | /PyPoll/main.py | 2,193 | 3.703125 | 4 | #Modules
import os
import csv
import pandas as pd
# Get data file needed for analysis
election_data_path = "./Resources/election_data.csv"
#Store data into a pandas data frame
election_file_df = pd.read_csv(election_data_path)
#Create variables to store values needed for summary
total_votes = 0
khan_votes = 0
corre... |
1dc5bc5308f74ca53aaf21d890db45fe21650a15 | RapetiBhargav/datascience | /2019-may/1.python/11.functional-style.py | 1,130 | 4.34375 | 4 | #functions are first class objects i.e., they can be used like other data objects
funcs = [sum, len, type]
for func in funcs:
print(func(range(1,5)))
#anonymous functions: functions without name
funcs = [lambda x: x, lambda x: x**2, lambda x: x**3]
for func in funcs:
print(func(10))
#higher order fu... |
5575451c70757bc7b7f7178b11044a61ae9a45d7 | jaxmandev/Python_JSON_Task | /exchange.py | 1,038 | 3.96875 | 4 | # the json module is imported
# to handle a .json file
import json
# class created and methods initiated
class Currency:
def __init__(self):
self.xchange_rates = self.load_dic()
self.display_basic_info()
self.display_rates()
# store .json file data in a python object
def load_... |
37c1a27d7f088d992759f80df681c6cbcea2b067 | subahan983/Basic-programs-in-python | /Multiply.py | 171 | 4.375 | 4 | # In this program, the product of two numbers is found.
num1 = int(input('Enter any number : '))
num2 = int(input('Enter any number : '))
print('Product = ',num1*num2)
|
059b7d3225a615c54bb30459130fa7ad17f66d17 | czhhhhhhh/pythonchenzehua | /day1.py | 3,242 | 3.90625 | 4 | # email = '666@qq.com'
# for e in email:
# o = ord(e)-10
# print(chr(o),end='')
# year = int(input('请输入一个年份:'))
## if (year % 4 == 0 and year % 100 !=0) or (year % 400 == 0):
# print ('%d 是闰年' %year)
# else:
# print ('%d 不是闰年' %year)
#作业1
# C = float(input('请输入一个摄氏温度... |
75254e830a3eb1443aef2491b3ac494401d1d008 | nr96/WebSearch | /WebSearch.py | 2,082 | 3.625 | 4 | import requests
def main():
splitTxt = [] # list to hold parsed txt from webpage
keyHist = [] # list to hold keyword history
page = '' # var to hold webpage url
page = getWebpage(page) # get webpage url and store in page
txt = parseWebpage(page) # parse webpage content into txt
splitTxt = splitPage(txt, splitT... |
af9d0977a048859c9698f1c3cbffbe9de37f5121 | gustavw10/pythonaflevering | /utils.py | 1,005 | 3.75 | 4 |
import os
import csv
def get_file_names(folderpath, out="output.txt"):
""" takes a path to a folder and writes all filenames in the folder to a specified output file"""
files = os.listdir(folderpath)
with open(out, 'w') as output_file:
for file in files:
output_file.write(file + '\n'... |
da8ddd51f04168591d75f04eb95b3e9c52666237 | jarelio/FUP | /Lista 1/1a.py | 201 | 4 | 4 | nota1 = float(input("Digite o primeiro número: "))
nota2 = float(input("Digite o segundo número: "))
media = (nota1*2 + nota2*3)/5
print("A média ponderada desses dois números é %.3f" %media)
|
5df8c7162f9f8344c1887f95dc6aa5db932eeed9 | ogoshi2000/smile | /crazysmiley2/crazysmiley2.pyde | 2,016 | 3.578125 | 4 | def setup():
size(400,400)
frameRate(10)
fullScreen()
number=100
radius=300
circle_size=50
max_circle=80
def draw():
global number,radius,circle_size,max_circle
g=(frameCount%max_circle)
if g < max_circle/2:
circle_size=g
else:
circle_size=max_circle-g
k=f... |
1a77b99766e725e3b40c5c4c2ea13f31aa98413a | alexparunov/leetcode_solutions | /src/1-100/_96_unique-binary-search-trees.py | 370 | 3.546875 | 4 | """
https://leetcode.com/problems/unique-binary-search-trees/
"""
class Solution:
def numTrees(self, n: int) -> int:
# Calculate N-th Catalan Number
cat = [0] * (n + 1)
cat[0] = 1
cat[1] = 1
for i in range(2, n + 1):
for j in range(i):
cat[i] +... |
05ddbd71a0244f9a2b1af78697f19221712ad097 | poohcid/class | /PSIT/170.py | 965 | 3.671875 | 4 | """ OTP """
def main():
""" OTP """
otp = input()
while otp != "0":
check = list(map(lambda x: otp.count(x), set(otp)))
if len(otp) == 4:
print("Valid" if verified(2, 1, list(check)) else "Invalid")
elif len(otp) == 6:
if verified(2, 2, list(check)):
... |
fad2243b7117d7956d43af65aa01b6b1f5b95637 | HOZH/leetCode | /leetCodePython2020/2265.count-nodes-equal-to-average-of-subtree.py | 856 | 3.515625 | 4 | #
# @lc app=leetcode id=2265 lang=python3
#
# [2265] Count Nodes Equal to Average of Subtree
#
# @lc code=start
# 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:... |
a527be8f0092e5e5cbed876c2264b750373dc737 | Eloquade/Python_zip_function | /main.py | 779 | 3.953125 | 4 | list1 = [1, 2, 3, 4, 5, 6]
list2 = ['one', 'two', 'three', 'four', 'five', 'six']
zipped = list(zip(list1, list2))
print(zipped)
unzipped = list(zip(*zipped))
print(unzipped)
for l1, l2 in zip(list1, list2):
print(l1)
print(l2)
items = ['apple', 'banana', 'grapes']
quantity = ['1', '2', '3']
prices = ['123'... |
32a2f8c08363a9ce97f48e0c3741d54bec0c9150 | liyi-1989/neu_ml | /code/data/data_collector.py | 9,874 | 3.8125 | 4 | import pdb
import numpy as np
class DataCollector:
"""Data collection class used to record data during algorithm execution for
subsequent analysis.
There are three concepts used by this class: 'trial', 'run', and
'iteration'. A 'trial' exists at the level of a particular algorithm
execution and c... |
b579040e68768d3c6ecd65eeda9f53d886ed3f52 | thatnerd2/Algorithms-Data-Structures | /misc-practice/costly-chess/costlychess.py | 412 | 3.890625 | 4 | def costFcn (start, end):
return start[0]*end[0] + start[1]*end[1];
# Define P_px->py to be the minimum cost to get from start to end
# Define positions to be p1, p2, p3, p4, end
# P_p1->p2 is the minimum cost of P_p1->p2 + Pp3->end
# base case: P_p?->end is min(all eight possibilities)
def compute(p, end, cost):... |
453912539d8c95d07b221613b0581249d3f98473 | melanieren/MoMA-analysis | /MoMA-data-analysis.py | 4,526 | 3.734375 | 4 | # Import libraries and data
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df_artworks = pd.read_csv('data/artworks.csv')
print(df_artworks.shape)
print(df_artworks.head())
df_artists = pd.read_csv('data/artists.csv')
print(df_artists.shape)
print(df_artists.head())
# 1. Artists with most pi... |
ac50a6bc11e3457aa288c818563df86fce381b1c | z727354123/pyCharmTest | /2018-01/01_Jan/15/02-methodUse.py | 376 | 3.5 | 4 | class Person:
name = "lisi"
def func1(self):
print('这是一个 实例方法', self.age, self.name)
return self
@classmethod
def func2(cls):
print(cls.__bases__[0].name)
p1 = Person()
p1.age = 111
funcX = p1.func1
# funcX()
class Person2(Person):
name = "XXXXX"
pass
p2 = Person2()
... |
419840d793c856513954dbb8a1b10e6a49d0e06e | NachbarStrom/public-python-nachbarstrom-commons | /nachbarstrom/commons/world/roof.py | 1,943 | 3.53125 | 4 | from enum import Enum
import math
class RoofType(Enum):
flat = 0
gabled = 1
halfHipped = 2
hipped = 3
mansard = 4
pyramid = 5
round = 6
class RoofOrientation(Enum):
East = 0
SouthEast = 1
South = 2
SouthWest = 3
West = 4
class Roof:
def __init__(self, roof_type... |
af3945be1d356c3952c1566e5129ae41c780056e | longlee218/Python-Algorithm | /017_week2/17+2_too_long_words.py | 885 | 4.25 | 4 | """
Let's consider a word too long, if it length is strictly more than 10 characters. All too long worlds
should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them
we write a number of letters between the ... |
bdc30567bd67fce78bc7dd3c6bb5e8a92ad0578b | Nandik-Aminur-Peer-Programming/CodechefProblems | /SpecialString.py | 1,932 | 3.75 | 4 | """You are given a string S and you want to make it (n,k) special.
String A is (n,k) special if after concatenating n copies of string
A we get at least k substring of A in the resulting string (Overlapping substrings also count).
Your task is to find the minimum number of characters you need to alter to make stri... |
076d7e8a94a314c3b999633d94a72683de7c61be | pravinmaske/TorontoPython | /a2.py | 2,599 | 4.28125 | 4 | def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
... |
9473922c20a57bc5868f4c2bae76bbf3f134ee7f | szabgab/slides | /python/examples/format/formatted_float.py | 575 | 3.71875 | 4 | x = 412.345678901
print("{:e}".format(x)) # exponent: 4.123457e+02
print("{:E}".format(x)) # Exponent: 4.123457E+02
print("{:f}".format(x)) # fixed point: 412.345679 (default precision is 6)
print("{:.2f}".format(x)) # fixed point: 412.35 (set precision to 2)
print("{:F}".format(x)) # same as f.... |
599301e824c68e3463785063859046dc49b9edc0 | 2jigoo/study_algorithm | /3-3.py | 1,134 | 3.828125 | 4 | # n * m 개의 카드
# 뽑고자 하는 행 선택
# 그 행중에서 가장 작은 수의 카드
# 최종적으로 가장 높은 숫자의 카드를 뽑을 수 있도록!
def using_double_for(data, result):
min_value = 20000
# 해당 행에서 min값과 아이템 비교해서 최소값 저장
for a in data:
min_value = min(min_value, a)
# 저장한 최소값이 현재까지 찾은 값과 비교해 더 큰 값을 저장
print("이번 행의 최소값: ", min_value, "현재까지 최대값:... |
aa6586351e351ae8c8d191639acaaf7e4ad1f920 | ISMAILFAISAL/program | /multiple of 5/multiple of five.py | 55 | 3.609375 | 4 | num=int(input())
for i in range(1,6):
z=i*num
print(z)
|
b7bee446e46797634e8be10cb66d845bb14db141 | NallamilliRageswari/Python | /Exor_ex.py | 271 | 3.78125 | 4 | #n=4
#start=3
#output:8
#explaination:array nums is equal to [0,2,4,6,8] where [0^2^4^6^8] exor operation .
n=int(input("Enter a number :"))
start=int(input("Start number:"))
x=0
for i in range(n):
x^=start+(2*i)
print("after applying exor operation:"+str(x))
|
4f2bef7403690d885a3cae6df7403f722e213273 | AK-1121/code_extraction | /python/python_23552.py | 96 | 3.65625 | 4 | # Python list to list of lists
l = [1.0, 2.0, 3.0]
print [[x] for x in l]
[[1.0], [2.0], [3.0]]
|
606612bfd3f79b84648fc28d629e9d773be3a65b | jcwu411/Advective_equation | /plot_data.py | 1,305 | 3.625 | 4 | #!/usr/bin/env python3.8
"""
Created on 15/11/2020
@author: Jiacheng Wu, jcwu@pku.edu.cn
"""
import numpy as np
import matplotlib.pyplot as plt
def plot_2d(n, x, y, color, lw, lb,
ti="Plot", xl="X", yl="Y", legendloc=4,
xlim=(0, 1), ylim=(0, 1), ylog=False,
fn="plot2d.pdf", sa=Fa... |
60f3c46e1307438c3c95c75c98806675a416e77f | pitz-qa/python | /REST API with Fask And Python/pythonBasics/in StatWithIfStat.py | 233 | 4.1875 | 4 | movies_watched = {"3idiots","Tere Naam","Chakh De India"}
user_movie = input("Enter movie name: ").lower()
if user_movie in movies_watched:
print(f"I have watched {user_movie} too!")
else:
print(f"I didnt watched {user_movie}") |
77a37cef97957b1226c3b2313ec12a2f211f6c3c | cnrgrl/PYTHON-1 | /mp01/rpsls.py | 1,177 | 3.90625 | 4 | import random
def rpsls(player_choice,computer_choice):
d=(computer_choice-player_choice)%5
if d==1 or d==2:
print("computer wins")
elif d==0:
print("Spiel zieht")
else:
print("player wins")
def name_to_number(name):
if name == "rock":
number=0
elif name=="paper... |
1b166af4033338f867d38fd69e0819e77ca9f8e6 | amjadtaleb/Computational_Physics_in_Python | /fourier_transform.py | 4,013 | 3.609375 | 4 | import numpy as np
from scipy.fft import fft, ifft
def nextpow2(n):
"""
returns next power of 2 as fft algorithms work fastest when the input data
length is a power of 2
Inputs
------
n: int
next power of 2 to calculate for
Returns
-------
np.int(2 ** m_i): int
... |
a03c5da62c8b866e07a873378439addb6896353b | kugmax/show-me-the-data-structures | /problem_4.py | 3,377 | 3.828125 | 4 | class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = set()
self.users = set()
def add_group(self, group):
self.groups.add(group)
def add_user(self, user):
self.users.add(user)
def get_groups(self):
return self.groups
def ... |
d2f7d6576fb46ce72ae73967d933582023e3ddc1 | TsymbaliukOleksandr1981/Python-for-beginners | /lesson_2/task_3.py | 121 | 3.921875 | 4 | import math
radius = float(input("Input circle radius: "))
perimetr = math.pi * 2 * radius
print("Perimetr = ",perimetr)
|
004d87d51091915a44b00a3ba024700056837167 | amit081thakur/assignment3 | /question5.py | 381 | 3.625 | 4 | Python 3.7.0b5 (v3.7.0b5:abb8802389, May 31 2018, 01:54:01) [MSC v.1913 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> A=[1,2,3,4]
>>> B=[5,6,7,8,9]
>>> A.sort()
>>> B.sort()
>>> A
[1, 2, 3, 4]
>>> B
[5, 6, 7, 8, 9]
>>> C=A+B
>>> C
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print("ne... |
3894c7ec8358539696700c1d996e665dd6a9ec9c | sheelabhadra/LeetCode-Python | /287_Find_the_Duplicate_Number.py | 775 | 3.921875 | 4 | """PROBLEM:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least
one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
"""
"""SOLUTION:
Similar to cycle detectio... |
dbdc3583bc8b8aa12652c2a76626011e271b43de | Bellroute/algorithm | /python/book_python_algorithm_interview/ch10/design_circular_deque.py | 1,700 | 3.6875 | 4 | # 리트코드 641. Design Circular Deque
class ListNode:
def __init__(self, val=None, prev=None, next=None):
self.val = val
self.prev = prev
self.next = next
class MyCircularDeque:
def __init__(self, k: int):
self.max = k
self.len = 0
self.head = ListNode(None)
... |
7f5d0e930ea20f24e36551febf605a4331379eed | talk2sunil83/UpgradLearning | /06Deep Learning/02Convolutional Neural Networks/02Building CNNs with Python and Keras/02Building CNNs in Keras - MNIST/Building a Basic CNN The MNIST Dataset.py | 9,593 | 4.40625 | 4 | # %% [markdown]
# # Building a Basic CNN: The MNIST Dataset
#
# In this notebook, we will build a simple CNN-based architecture to classify the 10 digits (0-9) of the MNIST dataset. The objective of this notebook is to become familiar with the process of building CNNs in Keras.
#
# We will go through the following step... |
695870486e96d4dcb50a5f812fb647d1d48ef3f5 | advorecky/python-basics | /lesson4/exercise01.py | 1,032 | 3.828125 | 4 | # 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
# В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия.
# Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
from sys import argv
productivit... |
5966f7a0f57fa534445c0bbee25b92c55f9255e0 | AaravGang/KidNeuralNetwork | /SimplePerceptron/Perceptron.py | 1,254 | 3.890625 | 4 | from random import uniform
class Perceptron:
def __init__(self,n,lr):
self.weights = [uniform(-1,1) for _ in range(n)] # initialise the weights, number of weights is same as number of inputs
self.c = lr # learning rate is constant
def train(self,inputs,desired):
... |
223d42f927bf50c98e0c95ab84a58ff6d6ae30be | All3yp/Daily-Coding-Problem-Solutions | /Solutions/115.py | 1,732 | 4.03125 | 4 | """
Problem:
Given two non-empty binary trees s and t, check whether tree t has exactly the same
structure and node values with a subtree of s. A subtree of s is a tree consists of a
node in s and all of this node's descendants. The tree s could also be considered as a
subtree of itself.
"""
from DataStructures.Tree ... |
b4c0ffd41dabfc4a7bbcfbc0c61f1f625c7a5266 | jdukosse/LOI_Python_course-SourceCode | /Chap15/recursivecount.py | 763 | 3.96875 | 4 | def count(lst, item):
""" Counts the number of occurrences of item within the list lst """
if len(lst) == 0: # Is the list empty?
return 0 # Nothing can appear in an empty list
else:
# Count the occurrences in the rest of the list
# (all but the first element)
co... |
bb8af46f1242bd5934a3f355cdb46f1b3ea5cb19 | lcookiel/ukr_tax_id | /main.py | 1,516 | 3.546875 | 4 | from datetime import date
import math
def birthcode(birth_date):
birth_date = birth_date.split("-")
birth_date = date(int(birth_date[0]), int(birth_date[1]), int(birth_date[2]))
delta = birth_date - date(1899, 12, 31)
return delta.days
def control_digit(taxid):
control_sum = int(taxid[0])*(-1) +... |
5ecfeefa0476b35b33c5884ca25728166b05d780 | Navajyoth/Anand-Python | /Anand python/unit2/u2prob17.py | 105 | 3.5625 | 4 | def reverse(s):
for i in reversed(open(s).readlines()):
print i.strip()
reverse('cat.txt')
|
3d58cfc2cca41f2fc7c9e05c5412bc7cb6f3e67f | PurpleMyst/aoc-2018 | /03/easy.py | 870 | 3.578125 | 4 | import collections
SQUARE_SIDE = 1000 # inches
Claim = collections.namedtuple("Claim", "x y w h")
def points(claim):
for dy in range(claim.h):
y = claim.y + dy
for dx in range(claim.w):
x = claim.x + dx
yield (x, y)
def parse_claims():
lines = open("03/input.txt... |
1d742cda2a7123e39385003ac4d00f664efd6b3b | GB071957/Advent-of-Christmas | /Advent of Code problem 1 part 2 - expenses add to 2020.py | 772 | 3.609375 | 4 | # Advent of Code problem 1 part 2 Program by Greg Brinks
# Find three numbers in the list of 200 that add to 2020 and multiply them together
from timeit import default_timer as timeit
start= timeit()
import csv
expenses = []
with open("Advent of Code problem 1.txt") as expense_file:
file_contents = csv.reade... |
7828840d7e9827a56c42d6d84360a1f65ea002c6 | peltierchip/the_python_workbook_exercises | /chapter_8/exercise_183.py | 2,787 | 3.65625 | 4 | ##
# Find the longest sequence of elements starting with the chemical element entered from the user, so that each
# element follows an element whose last letter coincides with its first letter; the sequence cannot contain duplicates
# The following list contains the name of the chemical elements
c_e_l = ["Actinium", "A... |
88c4348d3afbd1d175f0f40504317470f5df9808 | dillonp23/CSPT19_Sprint_1 | /sprint_challenge.py | 8,423 | 4.40625 | 4 |
"""
Exercise 1
Given a string (the input will be in the form of an array of characters), write a function that returns the reverse of the given string.
* Examples:
csReverseString(["l", "a", "m", "b", "d", "a"]) -> ["a", "d", "b", "m", "a", "l"]
csReverseString(["I", "'", "m", " ", "a", "w", "e", "s", "o", ... |
4f24b7f36fbedb24c3effefdfec084e578ae4513 | Dastan-dev/part2.task7 | /task7.py | 121 | 4.09375 | 4 | number = int(input("vvedite chislo: "))
if number > 0:
print (1)
elif number < 0:
print (-1)
else:
print (0)
|
6ec2bff8324bfd8ee96f0d954229b1b4dc36ce2f | BillGrieser-GW/Final-Project-Group-7 | /code/svhnpickletypes.py | 2,854 | 3.71875 | 4 | """
Classes and command-line operations to convert the SVHN data into pickled
formats for tidier use.
bgrieser
"""
# =============================================================================
# Class definition for what gets pickled
# =============================================================================
cl... |
dc02c4dd55566b1c11e9e1cf50b8677b68af889d | loggar/py | /py-core/List/list.sort.multiple-keys.py | 365 | 3.609375 | 4 | import operator
people = [
{'name': 'John', "age": 64},
{'name': 'Janet', "age": 34},
{'name': 'Ed', "age": 24},
{'name': 'Sara', "age": 64},
{'name': 'John', "age": 32},
{'name': 'Jane', "age": 34},
{'name': 'John', "age": 99},
]
people.sort(key=operator.itemgetter('age'))
people.sort(key... |
b9a7e97826c1f746c7ce528958f7320e671a9ab7 | yooni1903/DDIT | /workspace_python/HELLOPYTHON/day09/mynumpy03.py | 154 | 3.625 | 4 | import numpy as np
a = np.zeros((10, 10), dtype=int) # int형으로 넣어주는 명령어
print(a)
print(a.shape)
b = np.reshape(a,(20,5))
print(b)
|
b67b3c5c9fcf924ae6314681afeb8b05380a0f6d | freebz/Learning-Python | /ch32/spam_class.py | 952 | 3.8125 | 4 | # class Spam:
# numInstances = 0 # 정적 메서드 대신에 클래스 메서드 사용
# def __init__(self):
# Spam.numInstances += 1
# def printNumInstances(cls):
# print("Number of instances: %s" % cls.numInstances)
# printNumInstances = classmethod(printNumInstances)
class Spam:
numInstances = 0 ... |
668b0a0d32f742e53eca223b9ad76c52e6d251f1 | Vsevolod-dev/forTensor | /modules/quadratic_equation_module.py | 772 | 3.671875 | 4 | from math import sqrt
def quadr_equ(disc, a, b):
if disc == 0:
x = -b / (2 * a)
print("Корень уравнения = ", x)
elif disc > 0:
x1 = (-b + pow(disc, 0.5)) / (2*a) #без использования библеотек
x2 = (-b - sqrt(disc)) / (2*a) #с использованием библеотекb math
print(f"""
... |
0184d9c6514e5dfd5efac1d43704a770e6134aa5 | wdempsey96/playground | /bubble_sort.py | 591 | 4.15625 | 4 | """Bubble sort implementation."""
UNSORTED_ARRAY = [5, 2, 4, 3, 1, 8, 10, 103, 69, 420, 17, 6, 88, 16, 191]
print("Unsorted array: ", UNSORTED_ARRAY)
print("Sorting...")
is_sorted = False
swapped = False
while not is_sorted:
i = 0
is_sorted = True
while i < len(UNSORTED_ARRAY) - 1:
if UNSORTED_A... |
1033179fb4d947f5468eb7bfbffe43cdfb5e086c | soowon-kang/tensorflow-practice | /03-Cost/02-gradientDescent.py | 1,071 | 3.703125 | 4 | import tensorflow as tf
# tf Graph input
x_data = [1., 2., 3.]
y_data = [1., 2., 3.]
# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 1 and b 0, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -10.0, 10.0))
X = tf.placeholder(tf.f... |
a22c6b0650cd3272059ef3fcad25c693591508e9 | kevincharp/EjercicioPython-IFTS18 | /Ejercicio_9.py | 403 | 4 | 4 | #Pedir una nota en numero y decir si es Insuficiente, Suficiente, Bien, Muy Bien, Exelente
num = int(input('Ingrese nota del 1 al 10: '))
if num <= 3:
print('NOTA INSUFICIENTE')
if num <= 5:
print('NOTA SUFICIENTE')
if num <= 7:
print('NOTA BIEN')
if num <= 9:
print('NOTA MUY BIEN')
if num == ... |
64a3f1b63d944622abceac3f887ce3a281324211 | xookerchang/age | /age.py | 460 | 3.890625 | 4 | driving = input('請問你有開過車嗎:')
if driving != '有' and driving != '沒有':
print('請輸入有或者沒有')
raise SystemExit
age = input('請輸入你的年齡:')
age = int(age) # casting
if driving == '有':
if age >= 18:
print('You pass the exam')
else:
print("it's werid, how?" )
elif driving == '沒有':
if age >= 18:
print(... |
7fe5c0acb0e85548ac285c8feea7f1942f2a2fb7 | tippenein/NonsenseGenerator | /nonsenseGenerator.py | 1,416 | 3.921875 | 4 | #!/usr/bin/env python
'''
USE THIS TO CREATE YOUR OWN RAMBLING PARANOID NEWS FEED!
'''
import random
def makeNonsense(part1, part2, part3, n=10):
"""return n random sentences"""
#convert to lists
p1 = part1.split('\n')
p2 = part2.split('\n')
p3 = part3.split('\n')
#shuffle the lists
[ rand... |
8b1c92bb18b68596c1379522882291c193025c9f | hatopoppoK3/AtCoder-Practice | /CADDi/A.py | 105 | 3.5 | 4 | N = str(input())
ans = 0
for i in range(0, len(N)):
if N[i] == "2":
ans = ans + 1
print(ans)
|
8c52ee4d1a6dd9efb9dd97fa7f1b0e70eebca689 | Tvisha-D/COGS-18-Final-Project | /my_module/test_functions.py | 5,070 | 3.5625 | 4 | from functions import mood_finder, music_recommender, playlist_interest
##
##
# This tests the callability of the playlist_interest() function, ensures that the paramenter for the function is a list,
# and checks if the number of questions asked is 2. As the aim of the function is to collect user input (using the i... |
85f4d4063b5053c62e14ecfb1c18c53f4230efa8 | Jitender214/Python_basic_examples | /07-Errors and Exception Handling/CustomException.py | 725 | 3.78125 | 4 | class UserdefindExp(Exception):
pass
class NameEception(UserdefindExp):
pass
def testexp():
try:
mystring = 'Jithu'
enterstr = input("enter name ")
if mystring == enterstr:
print('name matches')
else:
raise NameEception
except NameEception:... |
67f22a74eedc6c07c1841e2848930856b3acccfc | jnwki/blackjack | /game.py | 2,246 | 3.6875 | 4 | from deck import Deck
from hand import Hand
def game():
# Instantiate game deck, player and dealer
deck = Deck()
player = Hand()
dealer = Hand()
# Initial Deal
player.hand = [deck.hit() for _ in range(2)]
dealer.hand = [deck.hit() for _ in range(2)]
print("\n\nWelcome to Blackjack.\n... |
62bc09870aef45a2fe74ab91ca15dcd774824c5f | ionutdrg45/BottlesOfBeer | /main.py | 401 | 3.90625 | 4 |
def bottles_of_beer(beer_num):
if beer_num < 1:
print("""No more bottles of beer on the wall. No more bottles of beer.""")
return
tmp = beer_num
beer_num -= 1
print("""{} bottles of beer on the wall. {} bottles of beer. Take one down, pass it
around, {} bottles of beer on the wall"... |
1d9bb9f6b50bc3c5f1d09130276f4000f23f385d | yangyuxiang1996/leetcode | /98.验证二叉搜索树.py | 1,780 | 3.71875 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-06 18:14:40
LastEditors: yangyuxiang
LastEditTime: 2021-05-06 18:49:21
FilePath: /leetcode/98.验证二叉搜索树.py
'''
#
# @lc app=leetcode.cn id=98 lang=python
#
# [98] 验证二叉搜索树
#
# @lc code=start
# Definition for a binary tree node.
# clas... |
5ce1f734f8785fd51730ec0f34e62e59c4a45a2c | shaziya21/PYTHON | /pali.py | 907 | 3.96875 | 4 | def count(lst):
even = 0
odd = 0
for i in lst:
if i%2==0:
even+=1
else:
odd+=1
return even,odd
lst=[20,25,14,19,16,24,28,47,26]
even,odd = count(lst)
print(even)
print(odd)
print(type(even))
######################################
def count(lst):
even =... |
9b1f993d127f6d22c9204327893885ebee304206 | huseyin1701/goruntu_isleme | /1. hafta - python giris/3_degiskenler.py | 231 | 3.65625 | 4 | a=5
b=5.5
c = "metin"
d = True
e = 'e'
print(a)
print(b)
print(c)
print(d)
print(e)
print("a nın değeri :", a)
print("b nın değeri :", b)
print("c nın değeri :", c)
print("d nın değeri :", d)
print("e nın değeri :", e)
|
754e12ed25948cf40c0312647c55647216355c2c | NaychukAnastasiya/goiteens-python3-naychuk | /lesson_5_work/Ex5.py | 285 | 3.859375 | 4 | donuts = ["ягідні","вишневі","шоколадні","карамельні"]
is_present= False
for i in donuts:
if i=="вишневі":
is_present= True
break
if is_present== True:
print("Є")
else:
print("Немає")
|
825d346ce56fdd28914dd483066b24483bd34ed8 | vthakur-1/sub1 | /prob12.py | 299 | 3.5625 | 4 | inpr=input()
liss=inpr.split(",")
num1=int(liss[0])
num2=int(liss[1])
if num1>=1000 and num2<=3000:
for inter in range(num1,num2):
f=0
for inter2 in str(inter):
if int(inter2) % 2 != 0:
f=1
break
if(f==0):
print(inter,end=",")
else:
print("entre number between given range")
|
4901dec5cb8e60c1d380169f4abdcc77da8188f8 | Hallyson34/uPython2 | /dentroparafora.py | 546 | 3.578125 | 4 | def decifrarE(v):
meio = len(v) // 2
j = meio - 1
for i in range(meio // 2):
aux = v[j]
v[j] = v[i]
v[i] = aux
j -= 1
def decifrarD(v):
meio = len(v) // 2
j = len(v) - 1
for i in range(meio, meio + meio // 2):
aux = v[j]
v[j] = v[i]
v[i... |
95088069ad85adc8652025bc006ae3325ebe4548 | leilalu/algorithm | /剑指offer/第一遍/linkedlist/07-2.求链表的中间结点.py | 1,426 | 3.953125 | 4 | """
题目描述
求链表的中间结点。
如果链表中的结点总数为奇数,则返回中间结点;如果结点总数是偶数,则返回中间两个结点的任意一个。
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindMidNode(self, head):
"""
可以使用【两个指针】,两个指针同时出发,第一个一次走两步,第二个一次走一步。当第一个指针走到链表末尾时,第二个指针刚好在链表中间
考虑... |
38a0043338a353e10301d1bd9b26787dc84d1d54 | geometryolife/Python_Learning | /PythonCC/Chapter07/e5_counting.py | 285 | 4.09375 | 4 | print("----------使用while循环----------")
# for循环用于针对集合中的每个元素的一个代码块,而while循环不断地
# 运行,直到指定的条件不满足为止
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
|
8db85b9d702229b511a33f36b8052b4582de3a25 | denizcetiner/rosalindpractice | /HEA.py | 1,173 | 3.84375 | 4 | offset = 1
def parent(pos:int):
if pos == 1 or pos == 2:
return 0
else:
return int((pos - 1) / 2)
def swap(array:[], pos0:int, pos1):
temp = array[pos0]
array[pos0] = array[pos1]
array[pos1] = temp
def max_heapify(max_heap_array:[], check_pos:int):
largest = check_pos
l... |
573b03724fdc1cb3fb2da71fd1047cfd56a601e5 | queensland1990/HuyenNguyen-Fundamental-C4E17 | /SS02/Homeworkss2/turtle2.py | 156 | 3.96875 | 4 | from turtle import*
shape("turtle")
begin_fill()
color("red")
end_fill()
dot_distance=10
width=10
height=10
for i in range(10):
forward(10)
mainloop()
|
b3858dee8cfb7b3b783368ef4cdc7b8d46d05b7c | brunoparodi/IME-USP-Coursera | /Parte02/Exercícios extras/11.6a-matriz-Recebe duas matriz a_mat e b_mat e cria e retorna a matriz produto de a_mat por b_mat.py | 1,013 | 3.578125 | 4 | # A = (aij)m x p e B = (bij)p x n é a matriz C = (cij) m x n
def mat_mul(A,B):
num_linhas_A, num_colunas_A = len(A), len(A[0])
num_linhas_B, num_colunas_B = len(B), len(B[0])
assert num_colunas_A == num_linhas_B
C = []
for linha in range(num_linhas_A):
C.append([]) # Começando uma nova li... |
513f5901b898f4da35aa87a31a7896c6339ab999 | Pravin2796/python-practice- | /chapter 3/2.slicing.py | 106 | 3.625 | 4 | #greeting = "good morning,"
name = "pravin"
#c= greeting + name #concatinating two strngs
print(name[:-1]) |
e06ddc4767c5e66476d280e20173cfded49b9a6b | tafiela/Learn_Python_the_hardway | /lambda_fun.py | 413 | 4.21875 | 4 | #lambda is a way of writting functions in one line
#its the quick and dirty way of doing functions
#This is one way for writting a function
def square(x):
return x*x
print square(99)
#This is another way for writting a function
def square(x): return x*x
print square(10)
#Here is the lambda way
square = lambda x: x*... |
c020fb004676b8365fc4a56a49420819f70ee40f | xu-robert/Leetcode | /Diagonal Traverse.py | 3,447 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 21:14:12 2020
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal
order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Since the picture does ... |
7e3b376ead8d26563d80f2c754d94137db7e714c | Taoge123/OptimizedLeetcode | /LeetcodeNew/python/LC_140.py | 3,344 | 3.9375 | 4 | """
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume ... |
2e43d4911bbeb9f1629d6d50dbf4e2f83a5db327 | michaelcyng/python_tutorial | /tutorial5/boolean_examples/boolean.py | 270 | 4.125 | 4 | # Two possible values of boolean variables
a = True
b = False
print("a = {0}".format(a))
print("b = {0}".format(b))
# Examples of boolean examples
c = (10 > 9)
d = (10 == 9)
e = (10 < 9)
print("c = {0}".format(c))
print("d = {0}".format(d))
print("e = {0}".format(e))
|
c35ddfdb76ab90a772c5738cb4bfdb137081f72e | GuillaumeFavelier/persistence-atlas | /ttk/core/base/spectralEmbedding/spectralEmbedding.py | 20,284 | 3.609375 | 4 | def _graph_connected_component(graph, node_id):
"""Find the largest graph connected components that contains one
given node
Parameters
----------
graph : array-like, shape: (n_samples, n_samples)
adjacency matrix of the graph, non-zero weight means an edge
between the nodes
node_... |
da0df8008b8f89f6aee683f204faefe8957e13ea | DaphneKeys/Python-Projects- | /amazon.py | 678 | 3.609375 | 4 | #This program retrieve the price of a product from amazon
import bs4
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
}
def getAmazonPrice(productUrl):
res = requests.get(productUrl)
res.raise_for_st... |
1352d9da2da74363a4bf2613fbbd4a7be5a45018 | Vadum-cmd/lab4_345 | /point.py | 435 | 4.1875 | 4 | class Point:
"""
Makes class to work with coordinates of the point.
"""
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to_origin(self):
"""
Gives us the distance from origin to point.
"""
return (self.x ** 2 + self.y ** 2) ... |
f4505262682fe32839e00c9f44d26974970ca7b2 | swetabhmukherjee/moneytor-assessment | /answer-2.py | 605 | 4.0625 | 4 | # Python code to remove duplicate elements
def duplicate_removal(arr):
if((len(arr)>=1) and (len(arr)<=1000000)):
final_list = []
for num in arr:
if num not in final_list:
final_list.append(num)
return final_list
else:
return "out of bounds"
# Dr... |
43ff4526380d96a3ff0ee2b68ace13fce8664cac | gracexin2003/ssp19 | /Coding/Python HW 1/GhostGame.py | 2,039 | 4.125 | 4 | # Purpose: Write a word game
# Project: Ghost Game
# Due: 6/21/19
# Name: Grace Xin
def ghost():
player = 1 # starting player is player 1, will switch in between turns
# read words.txt into a list of valid words
valid_words = []
for line in open("words.txt", "r"):
valid_words.append... |
ad9a85141199235b64b78eda73095a35c3ed4089 | doubledherin/Markov-Chains | /markov_variable_prefix_length.py | 2,700 | 3.828125 | 4 | #!/usr/bin/env python
from sys import argv
import random, string
def make_chains(corpus, num):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
new_corpus = ""
for char in corpus:
# leave out certain kinds of punctuation
if char in "_[]*": # NOT ... |
f3f282b2dfffe2205ae0ba484860e7fa8c524d25 | marciojmo/ai-examples | /linear-regression/linear_regression.py | 4,797 | 4.28125 | 4 | #!/usr/bin/env python
"""
A multi variate linear regression model.
"""
import numpy as np
from matplotlib import pyplot as plt
def normal_equation(x, y):
"""
Computes the closed-form solution to linear regression
:param X: The input values
:param y: The output values
:return: theta params found b... |
7d549abcfbaea95a1b63fbd443b3574a27c5fa1f | vabramson/CS115 | /lab4.py | 773 | 3.75 | 4 | """
I pledge my honor that I have abided by the Stevens Honor System
By Tim Zheng
29 Sep 2017
"""
from cs115 import filter
def knapsack(capacity, itemList):
"""which returns both the maximum value and the list of items (itemList) that make this value, without exceeding the capacity of your knapsack"""
if... |
6d463667d3385ad9a72f46c849b8465e79ab73df | uxrishu/python-codes | /stack.py | 583 | 3.796875 | 4 | class Stack:
def __init__(self):
self.values = list()
def push(self,element):
self.values.append(element)
def isEmpty(self):
return len(self.values) == 0
def pop(self):
if not(self.isEmpty()):
return self.values.pop()
else:
print('Stack Underflow')
return None
def top(self):
if not(self.isEmpt... |
e171706b710f600ffc05c255b7db0099ee483f39 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2219/60767/237566.py | 346 | 3.75 | 4 | import math
def isAddition(num):
n = int(math.sqrt(num))
left = 1
right = n
while(left<=right):
val = left*left+right*right
if(val == num):
return True
elif(val<num):
left = left+1
else:
right = right-1
return False
num = int(input(... |
e945111e311e5503f97f46caebb2b4bbc645d104 | janos01/esti2020Python | /Format/iteracio.py | 206 | 3.65625 | 4 |
# Számok bekérése 0 végjelig
# Adja össze a bekért számokat
osszeg = 0
szam = -1
while szam != 0 :
szam = int(input('Szám: '))
osszeg = osszeg + szam
print('Összeg: {}'.format(osszeg))
|
d3ebc479ca67b66359afdb83f4035fe281c04d1d | javacode123/oj | /test/huawei/3.py | 1,206 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019-08-24 15:41
# @Author : Zhangjialuo
# @mail : zhang_jia_luo@foxmail.com
# @File : __init__.py.py
# @Software: PyCharm
import sys
class Solution:
def find_num(self, a, b):
length = len(a)
count = [0]*length
for m in range(length):
... |
57be43bee40cf47a621e798bc08dd823a71a2319 | KarenYesenia/PythonCourse-Lists | /exercises/Dicts_exercise_1.py | 506 | 4.34375 | 4 | # We need to receive the basic info of user
#(first_name,last_name,age,email)
# and save them as keys into a dict call user.
#After recive the data, shw the info in the console
user = {}
user["first_name"] = input("hey bro, cual es tu nombre?:")
user["last_name"] = input("como dices que se apellidan tus gfes?: ")
user... |
7a9210e5dde71427c639b4e1b6eb28c38ad2977d | Ravinder-agg/python_gui | /1_digi.py | 760 | 3.625 | 4 | import tkinter as tk
from tkinter import font
from tkinter import ttk
import datetime
import time
def quit(*args):
root.destroy()
def clock_time():
time = datetime.datetime.now()
time = (time.strftime("%d-%b-%y \n%I:%M:%S %p"))
txt.set(time)
root.after(1000,clock_time)
root = tk.Tk()
root.geome... |
b2cb8b71f1d64d685110d7151c9c950859275367 | bekkam/code-challenges-python-easy | /dec2bin.py | 2,632 | 4.375 | 4 | """Convert a decimal number to binary representation.
For example::
>>> dec2bin_backwards(0)
'0'
>>> dec2bin_backwards(1)
'1'
>>> dec2bin_backwards(2)
'10'
>>> dec2bin_backwards(4)
'100'
>>> dec2bin_backwards(15)
'1111'
For example, using our alternate solution::
>>> ... |
0be6f317bd9daab3ac4f570deaaa211b9689661f | edwardmasih/Python-School-Level | /Class 11/11-Programs/Projectile motion.py | 586 | 4 | 4 | import math
u=int(input("Enter The Initial Velocity of The Object to be Projected (in m/s)==> "))
a=int(input("Enter The Angle of Projection (in degrees)==> "))
g=9.8
sin = (math.sin(math.radians(a)))
cos = (math.cos(math.radians(a)))
T =(2*u*sin)/g
H =(u**2)*((sin)**2)/(2*g)
R =(2*(u**2)*(sin)*(cos))/g
... |
9c037f794aa0ea5b8c876c6f23f3f70ab4dbdf6a | Pranav-21/psm | /Employee contact management.py | 15,684 | 3.59375 | 4 |
from tkinter import *
import sqlite3
import tkinter.ttk as ttk
import tkinter.messagebox as tkMessageBox
root = Tk()
root.title("Employee Contact List")
width = 1200
height = 600
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (scre... |
d51109538231a86744851112ae160615c077b8eb | cs-learning-2019/python2sat | /Lessons/Week21/Python_Classes_1/Python_Classes_1.pyde | 5,115 | 4.625 | 5 | # Focus Learning: Python Level 2
# Python Classes
# Kavan Lam
# Feb 19, 2021
"""
We already learned about the different data types in Python. For example, str, float, bool, int and list.
Now we will go through how to create our own data types
In Python there are already pre-made data type such as list, dicti... |
76191734f9f965d49a7bba942185199ef7e64970 | drcpcg/codebase | /Array/equilibrium-index-of-an-array.py | 1,537 | 4.09375 | 4 | # https://www.geeksforgeeks.org/equilibrium-index-of-an-array/
"""
refer to cpp version
Input: A[] = {-7, 1, 5, 2, -4, 3, 0}
Output: 3
3 is an equilibrium index, because:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
"""
# Python program to find the equilibrium
# index of an array
# function to find the equilibrium in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.