blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
02264880c920aced800f78c08d696a6d47056f92 | moisesquintana57/python-exercices | /tema_7_estructura_tipo_tupla/ejer1.py | 402 | 3.71875 | 4 | # creamos una función para cargar los valores
def cargar():
dia=int(input("Ingrese el día: "))
mes=int(input("Ingrese el mes: "))
year=int(input("Ingrese el año: "))
tupla=(dia,mes,year)
return tupla
# creamos una función para imprimir la tupla
def imprimir(tupla):
print(tupla[0],tupla[1],t... |
f7fcc3f528446fee573784bb5b7ff1ccd7268cae | moisesquintana57/python-exercices | /tema_11_poo/ejer1.py | 767 | 3.796875 | 4 | # inicializamos la clase
class Alumno:
# inicializamos los atributos
def inicializar(self,nombre,nota):
self.nombre=nombre
self.nota=nota
# función para imprimir los datos
def imprimir(self):
print("Nombre: ",self.nombre)
print("Nota: ",self.nota)
# función para obtener el re... |
85c9ae2811284e132ddfde82b542d1a75d20d6eb | moisesquintana57/python-exercices | /tema_5_estructura_tipo_lista/ejemplo4.py | 323 | 3.75 | 4 | #Declaramos las listas
alumnos=[]
notas=[]
# Rellenamos los datos
for x in range(5):
nombre=input("Ingrese el nombre del alumno: ")
nota=int(input("Ingrese la nota del alumno: "))
alumnos.append(nombre)
notas.append(nota)
# imprimimos los datos
for x in range(5):
print(alumnos[x]+" "+str(notas[x])... |
f2961a3cecefea3b44f1f64bbac1949d5131bae3 | rdevnoah/python_practice01 | /prob01.py | 307 | 4 | 4 | # 키보드로 정수 수치를 입력 받아 그것이 3의 배수인지 판단하세요
number = input('수를 입력하세요:')
result = (print('3의 배수입니다.') if (int(number) % 3 == 0) else print('3의 배수가 아닙니다.')) if (number.isnumeric()) else print('정수가 아닙니다.')
|
15355c583939d757c1407c4a5a0a264c023ff2a3 | MariomcgeeArt/compose-method | /remove_assignment_to_param.py | 1,333 | 4.1875 | 4 | # By Kami Bigdely
# Remove assignment to method parameter.
"""This file will calculates kinnetic energy"""
class Distance:
"""Represents the distance"""
def __init__(self, value, unit):
self.unit = unit
self.value = value
class Mass:
"""Represents the mass of the object"""
def __in... |
46e89696df8bba19b8e986389a81247d35df9223 | CarlosPereiraTI/Python_OOP | /OOP_PatrickLoeber/OOP3.py | 1,911 | 4.375 | 4 | # Code based on Patrick Loeber tutorial
# https://www.youtube.com/watch?v=-pEs-Bss8Wc
# OOP - Inheritance
"""Inheritance is the capability of one class to derive or inherit
the properties from another class. The benefits of inheritance are:
... It is transitive in nature, which means that if class B inherits... |
1ff154aa5e3394b5c60bd15b241925edbfa9c6fe | dhruvchawla1996/csc411_a3 | /naive_bayes.py | 5,151 | 3.890625 | 4 | # Imports
import math
def small_multiply(numbers):
"""
Multiply a lot of small numbers (values may be close to 0)
PARAMETERS
----------
numbers: list of floats
elements should be in (0, 1]
RETURNS
-------
float
product of all numbers
"""
log_sum = 0.
for ... |
e94d25e87fe4d8572b36edf0942e4890675c7fb6 | DanielZim/PyOpteryx | /pyopteryx/utils/sorting_to_compare.py | 3,506 | 3.5625 | 4 | import glob
import os
from operator import attrgetter
import lxml.etree as le
# Function to sort XML elements by id
# (where the elements have an 'id' attribute that can be cast to an int)
def sortbyname(elem):
name = elem.get('name')
if name:
try:
return name
except ValueError:
... |
7e5c19f1e1da5ac525382264668cd4925eaa709c | dhyeyjoshi/Pygame-Projects | /Rank of three persons by Dictionary.py | 1,323 | 4.21875 | 4 | """
@Clever Programmer
Backstory: Usain Bolt, you, and Qazi
had a race. Surprisingly, Usain bolt won.
You came in 2nd and Qazi came in 3rd :(.
Can you think of a way to write a function
that given a person's name, returns his/her place?
ALSO
Can you think of a way to write a function
that given a place, returns h... |
fc40fcdfef20fc5cf9cc18d3e0e358c2c9ba5169 | taradactyl27/npuzzle | /solver.py | 5,915 | 4 | 4 | ######################
# Alex Taradachuk #
# Prof. Raja #
# CSCI-350 #
# Assignment 1 #
######################
import math
import collections
import state
import sys
from queue import PriorityQueue
def breadth_first_search(stateInitial):
frontier = collections.deque() #use deque as the ... |
763b784116981106213e1114aa71f86964ecd611 | Proxims/PythonLessons | /Lesson_5_Strings.py | 746 | 4.1875 | 4 | # Lesson 5 Strings
mystring = "Bla Bla"
name ="mIkhAil lantSov"
print(name)
print(name.title())
print(name.upper())
print(name.lower())
print("------------------------\n")
print("Stroka 1\nStroka 2\n\nStroka 3")
print("Messages:\n\tMessage1\n\tMessage2\n\tMessage3\nEND")
print("Lower name: " + name.lower())
print("-... |
a98cddc8dece9c8f9b9aaa9e129f0dc4be083672 | L200170038/prak_asd_b | /MODUL8ASD/no3.py | 601 | 3.890625 | 4 | class Stack(object):
"""docstring for Stack"""
def __init__(self):
self.item=[]
def isEmpty(self):
return (len(self.item))==0
def __len__(self):
return len(self.item)
def peek(self):
if self.isEmpty() == True:
return None
else:
return self.item[-1]
def pop(self):
if self.is... |
5dc4de9a43c3be4e3539aeaea0d898f1665612f8 | ShinjoSato/InfectionPrediction | /note/src/multivariable.py | 1,410 | 3.546875 | 4 | import numpy as np;
import math;
import matplotlib.pyplot as plt;
import csv;
def sigmoid(x):
return 1.0/(1.0 + pow(math.e, -x));
def cost_function(hw, y):
if(y == 1): return -1*math.log(hw);
else: return -1*math.log(1-hw);
def gradient_descent(W, alpha, data, prediction):
W[0] = W[0] + alpha *... |
f0084b6019f88d954cbe1051c1676c2d7fd0aff7 | GiovanH/pysnip | /snip/data.py | 4,010 | 4.375 | 4 | # Data structures
def chunk(it, size):
"""A generator that yields lists of size `size` containing the results of iterable `it`.
Args:
it (iterable): An iterable to split into chunks
size (int): Max size of chunks
Yields:
lists
"""
from itertools import islice
iter_it ... |
ad678dafc799cd24580451ee75a8fa49e555deaf | tdonovan/RUP | /rectangle.py | 240 | 3.625 | 4 | #!/usr/bin/python
#
print "hey now brown cow!"
class rectangle:
length=15.6
width=12.5
def recArea(self):
return self.length*self.width
rectObject=rectangle()
print rectObject.length
print rectObject.width
print rectObject.recArea()
|
08db7fae468f5bae6e678963e515d4c4e3cfcd90 | YashawantParab/Job_Portal | /Service001.py | 2,121 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 11:20:09 2019
@author: yasha
"""
from pymongo import MongoClient
try:
conn = MongoClient()
print("Connected successfully!!!")
except:
print("Could not connect to MongoDB")
db = conn.Job_Portal
collection = db.Services
_id = inp... |
7f487d86d98c835bcbfc041e0d675fe83d6a591d | gurunathan055/KCETCollegePredictor | /KCETCollegePredictor.py | 18,753 | 3.515625 | 4 | import streamlit as st
import pandas as pd
import requests
import io
from PIL import Image
image = Image.open('BranchCode.png')
col_names = ["CETCode", "College" ,"Location", "Branch", "1G", "1K", "1R", "2AG", "2AK", "2AR", "2BG", "2BK", "2BR", "3AG", "3AK", "3AR", "3BG", "3BK", "3BR", "GM", "GMK", "GMR", "SCG", "SCK... |
e31721196528a7ea087005bf2f1a45d3f5fad149 | tinawong15/softdev-work | /08_lemme_flask_u_sumpn/app.py | 705 | 3.84375 | 4 | # Tina Wong
# SoftDev1 pd7
# K08 -- Fill Yer Flask
# 2019-09-20
from flask import Flask
app = Flask(__name__) #create instance of class Flask
@app.route("/") #assign fxn to route
def hello_world():
print("about to print __name__...")
print(__name__) #where will this go?
return "hello world!"
@app.route("... |
6de166cd87902a993d2633a0a9586ee47ab6822f | adelehedrick/ud120-projects | /datasets_questions/explore_enron_data.py | 2,286 | 3.59375 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
ae58cb9a11411c7335e0ae27dc3c51a29409b433 | AidenLong/data_fill | /rv/test.py | 516 | 3.859375 | 4 | # -*- coding utf-8 -*- #
# data = [1, 2, 3, 4, 5]
# index = data.index(2)
# print(index)
#
# new_data = [0] * len(data)
# new_data[index] = 1
# print(new_data)
import pandas as pd
import numpy as np
# 通过行标签索引行数据 index可以为整数
data = [[1, 2, 3], [4, 5, 6]]
index = [0, 1]
columns = ['a', 'b', 'c']
df = pd.DataFrame(data... |
16848a58ac8278708f02d239805ed066b8bc0692 | minjungkim85-zz/cs-review | /arrays/findsub.py | 1,147 | 3.78125 | 4 | # Find the subarray whose sum matches the desired value
# https://www.geeksforgeeks.org/find-subarray-with-given-sum/
data = [1, 4, 20, 3, 10, 5]
desiredsum = 33 # desired sum
print("Init: " + ''.join(str(data)))
print("Desired sum: %d.\r\n" % desiredsum)
# For each element in array
n = len(data)
result = (None,None)... |
55047ca2977a85acbd72104da6a4338d8843bcb0 | jc-LeeHub/Python-Learning | /Drawing Board/画板.py | 314 | 3.65625 | 4 | from tkinter import *
root = Tk()
w = Canvas(root, width=400, height=200)
w.pack()
def paint(event):
x1,y1 = (event.x-1), (event.y-1)
x2,y2 = (event.x+1), (event.y+1)
w.create_oval(x1, y1, x2, y2, fill="red")
w.bind("<B1-Motion>", paint)
Label(root, text="小画板").pack(side=BOTTOM)
mainloop()
|
59b74f947c25b39e54b2dbaeae077e5bf180419c | AlexSG18/Assignment1 | /DigitReg.py | 1,735 | 3.640625 | 4 | import tensorflow as tf
import matplotlib.pyplot as plt
mnist = tf.keras.datasets.mnist # 28x28 images og hand written digits 0-9
(x_train, y_train), (x_test, y_test) = mnist.load_data() #load the MNIST dataset using the Keras helper function
x_train = tf.keras.utils.normalize(x_train, axis=1) # scales data between ... |
8f834deeda1796c02d3a376b10b49f58e6ee0fb9 | Hieu-Ma/algos | /algoExpert/easy/insertionSort.py | 770 | 4.28125 | 4 | """
Clarification
implement insertion sort
"""
"""
Approach
loop through the array, for each element, we want to iterate backwards and find it's place in the array
to find the place in the array, we constantly swap between two numbers, based off of it's value
if it's < the number we swap, else no swapping is needed
... |
8b01a0ce8400635f8a1a317ecc976cf472a564e7 | archeranimesh/HeadFirstPython | /SRC/Chapter_13-Advanced-Iteration/10_tuple_comp_generator.py | 192 | 4.21875 | 4 | for i in [x ** 3 for x in [1, 2, 3, 4, 5]]:
print(i)
for i in (x ** 3 for x in [1, 2, 3, 4, 5]):
print(i)
mytuple = (x ** 3 for x in [1, 2, 3, 4, 5])
for x in mytuple:
print(x)
|
13a3bca91b1ddc35e7b24aba15e143f8493d0f78 | archeranimesh/HeadFirstPython | /SRC/Chapter_01-The-Basics/03_for_example.py | 135 | 3.890625 | 4 | for i in [1, 2, 3]:
print(i)
print("\n\n")
for ch in "hello!":
print(ch)
print("\n\n")
for num in range(5):
print(num)
|
80c39dceef8308a0ff7468971960a686085273e3 | yubi5co/python-practice | /Python_basic/5.5day/27. Quiz5.py | 922 | 3.6875 | 4 | '''퀴즈) 표준 체중을 구하는 프로그램을 작성하시오
*표준 체중 : 각 개인의 키에 적당한 체중
(성별에 따른 공식)
남자 : 키(m) x 키(m) X 22
여자 : 키(m) x 키(m) x 21
조건1 : 표준체중 별도의 함수 내에서 계산
* 함수명 : std_weight
* 전달값 : 키(height), 성별(gender)
조건2 : 표준 체중은 소수점 둘째자리까지 표시
(출력 예제)
키 175cm 남자의 표준 체중은 67.38kg 입니다.'''
def ... |
3499c0abfa96f2efb25fa0bbb87b0a6062750919 | VishalJoshi21/Python_Program | /prg16.py | 1,291 | 3.546875 | 4 | import os.path
from datetime import date
class library:
def issue_book(self):
li=[]
file=open("prg16.txt",'a')
name=input("Enter Student name :")
dat=input("Enter date(dd/mm/yy) :")
book_id=input("Enter Book ID :")
book_name=input("Enter Book name :")
... |
4fa184952059e4525a85c17ef7f390ec8826e854 | VishalJoshi21/Python_Program | /prg2.py | 233 | 4.125 | 4 | num1=10;
num2=20;
print("Before Swapping :");
print("Number 1 :",num1);
print("Number 2 :",num2);
num1=num1 ^ num2;
num2=num1 ^ num2;
num1=num1 ^ num2;
print("After Swapping :");
print("Number 1 :",num1);
print("Number 2 :",num2); |
3f9e180a6ca0b74e017aef1377356c1378e3c254 | VishalJoshi21/Python_Program | /prg19.py | 449 | 3.515625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
data = [['101', 'M', 34],
['102', 'F', 40],
['103', 'F', 37],
['104', 'M', 30],
['105', 'F', 44],
['106', 'M', 36],
['107', 'M', 32],
['108', 'F', 26],
['109', 'M', 32],
['111', 'M', 36... |
b1f953c29098de137f1455fc38662ed527dcb73f | jzraiti/Coverage_Algorithm_Enviornmental_Sampling_Autonomous_Surface_Vehicle | /Project_Files/Jasons_Functions/overlay_images.py | 1,342 | 3.546875 | 4 |
import numpy as np
import cv2
# import sys
# sys.path.append("/home/jasonraiti/Documents/GitHub/USC_REU/Project_Files/Jasons_Functions/")
from open_or_show_image import *
from get_negative_image import *
def overlay_images (image1,image2,make_negative_1, make_negative_2):
"""overlays two images with option ... |
6c23fd40006912030017cefacc6159c871de6558 | KarmaTsring/Advanced-Search-system- | /Search_Algorithm.py | 4,472 | 4.15625 | 4 | names_numbers = {'santosh': 9860777044, 'sakar': 9460777044, 'tsering': 9860722044, 'babita': 98612137044, 'ajay': 9860777022,
'akul': 9860777041,'atul': 9860771041,'Sachin': 9822777041,'Pritam Pani ko dai': 9860777042, 'tsering Topchen': 9860777041,
'ambay': 95656865654, 'sarita': 9... |
761eb302257472601e23c31cfeb41ac62bbfff1b | elijahdaniel/Intro-Python-II | /src/room.py | 710 | 4.03125 | 4 | # Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, room_name, description):
self.room_name = room_name
self.description = description
self.items = []
def __str__(self):
# prints current room
... |
f6893ed3f2baf6c5cc98c2df728b1ebc8d3a0c81 | YoungYoung619/leetcode | /problem/9_Palindrome_Number.py | 953 | 3.984375 | 4 | """
Copyright (c) College of Mechatronics and Control Engineering, Shenzhen University.
All rights reserved.
Description :
Author:Team Li
"""
"""
9. Palindrome Number
Easy
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Ou... |
14c62ee28cdbaba1c79d0404006a1997b9486152 | justsolo-smith/-trie | /106.从中序与后序遍历序列构造二叉树.py | 974 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=106 lang=python3
#
# [106] 从中序与后序遍历序列构造二叉树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: Lis... |
a60ec4e75455e8a46677c1b856d51196d35ef4bb | justsolo-smith/-trie | /024-二叉树中和为某一值的路径.py | 886 | 3.609375 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.sumc = 0
self.a = []
self.b = []
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNum... |
bdf30446041b3cfb7105285c8d4a318c10fd2204 | justsolo-smith/-trie | /合法的二叉搜索树.py | 1,394 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
实现一个函数,检查一棵二叉树是否为二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
'''
#递归遍历
class Solution:
def isValidBST(self, root: TreeNode) -> b... |
60a951cfca23802ebfa047a13d88c113b9aa5366 | Bernder/DigitalizaPUE | /04_if.py | 652 | 3.875 | 4 | #Crear un script en el que guardéis en una variable un número
numerico = int(input("Hola, introduce un número, por favor "))
#Controlar el tamaño del número en 4 rangos (menor de 20, entre 20 y 39, entre 40 y 59, mayor de 60)
#En cada uno de los casos imprimir por pantalla el número que se haya introducido.
if nu... |
d32fd686a763455b39390c3faee05b7400a59f65 | Limarceu/Uri_Online_Judge | /1-Iniciante-Beginner/1049 - Animal.py | 686 | 3.71875 | 4 | def animal(bicho):
animal = {
'aguia' : ['vertebrado', 'ave', 'carnivoro'],
'pomba' : ['vertebrado', 'ave', 'onivoro'],
'homem' : ['vertebrado', 'mamifero', 'onivoro'],
'vaca' : ['vertebrado', 'mamifero', 'herbivoro'],
'pulga' : ['invertebrado', 'inseto', 'hematofago'],
... |
67d9bb8240bffb053f45d133ffc2633ee4698264 | dncuervo/Sucursales | /service/agencies.py | 1,257 | 3.71875 | 4 |
class Agency():
"""Class representing a Sucursal"""
def __init__(self, nombre, direccion,telefono, sucursal_id):
self.nombre = nombre
self.direccion = direccion
self.telefono = telefono
self.sucursal_id = sucursal_id
self.preexistence = []
def add_preexistence(self... |
9f1ea318f4773b17653d4c553508de2384553604 | EllisMiao/pythonStudy | /Exercise/ex3.py | 617 | 3.59375 | 4 | #coding:utf-8#
#
print "I will now count my chickens:"
#ĸĿ
print "Hens",25+30/6
#Ŀ
print "Roosters",100-25*3%4
#㼦
print "Now I will count the eggs:"
#
print 3+2+1-5+4%2-1/4+6
#ж
print "Is it true that 3+2<5-7?"
#ʽ
print 3+2<5-7
#3+2
print "What is 3+2?",3+2
#5-7
print "What is 5-7?",5-7
#
print "Oh,that's why it's Fals... |
8ddd780656b43555e579100410a62dfcbc2cdebd | abhisheksoni0073/PYTHON- | /OOPS/5.py | 507 | 4 | 4 | #The isinstance() method is used to check the relationship between the objects
#and classes. It returns true if the first parameter, i.e.,
#obj is the instance of the second parameter, i.e., class.
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multipli... |
3f2456541393b21384f2ffcf34026a3155ec4f7c | charlihi/bridges-python | /bridges/line_chart.py | 9,624 | 4.125 | 4 |
class LineChart:
"""
@brief Show series of data or functions using a line chart.
Line charts (https://en.wikipedia.org/wiki/Line_chart) are used to
represent graphically functions such as f(x) = 3*x+1, or data such
as temperature of a liquid on a stove as time passes. A individual
functio... |
6dfedaa74212424f00d849f929448b8a98333c50 | charlihi/bridges-python | /bridges/array2d.py | 1,107 | 3.71875 | 4 | from bridges.array import *
class Array2D(Array):
"""
brief This class can be used to create 2D arrays of type Element<E>.
@author Kalpathi Subramanian, Matthew McQuaigue
@date 10816, 51717, 53018
This class can be used to create arrays of type Element<E> where E
is a generic... |
10a36ddcb6b16c2c294dc3fcd263b08014ecfbb9 | charlihi/bridges-python | /bridges/bridges.py | 12,761 | 3.671875 | 4 | from bridges.connector import *
from bridges import ColorGrid
import os
import json
class Bridges:
"""
@brief The bridges class is the main class that provides interfaces to datasets, maintains user and assignment information, and connects to the bridges server.
The bridges class is responsible for ... |
95e676a15dbc5815a2b4eeced008e217f9df793b | GDSC-SCTCE/Python-overflow | /instagram details/instaloader.py | 989 | 3.53125 | 4 | # importing libraries
from bs4 import BeautifulSoup
import requests
# instagram URL
URL = "https://www.instagram.com/{}/"
# parse function
def parse_data(s):
# creating a dictionary
data = {}
# splitting the content
# then taking the first part
s = s.split("-")[0]
# again splitting the content
s = s.spli... |
114a4ad47eddc0997027e48e0af66c33f22d7f4a | SimonAwiti/tutorial | /loops.py | 175 | 3.765625 | 4 | name = raw_input ("enter your name: ")
if len(name) < 6 and len(name) < 3:
print ("name must contain more than 3 xters and less than 6 xters")
else:
print ("proceed")
|
d15ef88b6faadd22dccbe91e57bcf663c54eabae | aarthi-arul/Daily-Practice | /find the percentage.py | 547 | 3.828125 | 4 | '''Print the average of the marks array for the student name provided, showing 2 places after the decimal.
ex=
Input=3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika
Output=56.00'''
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
... |
bcd8403244530d6e775470be5517acd84b116df4 | BBFPHIL/ProgrammingTheOneFifty | /StringBuffer/stringBuffer.py | 527 | 4.03125 | 4 | #!/usr/bin
#Phillip Walker
#Objective(s): Use a string buffer to implement a sentence
#
#String buffer to form sentence
#@param words: list of words
#
def stringBuffer(words):
#String list
str_list = []
#each word
for num in xrange(len(words)):
#append to sentence str
... |
4fb0138c22d0b81702ab29fb85ffefcda0117795 | vanessa-bergen/AlgorithmsCourse | /dijkstra-minHeap.py | 9,949 | 3.84375 | 4 | """
The file contains an adjacency list representation of an undirected weighted graph with 200 vertices labeled 1 to 200.
Each row consists of the node tuples that are adjacent to that particular vertex along with the length of that edge.
For example, the 6th row has 6 as the first entry indicating that this row corre... |
233e5281c3015487d4516d4a839a35872ff415a3 | vanessa-bergen/AlgorithmsCourse | /weightedCompletionTimes.py | 1,300 | 3.5 | 4 | class WeightedSum:
def __init__(self, fileName):
self.arr = []
f = open(fileName, "r")
firstline = True
for line in f:
if firstline:
firstline=False
continue
weight, length = line.rstrip('\n').split(" ")
... |
5519c9a363542b47e91e9f5a7f12b74a6b5f540f | stzhangjk/PythonDemo | /isinstance.py | 392 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog) and isinstance(dog, Animal))
import types
print(isinstance('123', str))
print(isinstance(123, int))
print(isinstance(abs, types.BuiltinFunctionType))
print(isinstance([... |
c83c4e1f388c4163d4f84fbb079ce204406face9 | stzhangjk/PythonDemo | /sorted.py | 170 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = [5, 6, -7, 3, -6, 7, 2, 0, -9, 4, 98, 2, 5]
print(sorted(a))
print(sorted(a, key=abs))
print(sorted(a, reverse=True)) |
5a447ba7fe3d841a11c30b5ed34f1e86725d8635 | stzhangjk/PythonDemo | /filter.py | 393 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filter()
def odd_number():
n = 1
while True:
n = n + 2
yield n
def not_divide(n):
return lambda x: x % n != 0
def prime():
yield 2
a = odd_number()
while True:
n = next(a)
yield n
a = filter(not_divid... |
4a1ed56ae616345bb159c782bbbcbc885e7e9b7e | anodino-dev/PyPDF2 | /tests/__init__.py | 2,055 | 3.5 | 4 | import os
import ssl
import urllib.request
from typing import List
from PyPDF2.generic import DictionaryObject, IndirectObject
def get_pdf_from_url(url: str, name: str) -> bytes:
"""
Download a PDF from a URL and return its contents.
This function makes sure the PDF is not downloaded too often.
This... |
5ee859f119fcd719d0f91458a1eb48d6d92bbda1 | algernon17/PythonProjects | /sun/sun6.py | 1,662 | 4.03125 | 4 | import math
import turtle
import time
import random
# ====================================================
# draw a circle using turtle
def drawRay(r):
# move to the start of the circle
turtle.circle(r, 60)
turtle.circle(-r, 60)
# ====================================================
# drawPattern fun... |
b79841aae5a34a77dfb697b51795a8d89e090bfc | algernon17/PythonProjects | /pattern/pattern2.py | 2,226 | 3.71875 | 4 | import math
import turtle
import tkinter
import random
#==========================================================
def patSeg(segLen, lrDir):
turtle.forward(segLen)
if lrDir == 0:
turtle.left(90)
else:
turtle.right(90)
#==========================================================
def ... |
8bde573182e2f9827290a05bc22df654591073d1 | emalonso/clase-6 | /calculadora.py | 569 | 3.671875 | 4 | class Calculadora:
def __init__(self):
self.numero = 0.0
self.entrada = 0.0
self.tip_oper = ""
def iniciar(self):
self.numero = 0.0
self.entrada = 0.0
def capturarInicial(self, valor):
self.numero = valor
def operacion(self, entrada):
if self.tip_oper == "S":
self.numero = self... |
a2680c95e277510bf6347a55401c9b512f8597de | KDes9394/week3day1assignment | /parking_garage.py | 222 | 3.5 | 4 | my_string = "This string has 10909090 numbers, but it is only 1 string. I hope you solve this 2day."
compiler = compile('[0-9]+')
found_nums = compiler.findall(my_string)
print(found_nums)
# Output: ['10909090','1',2]
|
296adfa97239f62d2b8ca61e06bf65b5b987da16 | gimoonx/ex-de-python-iniciante | /vetores/vetores2soma2.py | 339 | 3.53125 | 4 | def soma_vetores(a,b,c,t):
for i in range(t):
a.append(int(input('a: ')))
for i in range(t):
b.append(int(input('b: ')))
for i in range(0,t): #0,1,2,3,4
c[i] = a[i] + b[i]
print(c)
###################
t = int(input('Quant. elementos: '))
x = []
y = []
z = t*[0]
so... |
272d241f9bd4174d351191ab3fb6eabf60b77a36 | gimoonx/ex-de-python-iniciante | /vetores/vetores4qtdeelement.py | 382 | 3.59375 | 4 | def junta_valores(a,b,c,tam1,tam2):
for i in range(tam1):
a.append(int(input('A: ')))
for i in range(tam2):
b.append(int(input('B: ')))
c = a + b
return (tam1+tam2)
#####return guarda o valor no def########
t1 = int(input('Tamanho de A: '))
t2 = int(input('Tamanho de B... |
39b97dffae0f421b9075c37f67b01ea95ff443eb | gimoonx/ex-de-python-iniciante | /sequência/sequencia3.py | 64 | 3.671875 | 4 | n= int(input("digite um numero: "))
a=n//100
p=n-a*100
print(p) |
e195fe0ec5725f37028917f19b238f35e7390521 | gimoonx/ex-de-python-iniciante | /funções/funções10triangulo.py | 200 | 4 | 4 | def tri (a, b, c):
if (a+b<c) or (b+c<a) or (a+c<b):
return False
else:
return True
a=float(input("lado a: "))
b=float(input("lado b: "))
c=float(input("lado c: "))
print(tri (a, b, c)) |
1f6b26315242cf3a59d3f3de9d63972d6a3e9f06 | gimoonx/ex-de-python-iniciante | /exercícios aleatórios/questaoprova2.py | 104 | 3.65625 | 4 | n=int(input('n: '))
d=n%10
e=n//10
while e>9: e=e//10
if e==d: print('iguais')
else: print('desiguais') |
725e1f214ddf9dafa3a7b8447e1f4e2c15d90340 | gimoonx/ex-de-python-iniciante | /exercícios aleatórios/exercicioprofessor.py | 107 | 3.875 | 4 | while True:
x=int(input('x: '))
if x==0:
break
if x%2==0:
print('par')
else:
print('não é par') |
516ec2af45c5dbfc30b714bfa0833929425bacb4 | hemanth/p2pu | /variables/python/variables-pablox.py | 3,681 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# variables-pablox.py
#
# Copyright 2010 Pablo <pablo@glatelier.org>
#
# 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 Soft... |
a1d7e300b1c080179a67b6023d803b0cf5b3d75c | Vaibhav3M/Coding-challenges | /SortingAlgos/ShellSort.py | 508 | 3.796875 | 4 | class ShellSort(object):
def sort(self, arr):
gap = len(arr) // 2
while(gap > 0):
for j in range(gap, len(arr)):
curr = arr[j]
i = j
while(i>=gap and arr[i-gap] > curr):
arr[i] = arr[i-gap]
i = i ... |
c17f682a355a9de09ecc50d153790ba328839553 | lalitpagaria/speech-emotion-recognition | /speech_emotion_recognition/voice_recorder.py | 590 | 3.546875 | 4 | import soundfile as sf
import sounddevice as sd
from scipy.io.wavfile import write
def record_voice():
"""This function records your voice and saves the output as .wav file."""
fs = 44100 # Sample rate
seconds = 3 # Duration of recording
# sd.default.device = "Built-in Audio" # Speakers full name h... |
904577c328e8df238d365f2a6d97c4e6d8a23504 | Samuca47prog/Python_exercises_CursoEmVideo | /ex017.py | 733 | 4.25 | 4 | ##########################################################################
# Author: Samuca
#
# brief: calculate pythagoras
#
# this is a list exercise available on youtube:
# https://www.youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-
####################################################################... |
c68da22e659576ea80e797df9ba45a282975e662 | Samuca47prog/Python_exercises_CursoEmVideo | /ex032.py | 779 | 4.21875 | 4 | ##########################################################################
# Author: Samuca
#
# brief: is this a leap year?
#
# this is a list exercise available on youtube:
# https://www.youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-
#####################################################################... |
9f4d572e4a54a3f80a1cc4273b650205157b41e4 | Samuca47prog/Python_exercises_CursoEmVideo | /ex021.py | 605 | 3.703125 | 4 | ##########################################################################
# Author: Samuca
#
# brief: plays a mp3 song
#
# this is a list exercise available on youtube:
# https://www.youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-
#########################################################################... |
f85d5038e35aa2de566d6f0fe5fa6afa8ddbfe80 | BjornArnelid/corma | /timeunit.py | 226 | 3.703125 | 4 | import datetime
class TimeUnit(object):
"""Representation of a unit of time
A TimeUnit contains date and hours worked
"""
def __init__(self, date, hours):
self.date = date
self.hours = hours
|
87faa8e5d8236ceff8e13b217782ed95767bb616 | Cybernetic1/latex | /generate-NN.py | 579 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# Generate a neural network in TGF (trivial graph format)
# for use with yEd graph editor
# topology of neural network
topology = [3, 5, 7, 9]
# First, print all the nodes
for i, j in enumerate(topology):
for k in range(j):
print(chr(i + 48) + chr(k + 48))
# separator
print("#")
# Then p... |
194c5f7474bed7efbee0dc730970a3dd3e686b98 | jfdoming/real-analysis-tools | /example.py | 1,071 | 3.65625 | 4 | from atools import *
def print_info(set_to_analyze, name):
print(f"{name} = {set_to_analyze}")
print(f"closure({name}) = {set_to_analyze.cl()}")
print(f"closure({name}^c) = {set_to_analyze.co().cl()}")
print(f"int({name}) = {set_to_analyze.it()}")
print(f"int({name}^c) = {set_to_analyze.co().it()}"... |
0a01ddec377f22ad99caedd14d1c852234424b2a | toshinarin/ProjectEuler | /10/p0002.py | 263 | 3.5 | 4 | first = 1
second = 2
sum = 0
if first % 2 == 0:
sum += first
if second % 2 == 0:
sum += second
n = 0
while True:
if n > 4000000:
break;
n = first + second;
first = second
second = n
if n % 2 == 0:
sum += n
print(sum)
|
32c0efab9e8a96540765d870c9570ba8783fae7c | toshinarin/ProjectEuler | /30/p0029.py | 364 | 3.65625 | 4 | def count_terms(n):
s = set([])
for a in range(2, n + 1):
for b in range(2, n + 1):
s.add(a ** b)
#print s
return len(s)
def test():
if count_terms(5) != 15:
print count_terms(5)
return False
return True
#print "test result: " + str(test())
def solve():
... |
17ee06fc488e5a0e991d5b11c004c251b60e0b68 | JennaScript/cs-quiz-3-python | /quiz3/Question 4/main.py | 395 | 3.875 | 4 | # Quiz 3: Question 4
# Old Code:
def c(a):
b=0
for i in a:
b+=i
return b
print (c([4,5,2,-3]))
# The code above works but is not very descriptive at all in what the function is.
# New Code:
# This function will sum up integers in the list provided.
def get_sum(num_list):
sum = 0
for i ... |
d2d7ab0c445d000640bab3cb4c14b16fb63445bb | alechewitt/stanford_algorithms_analysis_course | /01_2_inversions/recursion_python.py | 1,326 | 3.765625 | 4 | # Method returns a sorted list and the number of inversions
# in that list
def countInversions(aList):
if len(aList) == 1:
return 0, aList;
halfLength = len(aList) / 2
aNumInv, listA = countInversions(aList[0:halfLength])
bNumInv, listB = countInversions(aList[halfLength:])
cNumInv = 0
listC = []
while len(... |
fca5cbe77a874c6e02a8087fbd99eb4dbbcc37ac | kerrgavin/cpscwebscraping | /csv_example.py | 920 | 3.796875 | 4 | import csv
def main():
header = ["Name", "Sex", "Age"]
user_info = []
newEntry = True
while(newEntry):
info = []
info.append(input("Enter in your name: "))
info.append(input("Enter in your sex(M or F): "))
info.append(input("Enter in your age: "))
user_inf... |
2a47cdaf7523066b6378aa194019601cb0845c8a | Allu2/Testing. | /LocData.py | 7,801 | 3.671875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Aleksi Palomäki'
import math
from datetime import datetime
class LocData:
def __init__(self, database, user):
self.db = database
self.userID = user
'''
getInCircle(radius, center_location)
This function will lookup information f... |
273f07f78c4c28a893683ae0a82a6bda4f968e46 | laorange/mooc_resource | /python基础语法课程内容/第5章 函数和代码复用/七段数码管的绘制v1.py | 995 | 3.625 | 4 | #数码管绘制1
import turtle as d
import random
def drawgap():
d.penup()
d.fd(5)
def drawline(draw): #绘制单段数码管
drawgap()
x = random.uniform(0,1)
y = random.uniform(0,0.5)
z = random.uniform(0,1)
d.pencolor(x, y, z)
d.pendown() if draw else d.penup()
d.fd(40)
drawgap()
d.right(90)
de... |
68a750d41fc247d209c1eafd7cdbc3cb274ce02a | thedrow/returns | /returns/functions.py | 1,574 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from functools import wraps
from returns.primitives.exceptions import UnwrapFailedError
from returns.result import Failure, Success
def is_successful(container):
"""
Determins if a container was successful or not.
We treat container that raise ``UnwrapFailedError`` on ``.unwrap(... |
37c75ec6120fa1c8810d8daf433a9ddff00c4310 | MSDPhoenix/bubble_sort_msd | /bubble_sort.py | 788 | 3.875 | 4 | x=[5,1,4,2,8,9,8,7,6,4,5,3,2,1]
y=[5,1,4,2,8]
def bubble_sort(bbl):
finished=0
count=0
while finished!=len(bbl)-1:
finished=0
for i in range(len(bbl)-1):
count+=1
if bbl[i]>bbl[i+1]:
bbl[i],bbl[i+1]=bbl[i+1],bbl[i]
... |
279417d3e30b1581b1dca815fe72239f94bf1ec9 | matthewrmettler/algorithms | /python/sorting.py | 6,727 | 3.765625 | 4 | '''
A collection of sorting algorithms implemented in python.
Written by Matthew Mettler.
'''
from random import randint, shuffle
'''
Insertion sort
Insertion sort is a simple sorting algorithm that builds the final sorted array
(or list) one item at a time. It is much less efficient on large lists than
more advance... |
7074b4571c5bede29ddb278542f453b835832987 | pooja2005/Design-and-Analysis-of-Algorithms | /Assignment1.py | 1,591 | 3.765625 | 4 | def sg(a):
l=a[0]
for i in range(1,5):
if(l<=a[i]):
l=a[i]
print("the largest no. is:",l)
for i in range(1,5):
if(l>=a[i]):
l=a[i]
print("the smallet no. is:",l)
def su(a):
s=0
for i in range(0,5):
s=s+a[i]
print("the sum of t... |
a902a484edb04a23ce3cde2d77f919e3c16458d9 | FoxLisk/misc | /curiousities.py | 1,011 | 3.8125 | 4 | def items_in_only_one_list(l):
'''given a list of lists (or, really, an iterable of iterables),
return every element that appears in exactly one list.
As a list, of course :)'''
return [x for sl in l for x in sl if not any(x in _sl for _sl in l if _sl != sl)]
class Summer(object):
def __init__(self... |
4ec8d3418e1a667c8f2624d5ae3586a1832aaea0 | oriveeer/Inbox | /00_Python/_old/kiso/test04.py | 397 | 3.65625 | 4 | # -*- coding: utf-8 -*-
test_str = """
test_1
test_2
"""
print test_str
#文字列の連結
test_str = 'python'
test_str += '345'
test_str += '678'
test_str += '9'
print test_str
#文字列へ変換
test_integer = 100
print str(test_integer) + '円'
#文字列の置換
test_str = 'python-izm'
print test_str.replace('izm', 'ism')
#
test_str = '... |
fa2ebe09975efddae2fe837fa4a8f7adde015bb2 | hodevin/Allegheny-College-CMPSC-comp | /comp/src/data_check.py | 1,941 | 3.9375 | 4 | """Checks user imported data."""
import pandas as pd
print(
"""Testing if the data provided by user matches
the pattern defined by data generator...\n
Please tidy your data if the test does not pass.\n"""
)
# Import data from csv.
df = pd.read_csv("./data/input_file.csv")
group_by_city = df.groupby("City")
group_... |
d2da96c8e04db518d652fcc4122f8644d823f6ad | Taurin190/py-sort | /main/merge_sort.py | 719 | 4.0625 | 4 | def merge(list1, list2):
merged_list = []
while len(list1) != 0 and len(list2) != 0:
if list1[0] < list2[0]:
merged_list.append(list1.pop(0))
else:
merged_list.append(list2.pop(0))
if len(list1) == 0:
merged_list = merged_list + list2
else:
merged_... |
f3aaa9c6013ff31978cb6f7431486d72fbdb18ec | radytrainer/demo | /friday.py | 504 | 3.8125 | 4 | left = 0
right = 0
down = 0
up = 0
isMove = True
while isMove:
action = str(input("Action: "))
if action == "l" or action == "L":
left = left - 1
if action == "r" or action == "R":
right = right + 1
if action == "u" or action == "U":
up = up + 1
if action == "d" ... |
5241779163e7fb9d10c89d2aeb6a2036ee7b879f | sherah/hb_audit | /exs/Exercise09/task7.py | 584 | 4.25 | 4 | #!/bin/env python
"""
Given the list l composed of tuples, sort the list by the second item in the tuple
l = [(1,3), (3,2), (5,1)]
becomes
l = [(5,1), (3,2), (1,3)]
"""
l = [(1,2), (3,1), (17, 35), (81,20)]
secondList = []
def flip_tuples(l):
newList = []
for t in l:
firstT = t[0]
secondT = t... |
73cc2ae9868aef2ae794459c0880e5ccd6e8b165 | sherah/hb_audit | /exs/Exercise05/lettercount.py | 898 | 3.640625 | 4 | from sys import argv
import pprint
script, filename = argv
f = open(filename)
data = f.read()
full_alphabet_count = {}
for i in data:
if i in full_alphabet_count:
full_alphabet_count[i] += 1
else:
full_alphabet_count[i] = 1
letter_count = {}
for l in full_alphabet_count:
if(ord(l) >= 65 and ord(l) <... |
4701eb25d40e79a633f57b3ac4eb9d1a394e07b2 | born2trycn/SunNing | /节日快乐.py | 1,155 | 3.703125 | 4 | import turtle
import time
a = turtle.Pen()
a.shape('turtle')
a.hideturtle()
now = time.gmtime()
print(now)
month = now.tm_mon
day = now.tm_mday
print(month)
print(day)
if (month == 9 and day == 10):
a.write('❤❤❤❤❤❤❤', font=('Arial', 20, 'normal'))
a.speed(100)
a.forward(200)
a.left(90)
a.forward(50)
a.left(90... |
288b84e71be7c97f86259a40b361bdae3bd01090 | ionufi/first | /model.py | 924 | 3.65625 | 4 | class Student(object):
def __init__(self, sid, name, surname, grade):
self._id = sid
self._name = name
self._surname = surname
self._grade = grade
def get_id(self):
return self._id
def set_id(self, sid):
self._id = sid
def get_name(self):
... |
fa71e8ea40e066ff5da1d42b75a594fd2e4de733 | AkramYamin/Binary-Tree | /TreeLevelOrderTraversalInSpiral.py | 960 | 3.9375 | 4 | class Node :
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def printInSpiral(root):
if root is None:
return
s1 = []
s2 = []
s1.append(root)
while not len(s1) == 0 or not len(s2) == 0:
while not len(s1) == 0:
node = s1.pop()
print(node.data, end = " ")
if node.r... |
d6cefd68b04863861cd3932cdc04c7b15dc41eee | bjorne/knapsack-dynamic | /hack/generate_input.py | 2,785 | 3.875 | 4 | #!/usr/bin/env python
# definite kill! double compile!
# usage>
# [~/hack/knapsack]:$> python hack/generate_input.py > input/small.txt 2> input/small.solution
import sys, random
def weight_of_solution(solution):
size = 0
for item in solution:
size += item[0]
return size
def value_of_solution(sol... |
8a8d32a4bd6b6c28b9435dc5dbadd390f590c817 | surrajjha/Practice | /coding/week_14/day_1/evaluation/count_vowels.py | 307 | 4 | 4 | n=str(input('string '))
countLower=0
countUpper=0
for i in n :
if (i == "a" or i == "e" or i == "i" or i == "o" or i == "u") :
countLower=countLower+1
elif (i=='A' or i == 'E' or i == 'I' or i == 'O' or i == 'U') :
countUpper+=1
print("lower ",countLower)
print("upper",countUpper) |
dae5d843a0b3f3269c68d84f3ff09a26ccb2a1e9 | surrajjha/Practice | /coding/week_12/day_4/session_2/union_sets.py | 105 | 3.671875 | 4 | print('Enter Set 1')
set1=set(input())
set2=set()
for i in set1 :
set2.add(i)
print(set2)
|
d45df4be1e433c4b8fcad8ccb77a757759cee60b | surrajjha/Practice | /coding/week_12/day_4/session_1/count_consonants.py | 161 | 3.65625 | 4 | n = (input("Enter string"))
count=0
for i in n :
if (i!= "a" and i != "e" and i != "i" and i != "o" and i != "u") :
count=count+1
print(count)
|
1d633417ea0264834d22dfa0bd5412cbaf2c608d | surrajjha/Practice | /coding/week_12/day_4/session_1/print_evens.py | 92 | 3.71875 | 4 | n = int(input("Enter a no "))
for i in range (0,n) :
if (i % 2 ==0) :
print(i)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.