blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8a1a67998fff7179711b94c7334b7378fe723c4a | jaymaity/BusinessCanada | /Lib/Stringer.py | 497 | 3.640625 | 4 | """Modifies string functions"""
def is_number(s):
"""
Check if a string is a number or not
:return:
"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueE... |
69d605345e2b88851c85f217c548612befaeae1b | daniel-reich/ubiquitous-fiesta | /ZDDyfBFBWMotQSYin_13.py | 137 | 3.578125 | 4 |
def is_harshad(num):
sum_of_digits = sum(int(x) for x in str(num))
return num%sum_of_digits == 0 if sum_of_digits > 0 else False
|
229c613e05a1853e5673dea7b0c6bfc9a091b433 | mwolffe/my-isc-work | /advanced_python/arrays_numpy.py | 383 | 3.625 | 4 | import numpy as np
x = list(range(1,11))
a = np.zeros((3,2), dtype=np.float64) #creates a 64 bit 3x2 array of zeros
a1 = np.array(x, dtype=np.int32) #converts a list to an array of integers
a2 = np.array(x, dtype=np.float64)#converts a list to an array of floats
#print(x.dtype) - doesn't work as this is a list not... |
f9805ce26c751ec79b5932b2dbaf6176653f3803 | samr87/AI-Homework-2 | /hw2.py | 1,648 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 17:08:36 2020
@author: computer realm
"""
class Agent:
def __init__(self,n,x,y):
# this defines the class as self.
self.name = n
self.xPos = x
self.yPos = y
... |
b9cf55700b1458e947d3073d93134ba109a51d25 | ManikSharma001/SimpleCalculator | /calculator.py | 912 | 4.1875 | 4 | #Simple Calculator with Python
def addition(numOne, numTwo):
return (numOne + numTwo)
def subtraction(numOne, numTwo):
return(numOne - numTwo)
def multiplication(numOne, numTwo):
return(numOne * numTwo)
def division(numOne, numTwo):
return(numOne / numTwo)
response = ""
while response ... |
985d229e98a391bd5f1c9ac05017989f1bf2c601 | wingedrasengan927/Python-tutorials | /Pythontut2 - looping.py | 1,723 | 4.15625 | 4 |
# printing odd numbers using for loop
for i in range(20):
if i % 2 != 0:
print(i)
# rounding off float type
your_float = input('Enter a floating point ')
your_float = float(your_float)
print("the value rounded off to two decimals is {:.2f}".format(your_float))
# Problem : Have user input their invest ... |
4972037b410edc63adce205ca2514ae228fd1f9f | weady/python | /thread/python.multi.process.thread.py | 7,559 | 3.515625 | 4 | #/usr/bin/python
#coding=utf8
#
# 进程通信
import os,random,time
from multiprocessing import Pool, Queue, Process
import multiprocessing
import threading
‘’‘
Queue的功能是将每个核或线程的运算结果放在队里中,等到每个线程或核运行完毕后再从队列中取出结果
继续加载运算。原因很简单,多线程调用的函数不能有返回值,所以使用Queue存储多个线程运算的结果
pool = mp.Pool()
有了池子之后,就可以让池子对应某一个函数,我们向池子里丢数据,池... |
949fa53ec88029692060d644a2ce0725e5a7f2ac | LFBianchi/pythonWs | /Learning Python/function_study.py | 558 | 3.5625 | 4 | def min1(*args):
res = args[0]
for arg in args[1:]:
if arg < res:
res = arg
return res
def min2(first, *rest):
for arg in rest:
if arg < first:
first = arg
return first
def min3(*args):
tmp = list(args)
tmp.sort()
return tmp[0]
def max1(*args):
res = args[0]
fo... |
6e3fcb48692673093bbf85a6ce29ce198e30c63a | larry-dario-liu/Learn-python-the-hard-way | /ex11.py | 262 | 3.71875 | 4 | print "how old are you?",
age = raw_input("age your")
print "how tall are you?",
height = int(raw_input("your height"))
print "how much do you weigh?",
weight = raw_input("your weight")
print "So,you're %r old,%r tall and %r heavy."%(
age,height,weight) |
1e6e9d9d885d9d09050945de0c1360f33abda407 | kayliedehart/Evolution2 | /8/dealer/species.py | 3,113 | 3.9375 | 4 | import constants
from traitCard import *
class Species:
food = 0
body = 0
population = 1
traits = []
fatFood = 0
"""
creates a Species
food: how much food this species has eaten this turn
body: body size
population: population size
traits: Traits (String) on this species board (up to 3)
fatFood: h... |
b1ccef858b533ef1376a282ebaf6352cd2bda612 | KevinKnott/Coding-Review | /Month 03/Week 03/Day 04/b.py | 1,828 | 4.09375 | 4 | # Binary Tree Zigzag Level Order Traversal: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
from collections... |
b20880e1e0bfd211cdaa6c06f34b85020d75018d | San1357/Leetcode-August-2021 | /sqrt(x).py | 379 | 3.8125 | 4 | '''Problem: sqrt(x) '''
#code:
class Solution:
def mySqrt(self, x: int) -> int:
left = 1
right = 0
mid = 0
while(left<mid):
mid = left + math.floor((right-left)/2)
if (mid**2 > x):
right = mid
elif (mid**2) ==x:
return mid
else:
... |
7e5061ae04daa7d7a2f5a3e49238f753c67fe7a6 | karan-modh/logic | /helper/formulaToTree.py | 1,541 | 3.53125 | 4 | from globalvars import OPERATORS
class BinaryTreeNode:
def __init__(self, c):
self.data = c
self.isOperator = True if c in OPERATORS else False
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
pass
def make_tree(self, formula):
x =... |
8ca7cfb49cb03a4904b541931b1c8e22c5c9d6a8 | jesgogu27/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 159 | 3.59375 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
nl = []
for i in list(matrix):
nl.append(list(map(lambda i: i ** 2, i)))
return nl
|
58b4fa3419fa6ce4c8395b6865d9aa77525fca79 | GayatriMhetre21/python10aug21 | /14Aug21list.py | 1,186 | 4.21875 | 4 | #list
x=[2,3,4,5,6,7,8,9,1,0]#declare list type which carry 10 element
#extract all list
print("list x=",x[0:1])
print("list x=",x[0:5])
print("list x=",x)
print("list x=",x[7])
print("list x=",x[0:9])
print("list x=",x[1:9])
print("list x=",x[0:10])
print("list x=",x[10:0])
#extract index number 2 to 5
... |
9c3f96a6497484abe3aef1c18771fa53df70322d | tinnan/python_challenge | /07_collections/062_piling_up.py | 1,376 | 4.09375 | 4 | """
There is a horizontal row of n cubes. The length of each cube is given.
You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube(i) is
on top of cube(j) then sideLength(j) >= sideLength(i).
When stacking the cubes, you can only pick up either the leftmost or the rightmo... |
6e36b4d7ff8c39b68224909ccaed81729dfdc589 | jpragasa/Learn_Python | /Basics/7_Program_Flow.py | 805 | 4.0625 | 4 | # name = input("Please Enter your name\n")
# age = int(input("How old are you {0}\n".format(name)))
# print(age)
#
# if age >= 18:
# print("You are old enough to vote")
# elif age <= 18:
# print("You are not old enough to vote. Please come back in {0} years...".format(18 - age))
# else:
# print("In... |
a089264c84268ecb06bc85f361c84cb7304c88db | mathfinder/python-script | /util/log.py | 1,430 | 3.5 | 4 | import logging
class Logger:
def __init__(self, log_file='log/log.txt', formatter='%(asctime)s\t%(message)s', user='rgh'):
self.user = user
self.log_file = log_file
self.formatter = formatter
self.logger = self.init_logger()
def init_logger(self):
# create logger with... |
71a85beece563565130098534efd2999726d8682 | muhammedimad/Project_Rails | /Assignments/1st Assignment/Assignment1/venv/ex6.py | 278 | 4.0625 | 4 | num=input("Please enter a five digit number\n")
if(len(num)>5):
print("error")
else:
print("you entered the number "+ num)
digits=[int(n) for n in num]
print("the digits of the number are:\n",digits)
ans=sum(digits)
print("the sum of the digits is:",ans) |
189ca03dde80cf88cc2c3ec87ce2e47208ec3c3f | hyuji946/project_euler | /01 解答例/p027.py | 1,399 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Project Euler Problem 27
オイラーは以下の二次式を考案している:
n**2 + n + 41.
この式は, n を0から39までの連続する整数としたときに40個の素数を生成する.
しかし, n = 40 のとき 40**2 + 40 + 41 = 40(40 + 1) + 41
となり41で割り切れる. また, n = 41 のときは 41**2 + 41 + 41
であり明らかに41で割り切れる.
計算機を用いて, 二次式 n**2 - 79n + 1601 という式が発見できた.
これは n = 0 から 79 の連続する整数で80個... |
931c58b889992a80c9978f5585d616554598998b | cchudant/42ai_python_bootcamp | /day00/ex03/count.py | 904 | 4.3125 | 4 | import sys
def text_analyzer(text=None):
"""This function prints the number of upper characters, lower characters,
punctuation and spaces in a given text.
Input is taken from stdin when no argument is passed.
"""
if text is None:
print('What is the text to analyze?')
text = input... |
26b8c68e772b388eb81e1a4e35c1c3b1c74aac53 | jshk1205/pythonPractice | /11365.py | 177 | 3.875 | 4 | while True:
text = str(input())
if text == 'END':
break
text = list(text)
for i in range(len(text)-1, -1, -1):
print(text[i], end='')
print() |
c5dd1297b245da4176429a0a9b62ee5a8934ad49 | KFranciszek/Python | /ZADANKA/2/2.py | 720 | 3.6875 | 4 | from HTMLParser import HTMLParser
# create a subclass and override the handler methods
#class object(object):
#"Pierwsza klasa"
class object1:
def __init__(self,x,y):
self.a = x
self.b = y
print("Stworzenie klasy Object!! :)")
class HtmlObject(object1):
def __init__(self, x, y):
self.a = x
self.b = y
p... |
60aedb6ae5864eab3e69cf83e5d6c2304bca74ca | kingsreturn/Datenvisualisierung | /Python_Datavorbereitung/main.py | 1,849 | 3.515625 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import get_pdf
import extract_data
import generate_path
import os
import urllib.request
def get_pdf_by_url(folder_path... |
f890f92d450a22285b1405391f4727c38ceef762 | oneNutW0nder/csec380-hmwk | /hmwk_3/act1/step1/act1step1.py | 3,211 | 3.578125 | 4 | #!/usr/bin/env python
#
# Name: Simon Buchheit
# Date: October 6, 2019
#
# CSEC-380 : hmwk3 : Act1 Part 1
#
# Purpose: This script scrapes the site:
# https://www.rit.edu/study/computing-security-bs
#
# and collects the course number and corresponding course name.
# If there is no nam... |
db6cb4edcd45eb96f9960c6b00de6f98f825e42f | ankit12192/Email_encryptor | /decrypter.py | 378 | 3.5 | 4 | # -*- coding: utf-8 -*-
def Dec(key):
key = key % 26
file = open("decrypter.txt","w").close()
with open("encrypted_file.txt") as fileObj:
for line in fileObj:
for ch in line:
m=ord(ch)
S = (m - key)
k = unichr(S)
file = open... |
4c38a4173476e7520cbafdf7e664f1f54928ae51 | matheussl12/Python | /Sistema de notas.py | 604 | 4 | 4 |
print('***SISTEMA DE NOTAS ***\n')
np1 = float(input('Digite o valor de sua nota da NP1: \n'))
np2 = float(input('Digite o valor de sua nota da NP2: \n'))
media = (np1 + np2) / 2
if media < 7:
print("Você esta de exame!")
nexame = float(input('Digite a nota do exame: \n'))
nexame = (np1 + n... |
fe5d16f872f9cf871d6fab855060c268ae2760fb | shreyagg2202/Python | /Learning Python/inheritence.py | 365 | 3.75 | 4 | class Animal:
def Dog(self):
print("Dog is barking")
class AnimalChild(Animal):
def DogChild(self):
print("Dog's child is eating")
class Cal(AnimalChild):
def Add(self):
n1=2
n2=3
print(n1+n2)
obj = Cal() #Always create object of ch... |
3b2307ae7cbb19bd5ce14e0a2b65e3286f75a839 | ChaosNyaruko/leetcode_cn | /234.回文链表.py | 1,132 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=234 lang=python3
#
# [234] 回文链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head:
retur... |
2b93e891e1876ec1c01c86648f14d52673e1a06f | shanmukhanand/machine-learning-exp | /supervised-learning/tens/regression/firts.py | 780 | 3.796875 | 4 | import tensorflow as tf
import matplotlib.pyplot as plt
X = [1,2,3]
Y = [1,2,3]
W = tf.placeholder(tf.float32)
# Our hypothesis for linear model
hypothesis = X * W
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Launch the graph in a session.
sess = tf.Session()
# Initializes global varia... |
4349ec3ae67d73d5fd3bf22a1e8476780df76efa | AkshayGulhane46/hackerRank | /06_Loops.py | 119 | 3.546875 | 4 | if __name__ == '__main__':
n = int(input())
for ele in range(n):
square=ele*ele
print(square)
|
9e1c746c3a68c54efb9d0d653643249618a2f248 | ircubic/Master-Thesis | /src/testbed/simulation/chars.py | 3,674 | 3.6875 | 4 | class Shape(object):
def __init__(self, position):
self._position = list(position)
def move(self, direction, speed):
if direction == 'left':
self._position[0] -= speed
elif direction == 'right':
self._position[0] += speed
elif direction == 'up':
... |
44159023b941fe26953bf626e8ba6b60dbadf822 | Scarecrow1024/Python-Old | /threading_simple.py | 487 | 3.53125 | 4 | import threading
import time
num = 0
def run2():
lock.acquire()
global num
num += 1
lock.release()
lock = threading.Lock()
for i in range(100):
tt = threading.Thread(target=run2)
tt.start()
print("num:", num)
def run(n):
print(n)
time.sleep(2)
start_time = time.time()
ts = []
for i i... |
5e6c30faf3fdc48bb763fa0d604fffea8d33dc6e | Axioma42/Data_Analytics_Boot_Camp | /Week 3 - Python/Activities/3/Activities/08-Par_WrestlingWithFunctions/Solved/wrestling_functions.py | 2,135 | 4.09375 | 4 | import os
import csv
# Path to collect data from the Resources folder
wrestling_csv = os.path.join('..', 'Resources', 'WWE-Data-2016.csv')
# Define the function and have it accept the 'wrestler_data' as its sole parameter
def print_percentages(wrestler_data):
# For readability, it can help to assign your values ... |
2ef4f2c7bc1d6bb92fd546693d39c2e7c5c57896 | jardelhokage/python | /python/reviProva/Python-master/31_NúmeroPrimo.py | 288 | 3.734375 | 4 | primos = []
num = int(input('Qual numero testar? '))
for n in range(1, num+1):
if num % n == 0:
primos.append(n)
if len(primos) > 2:
print('O número {} NÃO é Primo!'.format(num))
break
if len(primos) == 2:
print('O número {} é PRIMO.'.format(num)) |
5b7d47affb56a1395c19c051ac165b8824db8fd2 | ljwhite/python | /basics/tuples.py | 363 | 4.15625 | 4 | my_tuple = (1,2,3,5,8)
print("1st value :",my_tuple[0])
print("1st 3 values :",my_tuple[0:3])
print("Length :", len(my_tuple))
more_fibs = my_tuple + (13,21,34)
print("34 in tuple? :", 34 in more_fibs)
for i in more_fibs:
print(i)
a_list = [55,89,144]
a_tuple = tuple(a_list)
b_list = list(a_tuple)
print("Max :", ... |
dd5ec0417b9e2441befec6f52b1a5156150edf00 | iampkuhz/OnlineJudge_cpp | /leetcode/python/passedProblems/128-longest-consecutive-sequence.py | 1,908 | 3.9375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"... |
bf421c2d34027e1724faafcc4663eb1ffc69e96d | choco9966/Algorithm-Master | /programmers/코딩테스트 대비반/1주차/올바른괄호.py | 394 | 3.515625 | 4 | def solution(s):
# [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
# print('Hello Python')
myStack = []
for i in s:
if i == "(":
myStack.append(i)
else:
try:
myStack.pop()
except:
return False
if len(myStack) == 0:
retur... |
7eae67863dfadfdf966e6e32c38fc9a006dacc5f | CommanderKV/SchoolChatApp | /Server/chatAppServerGUI.py | 14,569 | 3.59375 | 4 | import pygame
class Button():
def __init__(self, color, x, y, width, height, text='', function=None, args=None):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.function = function
self.args = arg... |
fc3cd9074d165d2555e7ddb656a9962e56154852 | liuhu0514/py1901_0114WORK | /days0214/封装练习/封装简单练习.py | 628 | 4.03125 | 4 | """
面向对象封装练习
"""
class Person:
"""人的类型"""
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self, ag... |
ce6f6a81a226c04221274afd77b9dc6c51eac8a1 | anitakamboj1997/task2 | /test.py | 6,213 | 4.34375 | 4 |
import sys
from enum import Enum
# Python3 implementation to build a
# graph using Dictonaries
from collections import defaultdict
# Function to build the graph
def build_graph():
edges = [
["A", "B",5], ["A", "E"],
["A", "C"], ["B", "D"],
["B", "E"], ["C", "F"],
["C", "G"], ["D", "E"]
]
graph = defaultd... |
8786c3c55d882471d9b64669b514b09e68bcbaf3 | SteenJennings/Neural-Net-Options | /Kevin/Archive/nn_code_midpoint.py | 1,810 | 3.890625 | 4 | #predict
from numpy import loadtxt
#import keras functionality for sequential architecture
#Keras is a free open source Python library for developing and evaluating deep learning models
from keras.models import Sequential
from keras.layers import Dense
#load and format dataset
dataset = loadtxt('/content/AMD_without... |
f9d955fef713f8fa07c7e77b1c3110f19a089348 | uch1/CS-2-Tweet-Generator | /coursework/classwork/whatever.py | 3,899 | 4.28125 | 4 | # Defines a "repeat" function that takes 2 arguments
def repeat(s, exclaim):
'''
Returns the string 's' repeated 3 times.
If exclaim is true, add exclamation marks.
'''
result = s * 3
if exclaim:
result = result + '!!!'
return result
# String literals
s = 'hi'
print s[1] ## i
print ... |
b8d83b1fe2ead806b7ce3ba4ba4456d3e8184bdb | GrubbClub/CoderBytes | /check_nums.py | 243 | 4.09375 | 4 | def check_nums(num1, num2): #if 1 is < 2 its true, 1 > 2 false, if same return -1
if num1 == num2:
return (-1)
elif num1 < num2:
return True
else:
return False
print check_nums(3,122)
print check_nums(122, 3)
print check_nums(32, 32) |
c885239cc1a78c056c384b2e73c55d39d591d965 | leoCardosoDev/Python | /1-Curso-em-Video/00-desafios-python/desafio007.py | 191 | 3.921875 | 4 | nota1 = float(input('Primeira nota: '))
nota2 = float(input('Segunda nota: '))
media = (nota1 + nota2) / 2
print('A nota {} e a nota {} tem a média de {:.1f} '.format(nota1, nota2, media))
|
ff0d53d00df17aa857d1c2deae593363aa44fbfa | Inverseit/fifteen-puzzle | /timer.Py | 1,286 | 3.578125 | 4 | # provides timer for the application
import time
class Timer(object):
def __init__(self, master, canvas):
self.master = master
self.canvas = canvas
self.total = 0 # total passed since start
self.passed = 0 # passed after past resume or start
self.tag = ""
self.... |
870e71a08d66afde1c8e1aa400bdfe034eabf996 | tmorgan181/Space_Blocks | /game_over.py | 4,037 | 4.03125 | 4 | # CS 3100 Team 8
# Spring 2021
#
# This file contains the functions needed to display the game over screen after a
# session is completed. If the final score of the game is a new high score, it
# will prompt the user to enter their name and add the score to the database.
import pygame as pg
import sys
from button impo... |
8bfb06030a9b39f695ee038379f5ef6829e13bec | Bittu0184/PlacementPortal | /logindatab.py | 517 | 3.546875 | 4 | import sqlite3;
conn = sqlite3.connect('login.db');
conn.execute("create table logintab1 (username char(20) primary key NOT NULL,pass char(20) NOT NULL);")
conn.execute("insert into logintab1(username,pass) values('aditya','ag16')")
conn.execute("insert into logintab1(username,pass) values('aditya1','ag16')")
conn.exec... |
29477558fd988a9d33466596cd9c20cce6e6a9a4 | hschilling/OpenMDAO-Framework | /openmdao.units/openmdao/units/units.py | 26,215 | 3.90625 | 4 | """This module provides a data type that represents a physical
quantity together with its unit. It is possible to add and
subtract these quantities if the units are compatible and
a quantity can be converted to another compatible unit.
Multiplication, subtraction, and raising to integer powers
are allowed without restr... |
47fbd7660f9c6022ad67caf06c6648d3644d887a | virajbpatel/text_message_analysis | /sms_preprocess.py | 1,293 | 3.578125 | 4 | # NLP Project
# Import relevant modules
import pandas as pd
import re
import nltk
from nltk.tokenize import word_tokenize
#nltk.download('punkt')
# Function to remove URLs from message
def remove_url(message):
url = re.compile(r'https?://\S+|www\.\S+')
return url.sub(r'', message)
# Function ... |
285107477f42dc9d5fb22f05d26e30c5c3041765 | eteq/keckguihws | /tkhelloworld2.py | 529 | 3.6875 | 4 | #!/usr/bin/env python
from Tkinter import Tk, Frame, Button, LEFT
class HelloApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Bu... |
843291cf73e0df86bb483207b4f09a9971253e62 | sunlingyu2931/Tensorflow- | /example 1.py | 1,092 | 3.609375 | 4 | import tensorflow as tf
import numpy as np
x_data = np.random.rand(100).astype(np.float32) # create data
y_data = x_data * 0.1 +0.3 # 真实值
# create tensorflow stracture (start)
Weight = tf.Variable(tf.random_uniform([1],-1,1)) # weight 一般用variable inpout output 神经元等用constant
biases = tf.Variable(tf.zeros([1]))
# 和上面的y... |
ee89cea4c018fea0dcb1318ab837f419328ee34b | jagchat/python | /02-language-basics/05-tuples/test.py | 2,667 | 4.75 | 5 | #tuple
# -a collection of elements/values
# -immmutable (not changeable)
# -allows duplicate elements
# -indexed (with an integer)
# -guaranteed of same order of elements
# -enclosed in parantensis - ()
#--initializing tuple with elements, nested tuples
s = ("hello", "hai", "world", "apple", "bat", "cat")
s = "hello",... |
bbbc34ab3687d59ae5656f0c8c38ce0447756fbd | naveensr89/sound_classification_methods | /src/utils.py | 1,104 | 3.765625 | 4 | import os
def get_path_fname_ext(full_file_path):
"""Return path, filename without extension and extension
ex: get_path_fname_ext('/Users/example/test.txt')
('/Users/example', 'test', '.txt')"""
path, filename = os.path.split(full_file_path)
fname, ext = os.path.splitext(filename)
retu... |
6e9cc576794dfa8b28bf350685bedec94e56ec88 | porigonop/code_v2 | /cours_POO/TP2/CompteEpargne.py | 1,375 | 4 | 4 | #!/usr/bin/env python3
from CompteBancaire import *
class CompteEpargne(CompteBancaire):
"""permet de representer un compte epargne a partire d'un compte bancaire
"""
def __init__(self, nom_titulaire, solde_initial = 1000, \
interet = 0.3):
"""on initialise a l'aide de l'interet men... |
cc6db5709b9ba5ccbb0160ad3336d5914334231f | elenaborisova/Python-Advanced | /18. Exam Prep/repeating_dna.py | 578 | 3.703125 | 4 | def get_repeating_dna(string):
repeating_subsequences = set()
index = 0
while index + 10 < len(string):
subsequence = string[index:index + 10]
if subsequence in string[index + 1:]:
repeating_subsequences.add(subsequence)
index += 1
return list(repeating_subsequences... |
11bb66562eefa09ca041e828237885c822efe9ed | xiaomingxian/python_base | /1.xxm/day12_minweb/3.装饰器/1/Demo2_装饰器.py | 562 | 3.84375 | 4 | # 持有原函数的引用 再对它加额外功能 同理与 java中的 装饰者模式
def out(fun):
def inner():
print("-----检验1------")
print("-----检验2------")
fun()
return inner
# @out
# def test1():
# print('-----test1-----')
def test1():
print('-----test1-----')
def main():
# @out
test1()
if __name__ == '... |
ac750073b1548456a6cf0089fa46b0bc1da9d27b | JesperGlas/networktool | /src/node.py | 778 | 3.5625 | 4 | from typing import Dict
from connection import Connection
class Node:
def __init__(self, name: str, processing: float = 0, queue: float = 0, connections: [Connection] = []):
self.name = name
self.proc = processing
self.queue = queue
self.con = connections
def __str__(self):
... |
7a07ef8a606a9b2943d9fecf980384c126bff0e8 | petersNikolA/turtle1 | /turtle8.py | 253 | 4 | 4 | import turtle
turtle.shape('turtle')
def sqspiral(n):
l = 5
while n > 0:
l += 5
for i in range(2):
turtle.forward(l)
turtle.left(90)
n -= 1
n = int(input())
sqspiral(n) |
6cc98eaaa9d4fd5be5af0eb4f77fcaa88df1e03b | anton1k/mfti-homework | /lesson_11/test_3.py | 377 | 4.125 | 4 | '''Напишите функцию calculate_min_cost(n, price) вычисления наименьшей стоимость достижения клетки n из клетки 1'''
def calculate_min_cost(n, price):
C = [float('-inf'), price[1], price[1]+price[2]] + [0]*(n-2)
for i in range(3, n+1):
C[i] = price[i] + min(C[i-1], C[i-2])
return C[n]
|
96abc8681717a9be43266bf9ce66b88ae6bab8dc | namntran/2021_python_principles | /workshops/4_busWhile2.py | 1,246 | 4 | 4 | # import math
n = int(input('Enter number of teams: '))
passengers = n*15
# num_small = int(math.ceil(passengers/10)) #number of small buses
# math.ceil(x) returns the smallest integer not less than x.
small = 0
big = 0
cost = 0.0
min_num_small = small # to keep track of number of small buses which gives minimum cost
... |
543bdcb309c599cb4dcb414ddcef1c5ee9be9e1f | fabifer/talleres | /matematicas.py | 7,701 | 4.15625 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
#matematicas.py: ejemplo de estructuras de datos
def validarEntero(s):
ingresoCorrecto = False
while(not ingresoCorrecto):
try:
valor = int(raw_input(s))
ingresoCorrecto = True
except ValueError:
print("Debes ingresar un numero entero")
return va... |
cba209273dc6319505bdfdd98be6aaee8fc93042 | Karan1012/GMM-using-PCA | /gmm.py | 9,195 | 3.515625 | 4 | """Functions for fitting Gaussian mixture models"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
def gmm(data, num_clusters, plot=False):
"""
Compute the cluster probabilities, means, and covariances of a Gaussian mixture model
:param data: d x n matrix of... |
096402638f0769a1465cbd88bb2efcab282c4c01 | vikramjit-sidhu/algorithms | /data_structures/fib_heap.py | 7,590 | 4.0625 | 4 | """
Fibonacci heap implementation
http://www.growingwiththeweb.com/2014/06/fibonacci-heap.html
http://stackoverflow.com/questions/19508526/what-is-the-intuition-behind-the-fibonacci-heap-data-structure
http://stackoverflow.com/questions/14333314/why-is-a-fibonacci-heap-called-a-fibonacci-heap
"""
import pdb
... |
34c91b86f8873bc55fbdad235a85bde1ea0eec07 | csangh94/python | /test02/mega/big13.py | 886 | 3.640625 | 4 | a = input("스티커 값 =") # 스티커값(변수)
q = int(a) # 저장값 정수 변환
b = input("사려는 스티커 갯수 :")
w = int(b)
c = input("책갈피 값 =")
e = int(c)
d = input("책갈피 사려는 갯수 :")
r = int(d)
t=q*w # 스티커 총 더한 값 저장
y=e* ... |
86b777fc38b93f9f1b26cda4f0ef178e9e3f75e9 | MiguelVillanuev4/EDA1-Practica11 | /Incremental.py | 568 | 3.96875 | 4 | def insertionSort(n_lista):
for index in range(1, len(n_lista)):
actual=n_lista[index]
posicion=index
print("valor a ordenar={}".format(actual))
while posicion>0 and n_lista[posicion-1]>actual:
n_lista[posicion]=n_lista[posicion-1]
posicion=posicion-1
... |
cd416a6380b0a0872b200f43aa060bb8e5bebfcf | PET-Comp-UFMA/Monitoria_Alg1_Python | /05 - Funções/q05.py | 277 | 3.671875 | 4 | def Primo(n):
countDivision = 2
if n%2 ==0 and n!=2:
countDivision=countDivision+1
elif n%3 == 0 and n!=3:
countDivision= countDivision+1
if countDivision>2:
print("false")
else:
print("true")
n = int(input())
Primo(n)
|
cf386459b075e8947153bf6748d5b2783346d428 | rafaelperazzo/programacao-web | /moodledata/vpl_data/420/usersdata/323/87560/submittedfiles/exe11.py | 272 | 3.8125 | 4 | # -*- coding: utf-8 -*-
Numero=int(input('Digite seu numero inteiro com 8 algarismos:'))
if Numero//10000000 < 1:
print ('NAO SEI')
else:
soma=0
while Numero>0:
ultimo= Numero%10
soma = soma + ultimo
Numero = Numero//10
print(soma) |
d3af5b9e19dbc1e6aef5f03ef8482fc0e3711f7a | user-lmz/python | /function/t1.py | 158 | 3.703125 | 4 | #!/usr/bin/env python3
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
m = add_end()
n = add_end()
print(m)
print(n)
|
05e3a53a361169997822a1d43c7152368628789e | helloworld575/leetcode | /longestSubString.py | 541 | 3.703125 | 4 | class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
maxlength = 0
substring = ""
for i in range(len(s)):
print(substring)
while s[i] in substring:
substring = substring[1:]
... |
d1d8264c969ec6d2cc31720150b5505b08fc9f0b | cyberjon/app-a-day | /hangman.py | 1,254 | 4 | 4 | import random
words = ['cat', 'computer','house','desktop','python']
rand_no = random.randint(0,len(words)-1)
random_word = words[rand_no]
word = "_" * len(random_word)
clue = list(word)
lives=5
user_input = input('I am thinking of a random word. Would like to play Y/N:')
if user_input.lower() =='n':
p... |
5bacc3d0bfd825b933715ecd18cdc59b8a4e3ad2 | Kyeongrok/python_algorithm | /chapter09_sort/01_select.py | 562 | 3.953125 | 4 | def findSmallestIndex(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selectionSort(arr):
resultArr = []
for i in range(len(arr)):
smallest = fin... |
d0af1c914a40daae9a3f21c84939ba29239a14e7 | sigirisetti/python_projects | /pylearn/numpy/data_analysis/fitting_line.py | 438 | 3.65625 | 4 | x = [0, 0.5, 1, 1.5, 2.0, 3.0, 4.0, 6.0, 10]
y = [0, -0.157, -0.315, -0.472, -0.629, -0.942, -1.255, -1.884, -3.147]
import numpy as np
p = np.polyfit(x, y, 1)
print(p)
slope, intercept = p
print(slope, intercept)
import matplotlib.pyplot as plt
xfit = np.linspace(0, 10)
yfit = np.polyval(p, xfit)
plt.plot(x, y, '... |
47734f1982d6ad94cd0c7e6b16cdf466d973c17d | wisesky/LeetCode-Practice | /src/101. Symmetric Tree.py | 1,203 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
return self.h... |
8aefdf9fb53dc7bd9aa7bf74ee56f50606213f86 | luizaq/100-days-of-code | /Day4_rockpaperscissors.py | 1,437 | 3.984375 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''... |
2186d77e302e51b5b08ff572a3e589642e271463 | RaghavGoyal/Raghav-root | /python/code/src/intermediate/Decorators/6.TimedFunctionsUsingDecorator.py | 592 | 3.65625 | 4 | from functools import wraps
from time import perf_counter
def timer(func):
@wraps(func)
def wrapper(n):
startTime = perf_counter()
result = func(n)
endTime = perf_counter()
duration = endTime - startTime
print(f'{func} took {duration:.8f}s')
return result
r... |
b150da66ebc3c2258ca1381f12ba58b73063aea5 | wilane/content-mit-latex2edx-demo | /python_lib/matrix_evaluator.py | 2,092 | 3.578125 | 4 | #
# formula_evaluator: allows multiple possible answers, using options
#
import numpy
from evaluator2 import is_formula_equal
def test_formula(expect, ans, options=None):
'''
expect and ans are math expression strings.
Check for equality using random sampling.
options should be like samples="m_I,m_J,I... |
f25fc2c67bb93bef06237828fb7650fd5575d9f0 | PrateekPethe/Small-dictionary | /dictionary.py | 1,122 | 3.78125 | 4 | import json
from difflib import get_close_matches
data = json.load(open("dictionary.json"))
def translate(w):
w = w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w, data.keys())) > 0:
yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % get_close_matches(w... |
835d4da80ceb5652d9ea6b020814ba752daa73fb | vrcunha/db_sql_and_nosql | /sqlite/funcs/crud_sqlite.py | 2,966 | 3.53125 | 4 | import os
import sqlite3
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
def connect():
"""Connects to SQLite database."""
try:
connection = sqlite3.connect('sqlite_python.db')
# print('Connection Succefully')
return connection
except sqlite3.Error as e:
... |
e578e16ee1cf342a67e195d3d1cf2c0b5a120c00 | syamilisn/Python-Files-Repo | /systemSoftware/sample.py | 83 | 3.515625 | 4 | dict={1:"we",2:"i"}
print(dict)
a=4
asval="they"
dict.update({a:asval})
print(dict) |
a1b955cfe6f2e47bf5d28d4e4a1fbdd3b373db0a | hpeppercorn/connect_four | /connect4_{hopepeppercorn}.py | 10,476 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
A connect four game that can be played by two people, a person vs a computer or
the computer vs itself
"""
from copy import deepcopy
import os
from random import choice
def newGame(player1, player2):
"""
takes 2 string parameters corresponding to each player's name, and r... |
00212f0146dc056290ca3a4b44f61d44f7aa5113 | pvpk1994/Leetcode_Medium | /Python/LinkedLists/Nth_Node_Remove.py | 1,972 | 3.578125 | 4 | # Remove Nth Node from Linked List
# Interesting: One Pass Approach using Fast and Slow Pointers
# Time Complexity: O(N) and Space Complexity: O(1)
# Leetcode Question: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0... |
bd990aa94481f6ca4ce8a8b76ce1138a29f65355 | Alhzz/Python3 | /Key_Midterm.py | 320 | 3.640625 | 4 | """ Key_Midterm2014 """
def calculate():
""" Calculate Key """
id_card = input()
last_digit = (int(id_card)%1000)*10
total = 0
for i in id_card:
total += int(i)
total += last_digit
if total < 1000:
total += 1000
total = total%10000
print("%04d" %total)
calculate()
|
08f27c4fe465ecc9fa6144da1db658683ac865c3 | chand777/python | /sha.py | 953 | 4.40625 | 4 | # first_list=[1,2,3,4]
# second_list=first_list.copy()
# print(first_list)
# print(second_list)
# second_list[1]=1000
# print(first_list)
# print(second_list) #Here you can see that item for second_list only changed not for first_list because both the list has diffrent diffrent location
# first_list=[[1,2,... |
25b8f3ecd8769e9e5ec17838ec746b37fe83241c | sunilnandihalli/leetcode | /editor/en/[846]Hand of Straights.py | 1,421 | 3.71875 | 4 | # Alice has a hand of cards, given as an array of integers.
#
# Now she wants to rearrange the cards into groups so that each group is size W
# , and consists of W consecutive cards.
#
# Return true if and only if she can.
#
#
#
#
#
#
# Example 1:
#
#
# Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
# Ou... |
2a284c0174789853e2fe4640fba69deefcc3948e | maokitty/IntroduceToAlgorithm | /dataStruction/avl.py | 9,130 | 3.859375 | 4 | import random
class Node(object):
def __init__(self,key,right=None,left=None,parent=None):
self.right = right
self.left = left
self.parent = parent
self.key = key
# 树是单独的结构,BST用来操作BST树,确保BST的性质不会有改变
class AvlBST(object):
"""左子树的值小于父子树的值小于等于右子树的值
最坏情况是:成为一条链
"""
def __init__(self):
self.root = None
... |
c25ef4b7f4e87ec0604b457093c0dcd1f76a9460 | anlanamy/DSA | /hw-1700015495/date_without_datetime.py | 448 | 3.921875 | 4 | #date
dtstr=input('Enter the datetime:(20170228):')
datekey={1:0,2:31,3:59,4:90,5:120,6:151,7:181,8:212,9:243,10:273,11:304,12:334}
datekeyr={1:0,2:31,3:60,4:91,5:121,6:152,7:182,8:213,9:244,10:274,11:305,12:335}
year=int(dtstr[:4])
month=int(dtstr[4:6])
day=int(dtstr[6:])
if year%4==0:
if year%100==0 and year%400!... |
31b54a5fe7ff8bea36169a8821891aa460f6c443 | wating41/game | /Python-game/01-if语句.py | 997 | 3.875 | 4 | import datetime
# if True :
# print('hello')
a = '赢'
if False:
print('你猜 1')
else:
print('你猜 2')
print('你确认是 %s' % a)
b = 'low'
c = ''
d = '98'
# 在命令行让用户输入一个用户名,获取用户输入,并进行判断
# 如果用户输入的用户名是admin,则显示欢迎管理员光临
# 如果用户输入的是其他的用户名,则什么也不做
name = input('请输入用户名:')
if name == 'admin':
print('欢迎管理员 %s' % name)
el... |
bd54456f0efd89489dc5bd9d0aab5b0f49dc5602 | Kobe-J/Python | /seleniumtest1/stu1.py | 6,638 | 3.890625 | 4 | import math
#
#
# def enroll(name, gender, age=6, city='Beijing'):
# print('name:', name)
# print('gender:', gender)
# print('age:', age)
# print('city:', city)
# print(enroll("yaoxilong","aa",22,"haerbin"))
#
#
# def calc(*a):
# sum = 0
# for n in a:
# sum = sum + n * n
# return su... |
f0fb4cb44e672d8e3da738bf94840febdff6564e | Sagar-Kumar-007/ML-and-Ds- | /practice/Bengaluru House Price Detection/Flask basics/flask_basics_3.py | 916 | 3.953125 | 4 | # More about Dynamic Url
# The default variable type is string...you can change the data type to int, float and path...ex: <int:variable-name>
# You can also use two or more route decorators to run more functions on different web addresses.
# Note that using while using the parameters of route decorator it is preferred... |
11e3dfb3d97bc7afd526283af39e672e72bcf56f | lorenzo3117/python-text-finder | /pythonTextFinder.py | 2,271 | 3.65625 | 4 | import os
import shutil
import re
def askInput():
print("This script will search for text you type in all txt files from the current directory and all its subdirectories. If any .txt files containing your text are found, you can copy them in a folder of your choice if you'd like to.\n")
text = input('Wha... |
2f167f5317c8c3dc8fb146761eedb72d5f65dcc8 | Athreyan/guvi_python | /num_wrd.py | 237 | 3.921875 | 4 |
def int_to_en(num):
d = { 0 : 'Zero', 1 : 'One', 2 : 'Two', 3 : 'Three', 4 : 'Four', 5 : 'Five',
6 : 'Six', 7 : 'Seven', 8 : 'Eight', 9 : 'Nine', 10 : 'Ten'}
return d[num]
num=int(input())
print(int_to_en(num))
|
98d6efee02a276736abaccc1d04b8bd698dcbd01 | lilyfofa/python-exercises | /exercicio37.py | 517 | 4.15625 | 4 | numero = int(input('Digite um número inteiro: '))
base = int(input('Digite a base para a qual ele será convertido:\n1 - Binária\n2 - Octal\n3 - Hexadecimal\nSua resposta: '))
if base == 1:
print(f'O número {numero} na base binária é {bin(numero)[2:]}.')
elif base == 2:
print(f'O número {numero} na base octal é ... |
62e25ea245025f9b856766ce40eb39c88cfa4211 | jetli123/python_files | /Python基础教程/Python教程-字符串.py | 538 | 3.75 | 4 | width = input("Please enter width: ")
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
Format = '%-*s%*.2f'
print '=' * width
print header_format % (item_width, 'Item', price_width, 'Price')
print '-' * width
print Format % (item_width, 'Apples', price_width, 0.4)
print Format % (item_width, ... |
8eecf88f1c9e569482f71f41e222a8648f68da26 | bakeunbi99/Python | /Example/book/4_3_Ex01.py | 333 | 3.6875 | 4 | # 원소가 한 개인 경우
t = (10, )
print(t)
# 원소가 여러개인 경우
t2 = (1, 2, 3, 4, 5, 3)
print(t2)
# 튜플 색인
print(t2[0], t2[1:4], t2[-1])
# 수정 불가
# t2[0] = 10 #error
# 요소 반복
for i in t2 :
print(i, end=' ')
# 요소 검사
if 6 in t2 :
print("6 있음")
else:
print("6 없음") |
fda2029330ea1c3e781343d0ff159435b3fb1fa3 | alllecs/l_python | /inputout3.py | 447 | 3.53125 | 4 | #!/usr/bin/python3
d = int(input())
know_words = []
new_words = []
for i in range(0, d):
know_words.append(str(input().lower()))
l = int(input())
for i in range(0, l):
new_words.append(list(map(str, input().lower().split())))
for i in range(0, len(new_words)):
for j in range(0, len(new_words[i])):
... |
935e91d3ec7bef8ccb3e07dbc41060d0068788ab | Activity00/Python | /leetcode/零钱兑换.py | 810 | 3.6875 | 4 | # coding: utf-8
"""
@author: 武明辉
@time: 2018/6/7 14:43
"""
"""
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
示例 1:
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
示例 2:
输入: coins = [2], amount = 3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。
"""
def coinChange(coins, amount):
... |
84f67d4e99e7f0634f4f8053fe7048914915b78c | erjan/coding_exercises | /unique_length_3_palindromic_subsequences.py | 2,068 | 4.1875 | 4 | '''
Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new s... |
186f0c48fa8e1351129377ade79bb1b50cf775c4 | mattfrancis888/Python_Data_Structures | /fran0880_a8/src/functions.py | 2,646 | 3.75 | 4 | '''
-------------------------------------------------------
[program description]
-------------------------------------------------------
Author: Matthew Francis
ID: 180920880
Email: fran0880@mylaurier.ca
__updated__ = "2019-03-20"
-------------------------------------------------------
'''
from Letter impo... |
7c3bfb385d867930d0f8563f7d49e7a8655d4c1e | Chandan-CV/school-lab-programs | /lab program 36.py | 949 | 4.125 | 4 | #Program 36
#Write a program to create a dictionary of product name and price. Return
#the price of the product entered by the user.
#Name: Neha Namburi
#Date of Excetution: October 14, 2020
#Class: 11
d={} # empty dict
ans='y'
while((ans=='y') or (ans=='Y')):
# values of p and pr are local to this while loop- i.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.