blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
64db6bc4f55091426605b6cb05edf8ea3c92a917 | keumdohoon/STUDY | /keras/keras79_diabetes_dnn.py | 3,845 | 3.5 | 4 | from sklearn.datasets import load_diabetes
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# import some data
dataset = load_diabetes()
print(data... |
cb974ea332ca6f35e7bdd4667d2d84e0f3cbe623 | dhruvbaldawa/project_euler | /0022-name-scores.py | 1,208 | 4.125 | 4 | """
Problem 22
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
... |
de4edcd922cce339fb8fb90694c6b3585dafeba6 | ismk/Python-Examples | /trip.py | 835 | 3.90625 | 4 | def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if(city == "Charlotte"):
return 183
elif(city == "Tampa"):
return 220
elif(city == "Pittsburgh"):
return 222
elif(city == "Los Angeles"):
return 475
def renta... |
31221785ba5391d1ecedbe7b3c096c8ba80d77a9 | viviayi/LeetCode | /toLowerCase.py | 426 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 12 17:16:24 2019
@author: 11104510
实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。
"""
class Solution:
def toLowerCase(self, str: str) -> str:
return str.lower()
if __name__ == '__main__':
sl = Solution()
print(sl.toLowerCase('Hel... |
64b1a6b5847bb39822445f8e1a597fa44c10104b | Edwar2-2/TestingSistemas | /ene-jun-2020/JOSE EDUARDO ONOFRE SUAREZ/Practica5/Contenedor.py | 798 | 3.703125 | 4 |
class contenedor:
def volumencontenedor(lista1,lista2):
listaC = []
suma = 0
for i in range(0,len(lista1)):
listaC.append(lista1[i]*lista2[i])
for i in range(0,len(listaC)):
suma+= listaC[i]
return suma
if __name__ == "__main__":
n = ... |
9eb3a80f93ad8f4ba48d0acba4da9ff9e30194d1 | ssawo/python-365-days | /python-fundamentals/day-1/assignment-operators.py | 868 | 4.53125 | 5 | # This lab explores basic Python assignment operators with examples
"""
Examples include:
+= | Equivalent to x = x+5
-= | Equivalent to
*= | Equivalent to
/= | Equivalent to
Others
%= | Equivalent to
//= | Equivalent to
**= | Equivalent to
"""
# This example if short-hand for... |
b26804f399438e0a6d5f63a5487c95619507a56e | phalt/hash_things | /hash_things/hash_dict.py | 700 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""Hash Dictionaries."""
from typing import Dict
def hash_dict(data: Dict) -> int:
"""
Hashes a Dictionary recursively.
List values are converted to Tuples.
WARNING: Hashing nested dictionaries is expensive.
"""
cleaned_dict: Dict = {}
def _clean_dict(data: Dict)... |
00e1705f1e407a7ca369b52bdac70a90865142ff | inudevs/ithaca-prob-type-model | /deprecated /generator.py | 544 | 3.5 | 4 | from converter import convert_file
from parser import parse_page
names = []
for year in range(2008, 2020):
for month in [3, 6, 9, 11]:
for grade in [1, 2, 3]:
for subject in [1]: # math only
names.append(
'{}-{:02d}-{}-{}'.format(year, month, grade, subject)... |
a73191314940f1775a22c0e81c4afc663b3b897b | Phillip-Kemper/image-sentiment-analysis-ml | /machine-learning/model/trainModel.py | 2,343 | 3.53125 | 4 | import numpy as np
import pandas as pd
from scipy.io import loadmat
import matplotlib.pyplot as plt
import scipy.optimize as opt
import dataRetrieval.dataRetrieval as getData
import model.neuralNetworkBackpropagation as ml
import sys
CSV_FILE = "../dataRetrieval/sources/fer2013.csv"
trainingData, evalData = getData.... |
95c10215f48a4cf84af09be568de522f0ada3eb4 | Sktank/wordSuggestions | /parse.py | 1,051 | 3.640625 | 4 | __author__ = 'spencertank'
from errors import raiseError
import verify
frequenciesFileNotFoundError = "The word frequencies file could not be found!"
misspelledFileNotFoundError = "The misspelled words file could not be found!"
def getWordFrequencies(frequenciesFilename):
try:
f = open(frequenciesFilenam... |
7c312b310cc4291da0e1f167a4fafbc54127e26b | HannibalCJH/Leetcode-Practice | /231. Power of Two/Python: Solution.py | 213 | 3.6875 | 4 | class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
power = 1
while power < n:
power *= 2
return power == n
|
e464ad15cde0de22563734bf064990566b8ef66d | msaitejareddy/Python-programs | /sep 17/readfile.py | 428 | 3.515625 | 4 | #how to read wickets data without loop from wickets.txt file
#infile=open('wickets.txt','r')
#wickets=infile.readline()
#print(wickets)
#wickets=infile.readline()
#print(wickets)
#wickets=infile.readline()
#print(wickets)
#how to read no of wickets taken by each bowler using while loop from wickets.txt file
infile=ope... |
a52631de3758aa260fa4c09782379078dc7fd432 | mmmarchetti/cev_python | /exercises/exe112/moeda.py | 981 | 3.609375 | 4 | class Calculo:
def __init__(self, num, aum=0, dim=0, cond=True):
self.num = num
self.aum = aum
self.dim = dim
self.cond = cond
def conta(self):
result_metade = (self.num / 2)
if self.cond:
result_metade = f'R${result_metade:0.2f}'
result_dob... |
d58d22b6b461d9de33aaa7204dcaec5ddf60717a | tongpf/ichw | /pyassign1/planets.py | 1,296 | 4 | 4 | import turtle
import math
def firststep(p,a,b):
a = a*5.0
b = b*5.0
c = a - math.sqrt(a**2-b**2)
p.shape("circle")
p.pensize(3)
p.penup()
p.forward(c)
p.left(90)
p.pendown()
def drawcircle(p,sz):
sz = sz * 5.0
d = 2 * math.pi * sz
p.forward((d/360)*(400... |
84078a344ca008afff0b64a150f38d13f3360f9e | weiguxp/pythoncode | /ProblemSets/ParseFile.py | 344 | 3.546875 | 4 | def ParseF(n):
''' opens file n and returns a list of words
n = name of file
'''
fin = open(n)
myList = []
for line in fin:
word = line.strip()
myList.append(word)
return myList
def ParsePartF(n, l):
''' Opens a file and parses the first l words
n = file name
l = desired length of list'''
myList = Pars... |
1264def3c3a4199f548a6f9dea1d9824aa5b97b1 | JVvix/tkToDo | /dictionary.py | 370 | 3.8125 | 4 | # stacgkoverflow.com/questions/2397754/how-can-i-create-an-array-list-of-dictionaries-in-python
#dictlistGOOD = list( {} for i in xrange(listsize) )
#dictlistGOOD[0]["key"] = "value"
dictlistGOOD = list( {} for i in range(listsize) )
dictlistGOOD[0]["key1"] = "value0"
dictlistGOOD[1]["key1"] = "value1"
for i i... |
2f62f182de4abf7b2db6eb93924624f7f1e3cc7f | ziGFriedman/My_programs | /Character_table_output.py | 874 | 3.921875 | 4 | '''Вывод таблицы символов'''
# Первые 128 символов по таблице Unicode такие же как и в таблице символов ASCII.
# Выведем их, начиная с пробела, кодовый номер которого 32.
# Чтобы привести вывод к табличной форме будем переходить на новую строку после
# каждого десятого выведенного на экран символа. Для этого в коде ниж... |
cb1e2664537744c9171c1bdf7e7fc324daaf009c | SADDLOVE/HomeWork | /nodmod.py | 652 | 3.5625 | 4 | #Задание выданное на лекции от 18.10.2021
#Напишите программу, которая получает на вход два натуральных числа и определяет их НОД с помощью модифицированного алгоритма Евклида
a = [64168, 358853, 6365133, 17905514, 549868978]
b = [82678, 691042, 11494962, 23108855, 298294835]
vivod = []
print(a)
print(b)
for i in r... |
3c5960fd3f39f4c5ba6b26135a6a09dbeb1cf165 | pradeepraja2097/Python | /python basic programs/array.py | 161 | 3.78125 | 4 | def sum(arr):
sum=0
for i in arr:
sum+=i
print(sum)
return(sum)
arr=[]
arr=[1,3,2]
answer=sum(arr)
print("answer is" + str(answer)) |
de668dfdb154730c611ddfd0e70dcbbf185c2870 | kushrami/Python-Crash-Course-book-Exercise | /Exercise_11_2_test.py | 473 | 3.640625 | 4 | import unittest
import Exercise_11_2 as module
class CityCountry(unittest.TestCase):
def test_city_country(self):
formatted_name = module.CityCountryFunc('santiago','chille')
self.assertEqual(formatted_name, 'santiago, chille')
def test_city_country_population(self):
formatted_name... |
c5e4f0f618350f718171e0089942065dfab73d26 | bbster/PythonBigdata | /workspace/11-method/practice2.py | 549 | 3.96875 | 4 | def grade(avg):
if avg >= 90 and avg <= 100:
return 'A'
elif avg >= 80 and avg <=89:
return 'B'
elif avg >= 70 and avg <=79:
return 'C'
elif avg >= 60 and avg <=69:
return 'D'
else :
return 'F'
def calc(x,y):
total = x + y
avg = total / 2
return... |
89710983d91b130a8b63f6b15bdb393df2b164c8 | tejachil/ECE2524-Chiluvuri | /HW3/mult2.py | 1,990 | 3.9375 | 4 | #!/usr/bin/env python2
# ECE 2524 Homework 3 Problem 1 (Nayana Teja Chiluvuri)
import sys
import argparse
import fileinput
# argument parser
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('files', nargs='*', type=str, default=sys.stdin)
parser.add_argument('--ignore-blank'... |
ce51fbe0fc2c85ad5dd93e9060d2f9c3216ed983 | LanonD/PythonBasics | /variables.py | 823 | 4.15625 | 4 | # -*- coding: utf-8 -*-
#
#Esto es un comentario
"""
esto es un heredoc (comentario)
"""
mensaje = """
esto es un mensaje, neta xd
"""
nombre = "Luis"
apellido = 'Vázquez' #Esta es la preferida
nombre_completo = nombre + ' ' +apellido
print(nombre_completo)
print(len(nombre.upper()))
print(nombre.lower())
prin... |
81b5abb30f2d1d493d05992076633b1af56b7186 | econpy/yav1 | /parse_log.py | 1,363 | 3.59375 | 4 | from pandas import read_csv
import os
import sys
from libv1.logparser import CleanLogData
"""
ABOUT:
This script parses a single YaV1 log located in the `rawlogs` folder. Just
pass the date of the log file you want to clean and it will output a new
CSV file in the `cleanlogs` folder.
USE:
python pars... |
69eb0c3d99d59be7c9e014ede201d46a37694ce1 | zhengqiangzheng/PythonCode | /basicpy/itertolls.py | 447 | 3.765625 | 4 | from itertools import combinations, groupby, permutations, combinations_with_replacement
a = [1, 2, 3, 4, ]
b = [4, 5, 6]
# print(list(permutations(a, 3))) # len(a)!
print(list(combinations(a, 3)))
print(list(combinations_with_replacement(a, 3)))
def small_than3(x):
return x < 3
groupby_obj = groupby(a, key... |
fd8fc61c99158c7fc25b757fe894fcb0b982cf64 | dahyunhong/CCSF_Classes | /CS110A/exercise1.6.py | 1,151 | 4.375 | 4 | rad = float(input("Enter the radius:"))
Area=3.14*rad*rad
Circumference=2*3.14*rad
print("The area is {}".format(Area))
print("The circumference is {}".format(Circumference))
# 2. Write a program to take the input of two numbers and then swap their values. Your code should display the original and the modified v... |
f71095b64b8ab9df1cb036aa3a18ad1cc10ec4b9 | vaishali-khilari/COMPETITIVE-PROGRAMMING | /leetcode/Sorted matrix .py | 1,139 | 4.4375 | 4 | Given an NxN matrix Mat. Sort all elements of the matrix.
Example 1:
Input:
N=4
Mat=[[10,20,30,40],
[15,25,35,45]
[27,29,37,48]
[32,33,39,50]]
Output:
10 15 20 25
27 29 30 32
33 35 37 39
40 45 48 50
Explanation:
Sorting the matrix gives this result.
Example 2:
Input:
N=3
Mat=[[1,5,3],[2,8,7],[4,6,9]]
Output:
1 2 ... |
5de0150031379492688c3044673c9bb2f3b4b2a5 | xodhks0626/pythonStudy | /practice/recursiveFunction.py | 560 | 3.765625 | 4 | # Recursive Function (재귀 함수) : 자기 자신을 다시 호출하는 함수
def recursive_function():
print("재귀함수")
recursive_function()
# recursive_function()
# 마지막에 나타나는 오류 메시지는 재귀의 최대 깊이를 초과했다는 내용이다. => 무한대로 재귀 호출을 할 수 없다.
def re_function(i):
if i == 100:
return
print(i, '번째 재귀 함수에서', i+1, '번째 재귀 함수를 호출.')
re_... |
8b04f8bd99a5c011091f1f589a44187ecf715c51 | JCYTop/ML | /100-Days-Of-ML-Code/Day 2/Day 2 Simple Linear Regression.py | 1,123 | 3.984375 | 4 | # step 1: Preprocess The Data *********
# 处理数据
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv("stduentscores.csv")
X = dataset.iloc[:, :1].values
Y = dataset.iloc[:, 1].values
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_... |
6df5140aebb1674b6efe8797a8353da3c6990b03 | akesiraju/raspberrypi | /sensors/samples/keytest.py | 171 | 3.609375 | 4 | import keyboard
print('hello')
while True:
if keyboard.is_pressed('up'):
print('up')
if keyboard.is_pressed('down'):
print('down')
break
|
f442b53c0433300429f49731389790ac08de324e | Rajadeivani/deivani5756 | /num_div_less_N.py | 114 | 3.546875 | 4 | N=int(input())
count=0
for i in range(2,N):
if(N%i==0):
count=count+1
if(count>0):
print("yes")
|
7cd58df5896359649fcdc77ad8e68ea1f10891b4 | anishsundaram/atbs-solutions | /Test Program.py | 242 | 4.15625 | 4 |
print("enter a number")
number = int(input())
def collatz(number):
if(number % 2 ==0):
print(str(number // 2))
return number // 2
else:
print(str(3*number+1))
collatz(number)
|
53bb6403b34dd5260bb20066d2387ad25dd60221 | tuanbieber/code-tour | /10-remove-duplicates-from-sorted-array.py | 636 | 3.53125 | 4 | class Solution:
def __init__(self):
pass
def function1(self, nums):
if len(nums) == 0:
return 0
if len(nums) == 1:
return 1
i = 0
for j in range(1, len(nums)):
if nums[i] != nums[j]:
i += 1
nums[i] = n... |
3e8b40c9cc79176053b6fbd41b8faf19aa3f81c9 | BenSandeen/autonomous_vehicle_flocking | /traffic_light.py | 6,451 | 3.859375 | 4 | import enum
import random
from copy import deepcopy
import math
from constants import *
class LightColor(enum.Enum):
green = 'green'
yellow = 'yellow'
red = 'red'
class TrafficLight:
def __init__(self, position):
"""These directions represent the color for a car travelling... |
a274da569cbbc4cd0432dce71234fbe6ab0b0915 | frclasso/CodeGurus_Python_mod1-turma1_2019 | /Cap03/script6.py | 477 | 4.125 | 4 | # strings
# -*-coding:utf-8-*-
frase1 ="Eu adoro maças"
frase2 = "Bem vindos ao curso de Python da Code Cla"
# concatenacao +
#print(frase1 + frase2)
# repetição *
#print(frase1 * 100)
# indices em Python iniciam por zero (0) dentro de colchetes
print(frase1[0]) # primeiro indice 'E'
print(frase1[-1]) # ultimo i... |
1ee086daf263bdc9dd81a5691a90912ce5a76ff3 | Jyllove/Python | /DataStructures&Algorithms/Sort/mergesort.py | 475 | 4.09375 | 4 | def MergeSort(lists):
if len(lists) <= 1:
return lists
num = len(lists)//2
left = MergeSort(lists[:num])
right = MergeSort(lists[num:])
return Merge(left,right)
def Merge(left,right):
l, r = 0, 0
result = []
while l<len(left) and r<len(right):
if left[l] <=right[r]:
result.append(left[l])
l += 1
e... |
8876ede3a3cf5135e86e17291bfceafdde5f1767 | PJH6029/Lecture | /oop1_fraction/main.py | 2,474 | 4.21875 | 4 | from fraction import Fraction
from fraction_handler import FractionCalculator
# main.py는 건드리지 않아도 되지만, 읽어볼만 한 내용
def take_fraction_input(n):
# 유효한 두 정수를 받는 함수
while True:
tmp = input(f'{n}: Enter the numerator and denominator of the fraction(both are integers): ').split()
if len(tmp) != 2:
... |
15a5618a8d2009bb95fbab107440abac21af18a7 | Arjitg450/Python-Programs | /char_count.py | 582 | 3.890625 | 4 | def char_count(text,char):
count=0
for c in text:
if c==char:
count+=1
return count
while True:
inp=input("enter the file name\n")
inp1=input("enter the char whose rep value you want to know\n")
inp2=str(inp1)
with open(inp+".txt") as f:
text=f.read(... |
c06cecc0ffa14d816cee6a12e35e1c01ef406a35 | wangning11/first | /31_冒泡排序.py | 243 | 3.53125 | 4 | arr = [4,9,2,7,1,0,3]
def buddle_sort(arr):
n = len(arr)
for j in range(0,n-1):
for i in range(0,n-1-j):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] =arr[i + 1], arr[i]
buddle_sort(arr)
print(arr)
|
de8784741867166cb2393e248ac996b12eeec8b7 | sangeetjena/datascience-python | /Dtastructure&Algo/sort/merge_sort.py | 809 | 4.125 | 4 | #logic behind is that it will keep deviding all the elements and up to reach the single elements
# the n keep forming sorted arrays and merge two to create one sorted array and that again
#sorted with others left.
def merge_sort(value):
if len(value)>1:
mid= len(value)//2
left=value[:mid]
r... |
542c4ddf4653c08c766b94cee73e40f4a57c23b3 | Crisescode/leetcode | /Python/Sort/1235. maximum_profit_in_job_scheduling.py | 2,470 | 3.796875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# https://leetcode-cn.com/problems/maximum-profit-in-job-scheduling/
# We have n jobs, where every job is scheduled to be done from startTime[i]
# to endTime[i], obtaining a profit of profit[i].
#
# You're given the startTime , endTime and profit arrays, you need to outpu... |
29da0e7ab10f8c1dc2ca19f7430a276d0cf0d067 | pskugit/organic-fractal-trees | /python/fractal_trees.py | 2,535 | 4.25 | 4 | from tkinter import *
import random
import math
#Initialization parameters
MIN_LEN = 5
STEM_SIZE = 100
WIN_WIDTH = 900
WIN_HEIGHT = 600
def branch(len, level, x, y, angle):
'''
Generates and draws a new branch to the current tree.
Is calles recursively to build the full tree.
:param len: int
... |
0c0d3ecd29026fe4facfbb0dbb8542d07e197bd9 | oliviaclyde/hello-world | /practice-python/String_Lists.py | 768 | 4.46875 | 4 | # # Ask the user for a string and print out whether this string is a palindrome or not.
# # (A palindrome is a string that reads the same forwards and backwards.)
#1st way: convert to string and reverse order
a = "qwertytrewq"
b = str(a)[::-1]
def isPalindrome():
if a == b:
print("Your string is a palin... |
89edad569fe88f2f87e0d888be8a3a90e89c722e | JHolderguru/Eng-57-Python-basics | /LIST_BASICS.py | 1,525 | 4.6875 | 5 | #Lists
#lists are exactly what you expect. they are lists
#they are organized with index. This means starts at 0
# list can hold any data type
#example
#syntax
#[] this bracket makes a list.
my_stingy_landlords = ["Alfredo", "Betty", "Joanna", "Mr .Sumersbee", 123, True]
# index [ 0 1 ... |
61ef893a88ea867280875ceff87a3fd416fda387 | movermeyer/django-laconicurls | /laconicurls/obfuscation.py | 1,206 | 3.84375 | 4 | #The base27 idea comes from this guy who was using base31 to cut out vowels.
#I've also removed the 4 numbers that look like vowels to prevent any unintentional calculator gags
#http://jeffreypratt.net/safely-base-36-encoding-integers.html
BASE27_ALPHABET = '256789BCDFGHJKLMNPQRSTVWXYZ'
def base27_encode(n):
"""En... |
84174ba5f3f4395db99c4f48a6da2a9e016b487e | chusehwan/python | /Part1/test_cities.py | 434 | 3.546875 | 4 | import unittest
from chapter_11_2 import city_functions
class test_city_country(unittest.TestCase):
def test_full_loc_name(self):
message = city_functions('santiago', 'chile',123000)
self.assertEqual(message, 'santiago chile - 123000')
def test_full_loc_pop_name(self):
message = city_f... |
8c91c5ea7456e46d50569472af4ebb05c72b7427 | andrew-yt-wong/ITP115 | /ITP 115 .py/Labs/ITP115_L5_1_Wong_Andrew.py | 3,760 | 3.828125 | 4 | # Andrew Wong, awong827@usc.edu
# ITP 115, Spring 2020
# Lab 5-1
import random
def main():
quitProgram = False
articles = ['a', 'the']
nouns = ['person', 'place', 'thing']
verbs = ['danced', 'ate', 'frolicked']
while not quitProgram:
print("\tWelcome to the Sentence Generator\n\tMenu")
... |
e1a590b11e1d580695f648e3e1afa89c4477b966 | shhuan/algorithms | /py/topcoder/TCCC 2003 Semifinals 2/TelephoneGame.py | 4,432 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import math,string,itertools,fractions,heapq,collections,re,array,bisect
class TelephoneGame:
def howMany(self, connect1, connect2, numPeople):
"""
分成两组,使得相交的区间最少
:param connect1:
:param connect2:
:param numPeople:
:return:
"""
... |
eb19b715a50c6241f907c6075dfb445c7d0701ae | mnipshagen/monty | /2018/10/Solution/final_countdown.py | 1,629 | 4.0625 | 4 | """
This module starts a countdown with a really dramatic ending. Viewer discretion
is advised
Uses the time and webbrowser modules.
"""
import time
import webbrowser
class NegativeError(Exception):
""" Just some error to avoid counting down from negative numbers. """
pass
def countdown(seconds):
"""
... |
3b6ec3fc0a486dc5227ad77a210150ad0e96e31d | selutin99/econometrica | /core/base_functions.py | 2,434 | 3.640625 | 4 | import core.checker as ch
def range(data):
"""
Find range of data list
:param data: list of int or float values
:return: max value of list minus min value of list
"""
if ch.check_list(data):
return max(data) - min(data)
def capacity(data):
"""
Find length of list
:param d... |
79f30ebe02801e5a6e8a98b08aeaa53dde72a1a9 | balaramhub1/Python_Test | /String Formatting/strtest_01.py | 245 | 3.84375 | 4 | '''
Created on Apr 28, 2014
@author: ROCKSTAR
'''
from datetime import datetime
fname="balaram"
sname="behera"
print(fname,"is my name",sname,"is my surname")
print("hello {}, your age is {}".format(fname,sname))
print(datetime.now()) |
59b5cbd3981729c24fb9aa2f3f32174d78e5b843 | TrickFF/helloworld | /type_str.py | 2,502 | 4.21875 | 4 | friend = 'Максим Макс'
print(friend)
print(type(friend))
say = 'Всем "двинутым" привет!'
print(say)
# Из строки можно получить символ по индексу = [переменная][индекс]. Индекс начинается с 0
first_letter = friend[0]
print('Первая буква имени друга - ', first_letter)
# индекс [-1] - адрес последней буквы строки
last... |
b59c11ab8b66839c2010bf88a1b7130da307405f | CircleZ3791117/CodingPractice | /source_code/627_SwapSalary.py | 1,810 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'circlezhou'
'''
Description:
Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.
For example:
| i... |
789f820b0a17736c93207d544bd42139b61fb246 | mkiterian/word_count | /counting.py | 195 | 3.96875 | 4 | def words(string):
the_words = string.split()
the_words = [int(word) if word.isdecimal() else word for word in the_words]
return {word: the_words.count(word) for word in the_words}
|
30b7a4d0425a26e0b471c7df17545830e84b6dd1 | yeboahd24/python202 | /Design Pattern/document.py | 720 | 3.953125 | 4 | #!usr/bin/env/python3
class Document:
def __init__(self):
self.characters = []
self.cursor = 0
self.filename = ''
def insert(self, character):
self.characters.insert(self.cursor, character)
self.cursor += 1
def delete(self):
del self.characters[self.cursor]
def save(self):
with o... |
c165c320edd793b406d12a6aef953c827a311557 | andrealmar/learn-python-the-hard-way | /ex3/ex3.py | 1,014 | 4.4375 | 4 | # just print the phrase between parenthesis
print "I will not count my chickens"
# print Hens and do a little math of 25 + (30 / 6) = 30
print "Hens", 25.0 + 30.0 / 6.0
# print Roosters and the math: 100 - ()(25 * 3) % 4)
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
# print the statement below
print "Now I will count t... |
ae7827b4b2ac0d954ff0072728456d4ee53a5c88 | Ing-Josef-Klotzner/python | /2017/hackerrank/compare_the_triplets.py | 2,105 | 3.875 | 4 | #!/usr/bin/python3
import os
import sys
#
# Complete the solve function below.
#
def solve(a0, a1, a2, b0, b1, b2):
al = 0
bob = 0
if a0 > b0: al += 1
if a1 > b1: al += 1
if a2 > b2: al += 1
if a0 < b0: bob += 1
if a1 < b1: bob += 1
if a2 < b2: bob += 1
return str(al) + " " + str(b... |
7268c213ec43f96e7bf661529ca632f39adec473 | memsql/memsql-loader | /memsql_loader/util/attr_dict.py | 817 | 3.53125 | 4 | class AttrDict(dict):
def __getattr__(self, key):
try:
return self.__getitem__(key)
except KeyError:
# This lets you use dict-type attributes that aren't keys
return getattr(super(AttrDict, self), key)
def __setattr__(self, key, value):
return self.__... |
b1ed530bc19418c2c73b66820b86cb3ea5a200a8 | Ubastic/coding-challenges | /leetcode/solutions/easy/hamming-distance/solution.py | 241 | 3.6875 | 4 | class Solution:
def hammingDistance(self, x: int, y: int) -> int:
diff = 0
while x or y:
x, f = divmod(x, 2)
y, s = divmod(y, 2)
diff += f != s
return diff
|
1bcbcadd32851565b62afd40201969cbde88ffa1 | k-schmidt/Coding_Problems | /code_rust/binary_search.py | 883 | 4.03125 | 4 | """
Binary Search
"""
def binary_search_recur(array, key, low, high):
if low > high:
return -1
mid = low + ((high - low) // 2)
if array[mid] == key:
return mid
elif key < array[mid]:
return binary_search_recur(array, key, low, mid - 1)
else:
return binary_search_re... |
44cd53b72e5c8e2e3c50385c439689a3b52989a5 | ivan-yosifov88/python_basics | /Nested Loops - Lab/05. Travelling.py | 281 | 3.96875 | 4 | command = input()
while command != "End":
budget = float(input())
total_save_money = 0
while total_save_money < budget:
save_money = float(input())
total_save_money += save_money
else:
print(f"Going to {command}!")
command = input()
|
230fe2159e5862b0d6fafac53f5684886d3fe3e3 | HaymanLiron/46_python_exercises | /q18.py | 432 | 4.125 | 4 | def is_pangram(string):
# checks if string contains all letters of alphabet at least once
# capitalization is not important
string = string.lower()
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w','x', 'y', 'z']
... |
776fcc6cab9bb156cb266eb43e8d00113bb39075 | elsandkls/SNHU_IT140_itty_bitties | /banking_transactions.py | 7,149 | 3.515625 | 4 | # Get the filepath from the command line
import sys
import re
#import variables
F1= sys.argv[1]
F2= sys.argv[2]
#print(F1,"\n",F2)
#Read Files in.
#___________ functions _____________
#open files
def openMyFiles(FileName):
myFile = open(FileName, 'r')
FileContent = myFile.read()
myFile.close()
return(FileC... |
4cc2d8833ddfbdd5b9924b7a4350cc1576ac12fa | connormclaud/euler | /python/Problem 024/solution.py | 1,144 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distribut... |
72b205cff44cd1ad0ba0eda13807aac97e581add | metheoryt/itstep-python | /1_intro/c_logical_ops.py | 1,339 | 4.09375 | 4 | """
Логические операции
Операции, возвращащие в качестве результата булево значение - True/False
"""
# Приведение к bool
assert bool(0) is False
assert bool('') is False
assert bool([]) is False
assert bool(None) is False
assert bool(-1) is True
assert bool('a') is True
assert bool([1]) is True
# Сравнение
assert ... |
e139015faf7aa0cb28b05d618e6e945d7dd544d0 | rk385/tathastu_week_of_code | /Day1/program4.py | 152 | 3.765625 | 4 | CP=int(input("enter the cost price:"))
SP=int(input("enter the selling price"))
Profit=SP-CP
print("profit is:",Profit)
SP=CP+(Profit*(1.05))
print(SP)
|
bec7379c510dfef2aba44341f8862ba03b4cf34d | JackNoordhuis/SDD | /Prelim/Tasks/Week #4/Sausages in a Can.py | 217 | 3.953125 | 4 | #####################
# Sausages in a Can #
#####################
rows = eval(input("Rows: "))
loops = 0
while loops < rows:
loops += 1
print("Row " + str(loops) + ": " + str((3 * loops * (loops - 1) + 1)))
|
a8b20c6e001500fc4a83223e089a9e5773ac2d02 | TrisAXJ/py-study | /demo2/demo2.py | 5,023 | 4.03125 | 4 | # -*- codeing = utf-8 -*-
# @Author:TRISA QQ:1628791325 trisanima.cn
# @Time : 1/12/2021 5:38 PM
# @File : demo2.py
# @Software: PyCharm
# namelist = ["小张", "小王", "小李"]
'''
#namelist = [] #定义一个空的列表
namelist = ["小张", "小王", "小李"]
testlist = [1, "测试"] # 列表中可以存储混合类型
print(type(testlist[0]))
print(type(tes... |
553186729974dfaff8398beaca45f2845bf8da60 | SejalChourasia/python-assignment | /python assignment11/Module4/Question-06/flatter_list.py | 265 | 3.671875 | 4 | l=[[int(i) for i in range(10)]for j in range(10)]
print('Unflattened list',l)
flatten=[i for sublist in l for i in sublist if i<5]
'''
for sublist in l:
for i in sublist:
flatten.append(i)
'''
print('flattened list with less than 5 ',flatten)
|
d4c067a8e6a72107f7668d2686188e516433a409 | shivapk/Programming-Leetcode | /Python/Misc/topological.py | 881 | 3.796875 | 4 | from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list)
self.v = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def dfs(self):
visited=[False]*(self.v)
sorted=[]
for s in range(self.v):
... |
72d52d2f755abbb7bcdd69bb91a17d48c7d736ec | chng3/Python_work | /第十章练习题/learning_C.py | 149 | 3.640625 | 4 | # 10-2 C语言学习笔记
filename = 'learning_python.txt'
with open(filename) as f:
contents = f.read().replace('Python', 'C')
print(contents)
|
4fd851c1de50c0cd836c3331f18bbcaec065146a | ChristinaROK/TIC | /20210506.py | 865 | 3.90625 | 4 | # Programmers 오픈채팅방 level-2
def solution(record):
id2name = {}
res = []
for history in record:
h_list = history.split()
if h_list[0] in ["Enter","Change"]:
id2name[h_list[1]]=h_list[-1]
if h_list[0] == "Enter":
res.append(f"{h_list[1]},님이 들어왔습니다.")
... |
377c7554b950594435546456d978f2b999cfd882 | afcarl/word_sampling | /main.py | 2,149 | 3.75 | 4 | #! /usr/bin/env python
# Main file to be executed from the command line
import sys
import re
from alias_method import AliasMethod
def initialize_sampler(file_path):
"""
Load the corpus in the given file_path, count al the words,
and create a sampler to sample the words from the distribution of
word ... |
86c028eabe0f0999b9ea2a61d680e501abed7a06 | dhd12391/LearnPyData | /my-code/suitcase_task1.py | 1,201 | 3.984375 | 4 | """
Coding Challenge: The Traveling Suitcase
Scenario:
Travis traveled to Chicago and took
the Clark Street #22 bus up to
Dave's office.
He left his briefcase on the bus!
Try to get it back!
Task 1:
Travis doesn't know the number of the bus he
was riding. Find likely candidates by parsing
the data just downloaded a... |
c984ed15c578160106cddc6510e2ba4ea763f978 | ZeroTwoooo/pp | /pp1/thing.py | 235 | 3.546875 | 4 | from getpass import getpass
username = raw_input("What is your username ")
passw = getpass("Set your password ")
if passw == "dev123":
print("Login Succsess! \n Welcome, "+ username +"!")
else:
print("Incorrect password") |
1065bb2a8f51b68dc127fa2ca145690dbc70df3b | u8913557/codeTraining | /Hackerrank/30 Days of Code/Day25_Running_Time_and_Complexity.py | 430 | 3.9375 | 4 |
import math
number = input()
for i in range(int(number)):
str_num = input()
int_num = int(str_num)
if(int_num==1):
print("Not prime")
else:
k = 2
for j in range(2, int(math.sqrt(int_num))+1):
if(int_num%k==0):
break
k = k + 1
... |
e83f16d9f57269ca7d2a408cd7c5fadda6eb690c | NamanRai11t/bad_loan_classifier | /helpers.py | 4,476 | 3.71875 | 4 | import csv
import numpy as np
import matplotlib.pyplot as plt
#Load data from csv file, and break it into an data list of lists (feature set) and a y list.
def load_data(filename, split=0.8, features=[], blacklist=[], shuffle=True):
''' load_data(filename, split=0.8, features=[], blacklist=[], shuffle=True) -> X_tra... |
e682ca43a6fda34f222d60a7bdff78e366fdea2c | VAIBHAV-2303/Super_ASCII_Brothers | /src/mario.py | 2,408 | 3.5 | 4 | '''
[MM]
][
This file contains the Mario class
which generates mario itself and its
movement function '''
from person import Person
class Mario(Person):
'''Mario class'''
def __init__(self):
'''Initialization'''
Person.__init__(self)
self.lives = 3
self.posx = 20
s... |
60e1baaa09c99bf19d130c042efd854451a5bf2f | cesar-rayo/robot_fw_example | /libraries/ReadData.py | 420 | 3.65625 | 4 | import csv
import json
def read_csv_file(filename):
data = []
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
data.append(row)
return data
def read_json_file(filename):
data = {}
try:
with open(filename, 'r') as json_file:
... |
3b88407101133fa7f84f16100a6c9d8755e3ff01 | sudo-hemant/test | /geeksForGeeks/backtracking/combinations-sum.py | 1,634 | 3.6875 | 4 |
def combinationalSum(arr, x):
def find_sum(curr_pos, curr_arr, arr, length, find):
# index out of range or greater than required value
if curr_pos == length or find < 0:
return
# sum = required value
if find == 0:
result.append(curr_arr[:])
... |
8f47e5bd0face86b3b978442e7d71eb04bf6458e | XiaoTaoWang/JustForFun | /Project-Euler/Problem-4.py | 858 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 02 19:12:44 2016
@author: wxt
"""
"""
Problem 4:
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def bru... |
2c54e834ce30d9a3092d3be3508194d3bc58af9c | AILearnerNTHU/PySnake | /PySnake-term/PySnakeGame/Map.py | 614 | 3.609375 | 4 |
from enum import Enum
class MapEnum(Enum):
Wall = 'w'
Ground = 'g'
Fruit = 'f'
Snake = 's'
class MapObject(object):
def __init__(self):
self._filetype = MapEnum.Ground
@property
def FileType(self):
return self._filetype
@FileType.setter
def FileType(self,... |
e6bafc3229ba3788892985ea2a18fe51c665fc10 | jiabraham/Card-Games | /black_jack/game_scalable.py | 8,723 | 3.8125 | 4 | #!/usr/bin/python3
import actions
import cards
import copy
import math
import player
import random
#Global variables, deck and cards_dealt vectors simulate a standard card deck
deck = cards.setDeck()
cards_dealt = cards.setCardsDealt()
#Welcome messages
def main():
print("\n \n \n \n \n \n \n \n\n \n \n \n \n \n... |
3c7ae17e73043aaf986d163372a113d5ed633eb8 | Srini-py/Python | /Daily_Coding_Problem/486_find_celebrity.py | 949 | 4.0625 | 4 | '''
At a party, there is a single person who everyone knows,
but who does not know anyone in return (the "celebrity").
To help figure out who this is, you have access to an O(1) method called knows(a, b),
which returns True if person a knows person b, else False.
Given a list of N people and the above operati... |
a849b4f5a1834eb0245c933a5a55c17130548df8 | BiancaPal/PYTHON | /INTRODUCTION TO PYTHON/greet_users.py | 827 | 4.53125 | 5 | # You'll often find it useful to pass a list to a function, whether it's a list of names,
# numbers, or more complex objects, such as dictionaries. When you pass a list to a function
# the function gets direct access to the contents of the list. Let's use functions to make
# working with lists more efficient.
# Say y... |
366e230cedf648b32b7653cf9e695eb06d581ba6 | PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch | /52. Mutable vs immutable objects/mutablevsimmutableobjects.py | 865 | 3.8125 | 4 | """
object is a variable with MORE features than just showing value
You can invoke a function ON object
object can have many different values
immutable - unchangable (after sending as argument)
mutable - changable
immutable object: bool, int, float, tuple, str
= - means CHANGIN... |
1ed286de1e684cdec4e125b981680c59e7605cf5 | soniacamacho/Fall-19 | /CS 511/jawalkad_classroom_test.py | 1,335 | 3.59375 | 4 | from jawalkad_classroom import Student, Assignment
def main():
allen = Student(123, "Allen", "Anderson")
becky = Student(456, "Becky", "Beckyson")
print(allen.get_full_name()+',', "id:", allen.get_id())
print(becky.get_full_name()+',', "id:", becky.get_id())
a11 = Assignment("Assignment 1", 100)
... |
0f8896f62136e12de13521109e89f8daaebb2032 | antohneo/pythonProgramming3rdEdition | /PPCh7PE11.py | 446 | 4.03125 | 4 | # aaa
# python3
# Python Programming: An Introduction to Computer Science
# Chapter 7
# Programming Excercise 11
def main():
year = int(input("Enter a year: "))
century = year // 100
if year % 4 == 0:
if century % 4 == 0:
print("{0} is a leap year.".format(year))
else:
... |
4f79bf248975dd11aa9578ecc87cb56a287c7a99 | ArneRobben/DesertIslandDiscs | /code/Scraping.py | 6,730 | 3.625 | 4 | """ import libraries """
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml
import requests
import re
import pandas as pd
import time
"""initialise a session"""
# load the landing page
landing_page = "https://www.bbc.co.uk/programmes/b006qnmr/episodes/player?page={}"
html = requests.get(lan... |
e44db7e58454d9de0a9cbf27fec6e11f5c56afbe | dphillips97/pract | /general_py_pract_ex/menu.py | 3,037 | 4.625 | 5 |
#https://www.reddit.com/r/beginnerprojects/comments/1bytu5/projectmenu_calculator/
'''GOAL
Imagine you have started up a small restaurant and are trying to make it easier to take and calculate orders. Since your restaurant only sells 9 different items, you assign each one to a number, as shown below.
Chicken Strips... |
ced74babd22c59ea6dd25c94c4457cfcce8dde03 | trustmub/OBS | /src/controller/customer.py | 1,893 | 3.5625 | 4 | """
controller.customer
---------------
A customer controller that provide functionality for the customer creation and
amendment my a back office personnel.
this controller interacts with the user views.customer module
"""
import datetime
from src import db
# from src.models import session
from s... |
91a36da69f6961d31de01501f52e518159a75c1b | siddhantprateek/Python-in-Practice | /Primitive Types/typecoversion.py | 220 | 4.125 | 4 | x = input("x: ")
print(type(x))
# y = x + 1 THE PROBLEM IN THIS CODE WAS 'X' WAS A STRING, SO WE CANNOT ADD STRING TO A NUMBER,SO
# WE HAVE TO CONVERT X TO AN INTEGER
y = int(x) + 1
print(f"x: {x} , y: {y} ")
|
cec8f60f7c429e9dca44f8e055f137194c9fcbfe | akimi-yano/algorithm-practice | /lc/1687.DeliveringBoxesFromStorageTo.py | 4,880 | 3.9375 | 4 | # 1687. Delivering Boxes from Storage to Ports
# Hard
# 46
# 4
# Add to List
# Share
# You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.
# You are given an array boxes, where boxe... |
f371461105b0b1bb38f9756589d175e56cbd7f96 | StephenRyall/pythonalgorithms | /extraLondFactorials.py | 164 | 3.609375 | 4 | def extraLongFactorials(n):
fac = 1
if (int(n) >= 1):
for i in range(1, int(n)+1):
fac = fac * i
print(fac)
extraLongFactorials(25) |
277c551aca4ee2d3ee0fc6256623f15e522a7286 | jiinmoon/Algorithms_Review | /Archives/Leet_Code/Old-Attempts/0148_Sort_List.py | 1,341 | 3.8125 | 4 | """ 148. Sort List
Question:
Sort a linked list in O(n lg n) using constant space complexity.
+++
Solution:
We can achieve this sorting in-place via MergeSort algorithm. This is done
by first find the mid point to split the linked list into two halves. Then,
we recursively sort the list of two halv... |
77311300092f52bde9efe133f3a8c2379c6c4c3c | kishen19/HSS-Course-Allotment | /code/course.py | 1,394 | 3.65625 | 4 | ''''
Course Object
'''
class Course:
def __init__(self,code: str, name: str, cap: int, lecture_slots: list, tutorial_slots: list):
self.code = code
# Course code, ex: HS 151, dtype: (string)
self.name = name if name else ''
# Name of the course, ex: World Civilization, dtype: (strin... |
dd2d9528b3c67f17db915283f036abfb52f8839a | mavrovski/PythonPrograming | /Programming Basics - Python/06Drawing Figures with Loops/10Diamond.py | 800 | 3.953125 | 4 | n = int(input())
leftRightDashes = int((n-1)/2)
if n == 1:
print("*")
else:
# upside
for row in range(0,int((n-1)/2)):
print("-"*leftRightDashes,end='')
print("*",end='')
middle = int(n - 2 * leftRightDashes - 2)
if middle >= 0:
print("-" * middle, end='')
... |
cdd569e2928c4abb7177bca72878eb8daea269e8 | goku1011/66DaysOfData | /dsDay3/intermediateML_categorical_variables.py | 3,354 | 3.59375 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
X = pd.read_csv('home-data-for-ml-course/train.csv')
X_test = pd.read_csv('home-data-for-ml-course/test.csv')
# Remove rows with missing target, separate target from predictors
X.dropna(axis=0, subset=['SalePrice'], inplace=True)
y = X.SalePrice... |
4c7fc60bd109522a5949d13c688db5776514a3ac | ozkknnt/ML_preprocessing_study | /データクレンジング/defaultdict.py | 573 | 3.65625 | 4 | from collections import defaultdict
# 文字列 description
description = \
"Artificial intelligence (AI, also machine intelligence, MI) is " + \
"intelligence exhibited by machines, rather than " + \
"humans or other animals (natural intelligence, NI)."
# defaultdict を定義して下さい
char_freq = defaultdict(int)
# 文字の出現回数を記録して下さ... |
c958bd658c835edadd29244507f58ee520effec6 | alba054/CSUnhas_DataStructure | /HashTable/hashtable.py | 1,482 | 3.578125 | 4 |
class HashTable:
def __init__(self):
self.table = [None] * 10
# put key := string, value := any
def put(self, key, value):
hash_index = self.hash_func(key) # hash a string
if self.table[hash_index] is None:
self.table[hash_index] = []
self.table[hash_index]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.