blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d9b97b46ee60b664874596af17de6312d6de56c8 | SergioFaya/CN | /Lab/Calculator/libCalculator.py | 1,512 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 18:30:30 2017
@author: UO250973
"""
import math
def newton(f, df, x0, tol):
error = 1
iterations = 1
x = x0
while (error > tol):
Xk = x - (f(x)/df(x))
error = math.fabs(Xk-x)
x = Xk
iterations = iterations+1
return... |
513cae14dcf56dfbef197be660c21056fbe17ab3 | PlatypusK/EulerSolves | /Problem003.py | 786 | 3.734375 | 4 | '''
Created on 29. des. 2010
@author: Ketil
'''
import math
def findPrime(number):#code only gives smallest factors, not prime factors
primelist = []
i=2
while(i<number):
product=1
if number % i == 0:
primelist.append(i)
n=2
while ... |
7f59b8f9534603fe821e29355b81ab2ab8efa3e6 | Rushi21-kesh/30DayOfPython | /Day-12/Day_12_janvhi.py | 347 | 4 | 4 | n= int(input("enter numbers of elements:"))
a=[]
flag=0
for i in range(0,n):
x = int(input("enter element"))
a.append(x)
print(a)
k= int(input("enter no to be searched"))
def LinearSearch(k,a):
if k in a:
print("index found at",k, "is", a.index(k))
else:
print("element not... |
efccb0a24c4063fa1763abcb649ba580399bab97 | jedzej/tietopythontraining-basic | /students/pietrewicz_bartosz/lesson_04_unit_testing/test_collatz.py | 400 | 3.53125 | 4 | import unittest
from lesson_03_functions.the_collatz_sequence import collatz
class TestCollatzFunction(unittest.TestCase):
def test_invalid_type(self):
self.assertRaises(TypeError, collatz, 'aoeu')
def test_value_8(self):
self.assertEqual(collatz(8), 4)
def test_value_5(self):
se... |
6667787b7546bc1aca678161b7625786b4f3375d | vicely07/Deep-Learning-on-TAD-dataset | /Feature-based ML model/Dense_Layer.py | 8,302 | 3.78125 | 4 |
import numpy as np
# First, load the train data from a csv file to a numpy Array. Note that last column is assumed to be the
# class label. You will need the numpy library. We will #separate the predictors and class labels to two
# separate matrices 'x_train' and 'y_train', respectively.
Train = np.loadtxt('train_s... |
ecd1703af369c06c3da88b6a234c8c547be0ccbe | Jamshid93/TaskBook | /While/w11.py | 94 | 3.609375 | 4 | N=int(input("N="))
K=1
F=1
while F<N:
F=F+1
K=K+F
#F=K-1
#K=K+1
print("K=",K,"Sum=",F) |
3260be78534d235d965796ffaaa2abc279ca2731 | holy-pythonesque/py-homeworks-basic--7_files.task_3 | /main.py | 576 | 3.609375 | 4 | filenames = ['1.txt', '2.txt', '3.txt']
def get_lines_num(file_info):
return file_info['lines_num']
files_info = []
for filename in filenames:
with open(filename, 'r') as file:
lines = file.readlines()
files_info.append({
'name': filename,
'lines': lines,
'... |
d58c1c0618ec2f9c70ecf1d0f38db597ab4ddd90 | junteudjio/algorithms_in_python | /algorithms_in_python/_5_array_based_sequences/examples/dynamic_array.py | 1,397 | 3.515625 | 4 | import ctypes
__author__ = 'Junior Teudjio'
class DynamicArray:
def __init__(self, size=0, init_value=0):
assert size >= 0
self._init_value = init_value
self._size = size
if self._size:
self._capacity = 2 * self._size
else:
self._capacity = 1
... |
c19fdafbd81d76d7335d1f6e1cfa309ec1d130ab | shenbufan/runoob-Python-100 | /68.py | 1,096 | 3.53125 | 4 | # -*- coding:UTF-8 -*-
import datetime
n = int(raw_input('请输入数组长度:'))
m = int(raw_input('请输入移动位数:'))
list = []
def List(num):
for i in range(num):
list.append(int(raw_input('请输入第%d个数:'%(i+1))))
return list
def Move1(l,n):#Move1()是使用额外空间list_atmp存储超出长度的数
t1 = datetime.datetime.now()
length = len(l)
list_atmp = []... |
328bb00db3ff38691673cab39d6b6900858733d9 | lizetheP/PensamientoC | /programas/Laboratorios/8_Archivos/cuentaConsonantes.py | 895 | 3.71875 | 4 | def cuentaConsonantes(nombre):
file=open(nombre,"r")
cont = 0
while True:
letra = file.read(1) # Lee un caracter del archivo
if (letra.isalpha() and letra != 'a' and letra != 'e' and letra != 'i' and letra != 'o' and letra != 'u'):
cont = cont + 1
if not letra: # Si no es... |
aeb6e781cf434109b298959fe3bc82ce1106e477 | Sem-SO/stepik_autotest_projects | /Урок 2. Полезные методы Selenium/lesson2.3_step4.py | 820 | 3.578125 | 4 | import math
from selenium import webdriver
link = "http://suninjuly.github.io/alert_accept.html"
try:
browser = webdriver.Chrome()
browser.get(link)
browser.find_element_by_tag_name("button").click() #click on "journey" button
browser.switch_to.alert.accept() #accept "journey" alert
x = browser... |
3cab0776e3732fa5f0af3df331f4bb43d7a57235 | lyashevska/euler-solutions | /problem003/sol.py | 283 | 3.671875 | 4 | def factor(x):
factors = []
i = 2
while x > 1:
if x % i == 0:
x = x // i
factors.append(i)
else:
i+=1
return factors
n = 600851475143
print ('The maximum prime factor of the number %s is %s' % (n, max(factor(n))))
|
0708d8347769f3affbc786008ed982fe0ef46b8b | HackerSchool/HS_Recrutamento_Python | /Guilherme_Freitas/login.py | 2,965 | 3.671875 | 4 | from os import system
import math
from calc import *
def openfile():
key_file=open("key.txt","r")
#print(key_file.read())
return key_file
def closefile(file):
file.close()
def getInput():
user=input("<user>")# a variavel 'user' serve como controlo para as diferentes opções que podem ser ... |
b6875c44f7d5c8ddecdb5ea72092c285bd08458c | pacifastacus/gepitan-ex7 | /ex7/utils/recover_data.py | 1,228 | 3.75 | 4 | import numpy as np
def recover_data(Z, U, K):
"""
Recovers an approximation of the original data when using the
projected data
X_rec = recover_data(Z, U, K) recovers an approximation the
original data that has been reduced to K dimensions. It returns the
approximate reconstruction in X_rec.
... |
ef439ff886c5e37babbd36c8d76f62bea30af8e5 | mathieubue/rsa_encrypt | /rsa_m_buev2.py | 1,867 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 12:48:42 2021
@author: M BUE
"""
import math
def facteurs(n):
"""facteurs(n): décomposition d'un nombre entier n en facteurs premiers"""
F = []
if n==1:
return F
# recherche de tous les facteurs 2 s'il y en a
while n>=2:
... |
5d1a34082bf1e96e335d4bb68134a9a9d64d5b22 | Galakeit/Go_Python | /stepik/piramid.py | 411 | 4.0625 | 4 | import math
x_a = float(input("Введите координату X точки A "))
y_a = float(input("Введите координату Y точки A "))
x_b = float(input("Введите координату X точки B "))
y_b = float(input("Введите координату Y точки B "))
a = (x_a - x_b)**2
b = (y_a - y_b)**2
c = round(math.sqrt(a+b), 3)
print(a)
print(b)
print... |
f8116e2d180671e478ab26869e953b9763fb1737 | Weless/leetcode | /python/剑指offer/面试题04. 二维数组中的查找.py | 575 | 3.734375 | 4 | from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if not matrix: return False
i,j = 0, len(matrix[0])-1
while i < len(matrix) and j>=0:
if target > matrix[i][j]:
i+=1
elif target < matr... |
638aa0ec7c8ccfa92157fdef2e1041a506ddfae4 | RyanZhang0821/python20818 | /turtle05.py | 132 | 3.671875 | 4 | import turtle
a=turtle.Turtle()
n=int(input("Type n:"))
for i in range(n):
a.forward(100)
a.left(360/n)
|
1e971b1ffee3446e52e1844cfc82a01decb55b26 | sgarg87/sahilgarg.github.io | /code_bases/python_coding_practice/fizz_buzz.py | 426 | 3.5625 | 4 | class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
out = []
for x in range(1, n+1):
s = ''
if (x % 3) == 0:
s += 'Fizz'
if (x % 5) == 0:
s += 'Buzz'
if ... |
1fee93cb8ac3f9f4b83ffa8ac4f8930978092d89 | manuelpope/HighPerfomancePy | /hpP2/MultiThread1.py | 1,199 | 3.8125 | 4 | print('multi parallel processing python')
from threading import Thread, Lock,RLock
threadLock= Lock()
#Bad Practice-global variables
myGlobalString = "HELLO WORLD"
def addPrefix(prefixToAdd):
global myGlobalString
threadLock.acquire()
myGlobalString = prefixToAdd+" "+myGlobalString
threadLock.release()
... |
652b30ed891a0cb6ed2c9ce79ae191d452175716 | ApChaddha/madlib | /madlib.py | 464 | 3.828125 | 4 | print('Hi there! welcome to MAD LIBS')
noun = input('Enter what every student has? ')
sol = input('Enter what we can find with internet? ')
int = input('Enter what changed our lifes? ')
way = input('And in which way? ')
wit = input('Enter What is important to surf internet? ')
print('Today, every student has ' + noun ... |
24883c1d8467dd094bb0f8ebd09599c7612fd174 | karlmc15/cheaters | /lib/preprocessor.py | 1,097 | 3.75 | 4 | from lib import lexer_tools
class Preprocessor():
"""
Removes whitespace and renames all variables and functions.
Generates a map between hashes and line numbers to be used when working back from comparison results
"""
def __init__(self, source, filename):
self.line_map = self.create_line... |
7224985be0302ccc607b55d232b4fa11dcb47d69 | UWSEDS-aut17/groupby | /groupby/twitter.py | 6,110 | 3.703125 | 4 | import pandas as pd
from collections import Counter
import re
import sys
def open_tweets(fname):
"""
This function reads the twitter.csv file and returns a dataframe
Parameters:
-----------
fname : Twitter csv file
Returns:
--------
DataFrame
tweets_df : Data frame created from t... |
b49d69d0eedb85350a3058ccc06b72d9d1b964f0 | gucky92/dreye | /dreye/api/barycentric.py | 3,844 | 3.8125 | 4 | """
Module for handling barycentric coordinates and transformations.
This module provides a set of functions for handling barycentric coordinates
and performing transformations between barycentric and cartesian coordinates.
It includes functions for:
- Dimensionality reduction of a given data set X using l1-normaliz... |
d9f1b6c945fd807e9c18a1cf4d16e86eb9d8480a | Zriyaz/LAB | /Ex4/allPrograms.py | 1,614 | 4.25 | 4 | '''1. Create a two instance that belongs to the same class and create a one instance method
which is accessed by the both instance of the class'''
class Student:
Stream="MCA" #class variable
def __init__(self,name,roll): #constructor
#instance variables
self.name=name
self.roll=roll
def details(sel... |
13d44e4d306fa3ee34bec9b205768e45f8895c44 | daniel-reich/ubiquitous-fiesta | /8vBvgJMc2uQJpD6d7_9.py | 529 | 3.96875 | 4 |
def prime_factors(n):
a = [] # Prepare an empty list.
f = 2 # The first possible factor.
while n > 1: # While n still has remaining factors...
if n % f == 0: # The remainder of n divided by f might be zero.
a.append(f) # If so, it divi... |
09d197ad7a2d351c7b674a28a53f294e46a93737 | jasdestiny0/Competitive-Coding | /Leet code/Insertion Sort/solution.py | 283 | 4.125 | 4 | def insertionSort(array):
lengthOfArray=len(array)
for i in range(1,lengthOfArray,1):
if array[i-1]>array[i]:
j=i
while array[j-1]>array[j] and j>0:
array[j],array[j-1]=array[j-1],array[j]
j-=1
return array
|
cde041d0c32ed3fb4fd6d76d0b11e079f8a61d74 | ohmema/interview | /python/interviews/string/look_and_say_sequence.py | 772 | 3.96875 | 4 | """
look-and-say sequence:
1, 11, 21, 1211,111221,312211,13112221, 1113213211, ....
Write a function that takes as input an integer n and return the nth integer in the look-and-say sequence
"""
def look_and_say_sequence(k):
sequence = "1"
for _ in range(k):
new_sequence = ""
i = 0
wh... |
fb2692decc0521562452db12e5d42250133aa7ae | perkam/islands-counter | /counter/app.py | 1,468 | 3.734375 | 4 | import argparse
import os
import shutil
from pathlib import Path
from counter.map import Map
from counter.utils import count_islands
def _parse_arguments(args=None):
parser = argparse.ArgumentParser(
description="Program counting number of islands in a text file."
)
parser.add_argument("input", t... |
d7dd4ecf17409190f638e8152a6b7f788e863cd6 | youngcyberop/PythonCrashCourse | /Chapter 4 - Working With Lists/tiy_4_12_more_loops.py | 606 | 4.0625 | 4 | '''
4-12. More Loops: All versions of foods.py in this section have avoided
using for loops when printing to save space.
Choose a version of foods.py, and write two for loops to print each list of
foods.
'''
print("\n*******************************************************")
print("4-12 More Loops")
print("*************... |
600c5f0c97eab656801d641ff019476e354f915c | berkaysenkoylu/CrackingTheCodingInterview_mysolutionsWithPython | /Chapter 2/2.8.py | 244 | 3.984375 | 4 | ## Chapter 2 - 2.8) Loop Detection
import linked_list
linkedList = linked_list.LinkedList()
for i in range(1, 6):
linkedList.add(i)
linkedList.outputLastNode().set_next(linkedList.root)
print linkedList.whereLoopBegins()
|
1da24242db69a9a032083946e9e60a0152a04356 | LuisaArellano/Mision-03 | /TrapecioD.py | 777 | 3.546875 | 4 | #Luisa Fernanda Arellano Alvarado A01377974
def calcularArea(altura,baseM,basem):
AreaTrapecio = (baseM + basem)/2*altura
return AreaTrapecio
def calculaPerimetro(altura,baseM,basem):
LadosT = (((baseM - basem)/2)**2 + altura**2)** 1/2*2
PerimetroTrapecio = baseM + basem + LadosT
... |
913eea0b26c6893eb51db3e2921241feaf1c4b9b | meshula/exifotio | /jdutil.py | 9,371 | 4.25 | 4 | """
Functions for converting dates to/from JD and MJD. Assumes dates are historical
dates, including the transition from the Julian calendar to the Gregorian
calendar in 1582. No support for proleptic Gregorian/Julian calendars.
:Author: Matt Davis
:Website: http://github.com/jiffyclub
"""
import math
import datetim... |
59abeff425afa7531046a75d5f5d2b898f68188e | jdanray/leetcode | /nextLargerNodes.py | 353 | 3.640625 | 4 | # https://leetcode.com/problems/next-greater-node-in-linked-list/
class Solution:
def nextLargerNodes(self, head):
vals = []
while head:
vals.append(head.val)
head = head.next
stack = []
res = []
for i, v in enumerate(vals):
while stack and stack[-1] < v:
res[stack.pop()] = v
stack.append(i... |
c8fe6154e855abdb7ec6d4a2b07c4584f64dc591 | LuizFernandoS/PythonCursoIntensivo | /Capitulo05_InstrucoesIF/05_01TestesCondicionais.py | 761 | 4.1875 | 4 | #Pg.123 >>> 5.1 – Testes condicionais: Escreva uma série de testes condicionais.
#Exiba uma frase que descreva o teste e o resultado previsto para cada um.
#Seu código deverá ser semelhante a: car = 'subaru' print("Is car =='subaru'? I predict True.") print(car == 'subaru')
#print("\nIs car == 'audi'? I predict F... |
1ebe544508adef7e814bf29b61fcc10aaabddf47 | vigneshbharathi68/learning_port | /python/september_training/21-09-2020_Task.py | 2,042 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
# Source:
# https://pynative.com/python-basic-exercise-for-beginners/
# In[4]:
# Started this at 10:00 AM and ends in 10:43AM...
# Question 3: Given a string, display only those characters which are present at an even index number.
# For example str = "pynative" so... |
918b8d0e3ee146a6b8c503d99fdae908ac394e56 | chasepatten/Bank-Login-System | /Main.py | 2,088 | 4.0625 | 4 | import hashlib # imports hashlib library to hash our passwords input by user
import json # imports the library needed to manipulate JSON files
import add_user
# Function used to determine if the username and password provided are correct
def is_valid_credentials(username, password):
# opens the json file
... |
cf5ce547788a861f80b74b80a35fd8a4b82fb927 | ENGR102Review/Solutions | /Algorithms/11.py | 1,163 | 4.3125 | 4 | # a list to sort
my_list = [56, 71, 74, 75, 61, 55, 53, 90, 96, 88, 59, 64, 67, 62, 77, 70, 89, 60, 57, 87]
print('Original list:')
print(my_list)
# this list will eventually hold all of the numbers in order.
# it contains one very large number as a "starter" for this algorithm
my_list_sorted = [9e99]
### fake bubb... |
c7af95642510423c8e65dce3f38e72ac20d49c79 | arsho/leetcode | /solutions/342_Power_of_Four/solution_arsho.py | 730 | 3.625 | 4 | """
Title : 342. Power of Four
Category : Bit Manipulation
URL : https://leetcode.com/problems/power-of-four/
Author : arsho
Created : 05 August 2020
"""
class Solution:
def isPowerOfFour(self, num: int) -> bool:
""" Returns if a given number is a power of four.
Arguments:
... |
b3660ae66e03294d6e5e3fb6e5fc0a90ff4958ef | Sivapriyak56/program | /digitalclock.py | 296 | 3.78125 | 4 | import time
from tkinter import *
top = Tk()
top.title("DIGITAL CLOCK")
def digital():
dtime = time.strftime('%H:%M:%S')
clock.config(text = dtime)
clock.after(100,digital)
clock = Label(top,font=("time",100,"bold"),bg="green")
clock.grid()
digital()
top.mainloop() |
6cb471c82c7b70760c9347f8b2e99bae974087d9 | sangjianshun/Master-School | /python_high_level/chapter05/slice_object.py | 1,264 | 3.96875 | 4 | import numbers
class Group():
def __init__(self, group_name,company_name,staffs):
self.group_name = group_name
self.company_name = company_name
self.staffs = staffs
def __reversed__(self):
return self.staffs.reverse()
def __getitem__(self, item): #实现切片的关键,没有的话会报错TypeError:... |
a16e118da0021cca122b42e2d587799b9ca3c2f0 | shukhrat121995/coding-interview-preparation | /tree/path_sum.py | 1,598 | 4.03125 | 4 | """
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf
path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Input: root = [1,2,... |
6590ec34265be88425705f84829ab6ae603fb69e | janvozar/engeto_codebrew_hackathon_2019 | /echo.py | 471 | 4 | 4 | #example_sentece = ('I do not want to work today')
repeat = int(input('Please enter the number of repetitions: '))
core = input('Please enter your sentence: ')
dare = core.split()
echo = []
space_between_words = ' '
def echolocation(repet, dare, echo):
for i in dare:
string_creation = (i + ' ') * repeat
... |
c403a8c7bf33612796f9601326677f2f6806f1a3 | arvidarvidarvid/adventofcode | /2016/day01/1.py | 2,347 | 3.75 | 4 | from copy import deepcopy
START_DIRECTION = 'N'
def get_instructions():
with open('1.txt', 'r') as input:
instructions = input.read().split(',')
return instructions
def get_new_direction(current_direction, turn_direction):
turns = {
'N': {
'R': 'E',
'L': 'W'},
... |
477a20946819f399340f64e1a4d875a101046aca | jiwonjulietyoon/Algorithm | /past_work/SWTestPrep/Ad/2651_carRace.py | 3,038 | 3.53125 | 4 |
# unfinished
""" 자동차경주대회
- 정비소에서 정비하는 데에 걸리는 시간들의 합을 가장 적게
- backtracking and pruning?
"""
import sys
sys.stdin = open('../Input/2651.txt', 'r')
def backtrack(c, Sum, route): # c: current position , Sum: time spent so far, st: stops stopped by
global Min, stops, N, dis, time
if ... |
dd68575fcb73cc7b7be9a5282707a95f8b459230 | samikshasadana/python_codes | /31july.py | 2,160 | 3.546875 | 4 | '''n=int(input("enter no. of elements"))
a=[]
for i in range(n):
e=int(input("enter element"))
a.append(e)
a.sort()
a.reverse()
l=len(a)
for i in range(l):
if a[i]>a[i+1]:
print("second largest: ",a[i+1])
break;
n1=int(input("enter n1 capacity"))
n2=int(input(... |
25c4a0dc0b28662a4b4d918c699c691dcb4760ce | sharleneimperial/intro_to_python | /dictionary.py | 398 | 4.21875 | 4 | #making an empty dictionary
Dict = {}
print(Dict)
#adding elements one at a time
Dict[0] = 'Good Morning'
Dict[2] = 'Sharlene'
Dict[3] = 69
print(Dict)
#adding value set
Dict['Value_set'] = 8, 7, 3
print(Dict)
#updating keys value
Dict[2] = 'Software Engineer'
print(Dict)
#nesting key value to dictionary
seven =... |
61c4b4e9c08d25207c67e2eb8fe4650db15fc11d | mh-rahman/Programming-Practice | /58. Length of Last Word.py | 267 | 3.5 | 4 | class Solution:
def lengthOfLastWord(self, s: str) -> int:
s = s.split(' ')
# print(s)
for i in range(len(s)-1,-1,-1):
# print(s[i])
if len(s[i])>0:
return len(s[i])
return 0
return 0 |
3840b9d9e6d00823b353d877c014f7ca7e60e2e6 | mlassoff/PFAB_2_2014 | /list2.python | 478 | 3.84375 | 4 | #!/usr/bin/python
bands = [ "REO Speedwagon" ,
"Foreigner" ,
"Styx" ,
"Journey" ,
"Imagine Dragons" ,
"The National" ,
"Heart" ,
"Scandal" ];
#Reversing the order
#bands.reverse()
#print bands
#bands.sort()
#print ban... |
49a8d12062f5b78b12c1002ebba560d408218cf0 | harinath1314/6033_CSPP1 | /m6/p3/digit_product.py | 360 | 4.1875 | 4 | '''
Given a number int_input, find the product of all the digits
example:
input: 123
output: 6
'''
def main():
'''
Read any number from the input, store it in variable int_input.
'''
ans = 0
num_ = int(input())
while num_ != 0:
ans *= num_ % 10
num_ = num_ // 10
print(ans... |
a010eca9e75eff5c65bb7f3fa9426012bf4308bf | dba-base/python-homework | /Day06/school class.py | 1,614 | 4.03125 | 4 |
class SchoolMember(object):
member = 0
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
self.enroll()
def enroll(self):
'''注册'''
print("just enrolled a new school member [%s]" % self.name)
SchoolMember.member += 1
... |
a04f2c4aa52c119292f05c46f47778eac4573bb3 | karinaadcock/my-isc-work | /pythonwork/forward_backward.py | 261 | 4.34375 | 4 | forward = []
backward = []
values = ["a", "b", "c"]
for item in values:
forward.append(item)
backward.insert(0, item)
print "Forward is:", forward
print "Backward is:", backward
print forward.reverse()
forward = forward[::-1]
print forward == backward |
c286c088f9d05e30c620cf11ea48d2f7fb0d38af | syedahmedullah14/Python-programming-examples | /List_programs/clear_list.py | 221 | 3.984375 | 4 | # Q Different ways to clear a list in Python
#Method 1: using pop()
list1=[1,2,3,4,5]
for i in range(len(list1)):
list1.pop()
print(list1)
# Method 2: using clear() method
list1=[1,2,3,4,5]
list1.clear()
print(list1) |
46e464faecc91f59316084c5fa69bb08b1ee3802 | penguuu/python-examples | /operators/example12_logic_operators.py | 654 | 4.125 | 4 | #!/usr/bin/python
a = 10
b = 20
c = 0
if (a and b):
print "Line 1 - a and b are true"
else:
print "Line 1 - Either a is not true or b is not true"
if (a or b):
print "Line 2 - Either a is true or b is true or both are true"
else:
print "Line 2 - Neither a is true nor b is true"
a = 0
if (a and b):
print "Line ... |
785796388c5fef0bb0608483dd0eac94d07fb121 | michymochy/mypythonstuff | /return.py | 291 | 3.515625 | 4 | ##def string(something):
## return something[0]
##def product(nums):
## multiply = 1
## for x in nums:
## multiply *= x
## return (multiply)
##def string(x):
## x+="!"
## return(x)
##def exclaim(x)
## x=
from math import*
x=90
maff =radians(x)
print(maff)
|
f9035d2c6118c118c91d63b4fac4cca9f63ebf3d | t-tsekov/codefights-solutions | /interview/textJustification.py | 1,064 | 3.53125 | 4 | def textJustification(words, L):
begin, end = 0, 0
result = []
while True:
wordsLen = 0
while end < len(words):
if wordsLen + len(words[end]) + (end - begin) <= L:
wordsLen += len(words[end])
end += 1
else:
break
... |
52914914ec1a5da7f43ed09ba2548b28351a486d | dalanmiller/uw_python | /winter_2012/recho_client.py | 1,272 | 3.609375 | 4 | """
echo client, usage:
python echo_client.py <host> <port>
Both host and port are optional, defaults: localhost 50000
host must be present if you want to provide port
"""
import socket
import sys
import select
import datetime
host = 'localhost'
port = 50000
size = 1024
nargs = len(sys.argv)
if nargs > 1:
... |
2cbdf199a6ada0ab939d56af5c0b114e682e1eaa | KeerthikaElumalai/Program | /product.py | 111 | 3.609375 | 4 | n = int(input())
l= str(n)
ls= list(l)
product = 1
for i in l:
product = product * int(i)
print (product)
|
d34bbf52502a9455b39f0097922a25c2c1d7eb94 | jagadeshwarrao/programming | /reversedigits.py | 123 | 3.65625 | 4 | def solve(num):
# write your program from here
s=num%10
num=num/10
d=s*10+num
return int(d) |
ad2b030e0ec6f71a645f4f89c624724c56cb5c5a | iandioch/solutions | /advent_of_code/2019/04/part1.py | 364 | 3.6875 | 4 | def valid(num):
num_str = str(num)
double = False
for i in range(len(num_str)-1):
double = double or (num_str[i] == num_str[i+1])
if ord(num_str[i]) > ord(num_str[i+1]):
return False
return double
def main():
lo, hi = map(int, input().split('-'))
print(sum(1 for num... |
f53ee1508c5fe1f6ccaacc82bffa2b35f71986c6 | OleksandrNikitenko/CodeFights-Intro | /Land of Logic/sudoku.py | 1,641 | 4.28125 | 4 | """
Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with digits so that each column,
each row, and each of the nine 3 × 3 sub-grids that compose the grid contains all of the digits from 1 to 9.
This algorithm should check if the given grid of numbers represents a correct solution to Sudoku.... |
7045cf3c843d6d808c8cab928eb0ed96237788f7 | lgtateos/gis540 | /example_scripts/convertLat3.py | 1,321 | 3.953125 | 4 | # convertLat3.py
# Purpose: Read a file containing latitudes and convert from
# decimal-minute-second format to decimal degrees.
# Usage: csv_file_with_latitude_in_second_column
# Example: C:/gispy/scratch/lats2.csv
import sys
# Get the file path from the user.
theFilePath = sys.argv[1]
# Open the... |
8403edaa6761ca9e49099dd5ceb80cb790c6c75c | alhamzah/Project-Euler | /p026.py | 1,316 | 3.609375 | 4 | def ESieve(N):
l = [True for i in range(N)]
l[0]=l[1]=False
for p, isprime in enumerate(l):
if isprime:
for i in range(p*p, N, p):
l[i] = False
return [p for p, isprime in enumerate(l) if isprime]
N = 10**3
primes = ESieve(N)
def factor(n):
factors = []
whi... |
087ff56bc467752a266fc1b0659814edc994703b | LottaR17/Instagram-Bot | /tags.py | 394 | 3.5 | 4 | import re
def Gettags(textfile):
with open(textfile) as file:
new_list = set([])
for line in file:
line.strip()
print line
temp_list = re.split(r'\W+',line)
for i in temp_list:
if i not in new_list:
new_list.add(i)
... |
d99ac101475985ba1d17e0003fd12bfa385d3bc6 | husanpy/Programming-in-python-Coursera-MIPT | /2 OOP Patterns Python/Homework/4 Patterns/chain_of_responsibility.py | 3,316 | 3.53125 | 4 | class SomeObject:
def __init__(self, integer_field=0, float_field=0.0, string_field=""):
self.integer_field = integer_field
self.float_field = float_field
self.string_field = string_field
class EventGet:
"""
EventGet(<type>) создаёт событие получения данных соответствующего типа
... |
eaa3f9476f2e3983a4bfbdd798c3effeaf4d234b | mathvolcano/leetcode | /0513_findBottomLeftValue.py | 1,250 | 3.859375 | 4 | """
513. Find Bottom Left Tree Value
https://leetcode.com/problems/find-bottom-left-tree-value/
"""
# 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 fin... |
701e2a8b53f070bf71e03e139f96fcf3975561df | abbybernhardt/Bernhardt-MATH361B | /NumberTheory/N1_Collatz_Bernhardt.py | 718 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 11:59:24 2019
@author: abigailbernhardt
"""
#%%
Orgin = 8
CollNum = Orgin #number you change
CollSeq = [CollNum]
Lim = 10000
Runs = 2
for ii in range (0, Lim-1):
if CollNum % 2 ==0:
CollNum = CollNum/2
else:
CollNum =... |
453cf0bf51ccbf722c7a80b84b5182316b677f1e | darek526/ProgramyPython | /Strefa_kursow/krotki.py | 1,941 | 3.84375 | 4 | """
Bardzo podobna do listy ale bez mozliwości edycji
"""
krotka = (1,2,35,"kot", False, "duży kot")
#wyswietlenie krotki
print(krotka)
#(1, 2, 35, 'kot', False, 'duży kot')
#iteracja krotki po elementach
for i in krotka:
print(i)
"""
1
2
35
kot
False
duży kot
"""
#utworzenie krotki z fragmentu innej krotki
nowa ... |
945816caaa39a0af8d493d4b76834cc167884553 | chenxu0602/LeetCode | /913.cat-and-mouse.py | 4,153 | 3.640625 | 4 | #
# @lc app=leetcode id=913 lang=python3
#
# [913] Cat and Mouse
#
# https://leetcode.com/problems/cat-and-mouse/description/
#
# algorithms
# Hard (29.06%)
# Likes: 210
# Dislikes: 48
# Total Accepted: 5.3K
# Total Submissions: 17.9K
# Testcase Example: '[[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]'
#
# A game on ... |
db05db30026ef6323bc608ec65c0eba7f3f0d9bb | mikeschneider1977/mikeschneider-python | /Unit1/Unit1.py | 201 | 3.71875 | 4 | print('i love python')
myName = input()
print("my name is " + myName)
print(5 + 5)
print(5 * 5)
print(12 / 5)
print(12 % 5)
myNumber1 = input()
myNumber2 = input()
print(myNumber1 + myNumber2)
|
8c84dd8859d2dffc2fd2cdecb1feb7ab593e067a | micado-scale/ansible-micado | /playbook/project/roles/micado_master/start/files/terraform/utils.py | 339 | 3.59375 | 4 | #!/usr/bin/env python3
import json
def load_json(path):
""" Load the dictionary from a json file """
with open(path, "r") as file:
data = json.load(file)
return data
def dump_json(data, path):
""" Dump the dictionary to a json file """
with open(path, "w") as file:
json.dump(da... |
ddbfd5c0cca9c7d59287a5783ce3f5e846daf570 | yamonc/bigData_course | /base_python/0127/listComprehensions.py | 1,070 | 3.734375 | 4 | # 列表解析:根据已有列表,高效创建新列表的方式。
# 列表解析是Python迭代机制的一种应用,它常用于实现创建新的列表,因此用在[]中。
# 语法:
# [expression for iter_val in iterable]
# [expression for iter_val in iterable if cond_expr]
# 1. 要求:列出1-10所有的数字之和的平方
# 1. 直接的方法:
l = []
for i in range(1, 11):
l.append(i ** 2)
print(l)
# 2. 使用列表解析
l = [i ** 2 for i in range(1, 11)]... |
3afeb83b639e389cf6cf260464b2cd5296aab69f | TheAlgorithms/Python | /strings/dna.py | 555 | 3.734375 | 4 | import re
def dna(dna: str) -> str:
"""
https://en.wikipedia.org/wiki/DNA
Returns the second side of a DNA strand
>>> dna("GCTA")
'CGAT'
>>> dna("ATGC")
'TACG'
>>> dna("CTGA")
'GACT'
>>> dna("GFGG")
Traceback (most recent call last):
...
ValueError: Invalid Str... |
83c0de3f55ef2ea1569946c79741a4c4051b362b | arapujo/exercicios_python | /pyhton_para_zumbis/lista4/exercicio_4.py | 1,445 | 4.1875 | 4 | ''' Seja o statement sobre diversida de: “ The Python Software Foundation and the global Python community welcome and encourage participation by everyone. Our community is based on
mutual respect, tolerance, and encouragement, and we are working to help each other live up to these principles. We want our community to b... |
4c597c3cf4166d9b90d6f788063ef2313c3839db | broepke/GTx | /part_3/4.2.10_steps.py | 1,121 | 4.375 | 4 | # Now, let's improve our steps() function to take one parameter
# that represents the number of 'steps' to print. It should
# then return a string that, when printed, shows output like
# the following:
#
# print(steps(3))
# 111
# 222
# 333
#
# print(steps(6))
# 111
# 222
# 333
# 444
# 555
# 666
#
# Specifica... |
903651fd9474b4589bae4d1925c13aeceb01560a | lsironic/MITx_6.001 | /ProblemSet2_Problem1.py | 288 | 3.6875 | 4 | balance = 484
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
for i in range(1,13):
minimumMonthlyPayment = balance * monthlyPaymentRate
balance = (balance - minimumMonthlyPayment) * (1+annualInterestRate/12)
print("Remaining balance:", round(balance, 2))
|
123a39fd94e5c8c056687eb7fab2e3d77eb6977b | CircularWorld/Python_exercise | /month_01/teacher/day08/demo06.py | 470 | 4.25 | 4 | """
函数内存分布
1. 传入可变对象
2. 修改可变对象
3. 函数外可以得到结果(不用return)
练习:exercise10
"""
# 将函数的代码存储到代码区中
def func01(p1, p2):
p1[0] = 100
p2 = 200
list01 = [10]
list02 = [20]
# 调用函数在内存中开辟一块空间(栈帧),
# 用于存储在函数中创建的变量
func01(list01, list02)
# 函数执行后栈帧释放
print(list01[0]) # 100
print(list02[0]) # ?
|
69a1e263e2372ba70575d65a8ad84e23d871b094 | standrewscollege2018/2021-year-11-classwork-NekoBrewer | /Prices for different ages.py | 318 | 4.21875 | 4 | #Asks for your age and then evaluates whether you're old enough to be considered an adult or if you're considered a child.
Child_Age = int(input("Enter you age?"))
#if you are 13 or younger you get to pay the child price
if Child_Age <= 13:
print("You are", Child_Age, "please pay $10")
print("Welcome to the Zoo") |
adf1ff716765ed73fac0b4237c2a66379f2b5d1f | wfslithtaivs/InterviewPrepTasks | /patternmatch.py | 2,854 | 4.5625 | 5 | """Check if pattern matches.
Given a "pattern string" starting with "a" and including only "a" and "b"
characters, check to see if a provided string matches that pattern.
For example, the pattern "aaba" matches the string "foofoogofoo" but not
"foofoofoodog".
Patterns can only contain a and b and must start with a:
... |
67cdbe3e5bb054cc7a4cd223ddfd14a18a77d7ef | AlanHorowitz/SpringBoard | /python-misc-exercises/fair_lawn_covid.py | 2,187 | 3.53125 | 4 | from bs4 import BeautifulSoup
import requests
def print_fl_covid_info():
'''
Read the www.fairlawn.org website for current active covid counts.
Prints:
Current Active Cases:
Last Update date:
or
Error message if not able to parse the website
'''
fl_url = 'https://www.fai... |
ef0b0bac4ed56b88075ce335b9c143ab53831470 | sjogleka/General_codes | /evenOddOperations.py | 663 | 3.609375 | 4 | def getMaximumscore(integerArray,start,end, operation, sum1,score):
if sum1 ==0:
return score
if operation%2 ==0:
score -=sum1
else:
score +=sum1
score1 = getMaximumscore(integerArray,start+1,end,operation+1,sum1-integerArray[start],score)
score2 = getMaximumscore(integerArra... |
0e162f51716ab3223e575aa257af0cddd51f345c | Androw96/Raspberry-Communication | /send.py | 1,175 | 3.59375 | 4 | #Sending
import socket
global floor, row, in_out
def read_file():
global floor
global row
global in_out
count_while = 1
count = 1
input = "input.txt"
# File reading
while(count_while < 3):
file1 = open(input, 'r')
if(file1 == 0):
print("Nem tudtam megnyitni a fi... |
74079ae8c0d3dc7afab55940e731fba7227c4de0 | jH0ward/SparkCourse | /df/wordCount_df.py | 749 | 3.9375 | 4 | from pyspark.sql import SparkSession
from pyspark.sql import functions as F
spark = SparkSession.builder.appName("WordCount").getOrCreate()
# Read text file into a one-column dataframe
inputDF = spark.read.text('../data/Book.txt')
inputDF.show()
# Split text by word and put into new dataframe with col named "word"
w... |
a3d129266ae3e0fc6363445cb41e19f1a179c199 | MurilloFagundesAS/Exercicios-Resolvidos-Curso-em-Video | /Ex083-Parenteses.py | 690 | 3.578125 | 4 | lista = []
exp = str(input('Digite uma Expressão: '))
parenteses1 = 0
parenteses2 = 0
for simb in exp:
if simb == '(':
parenteses1 += 1
elif simb == ')':
parenteses2 +=1
if parenteses1 == parenteses2:
print('A expressão é válida!')
else:
print('A expressão é inválida')
'''
lista = []
x... |
b4da37e1ae2af7936f70cc67360067b0d0a22c2e | frumiousbandersnatch/sdsurvey | /sdsurvey/meta.py | 190 | 3.546875 | 4 | #!/usr/bin/env python
import csv
import sys
csvdata = csv.reader(open(sys.argv[1]))
first = csvdata.next()
for count, heading in enumerate(first):
print ('%3d: %s' % (count,heading))
|
179267b2ff0656248aeab3e29c010f123d8b2dfd | JoeDBNS/programming-practice | /Tutoring/Jake/workspace.py | 1,502 | 4.03125 | 4 | import random
# txt = "Hello, welcome to my world. welcome"
# search_find = txt.find("wel", 10, 35)
# search_index = txt.index("wel")
# print(search_find)
# print(search_index)
string_list = ['this', 'is', 'An', 'array', 'Of', 'is', 'an', 'strings', 'stinky']
starting_string = 'this is A string Of stinky'
pra... |
ea0e4a96e23593a348c6bd2427b153b657c7f072 | daviddiezpuntocero/coursera | /6.00.2x_IntroductionToComputationalThinkingAndDataScience/ProblemSet4/ps4.py | 2,382 | 3.671875 | 4 | # 6.00.2x Problem Set 4
import numpy
import random
import pylab
from ps3b import *
#
# PROBLEM 1
#
def simulationDelayedTreatment(numTrials):
"""Runs simulations and make histograms for problem 1.
Runs numTrials simulations to show the relationship between delayed
treatment and patient outcome us... |
13fa2c1f63274e8f73e4b6bdcf9904904504d22b | mr-zhouzhouzhou/LeetCodePython | /剑指 offer/链表/反转链表.py | 869 | 3.984375 | 4 |
"""
题目描述
输入一个链表,反转链表后,输出新链表的表头。
"""
#-*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if pHead is None:
return None
head = pHead
pHead = pHead.next
... |
dd47c8b14031c639a71fdb9b5acb6ec51d7b333e | DSCNIE/Hacktoberfest-GDSC-NIE-2021 | /singhshivansh/leetCode/11-Container-With-Most-Water.py | 836 | 3.5625 | 4 | # Author: @Iresharma
# https://leetcode.com/problems/container-with-most-water/submissions/
'''
Runtime: 648 ms, faster than 92.81% of Python3 online submissions for Container With Most Water.
Memory Usage: 27.8 MB, less than 11.09% of Python3 online submissions for Container With Most Water.
'''
class Solution:
... |
e7df99793ecacc041a27a656d490632fd1190859 | subhendusethi/daily-coding-problem | /day_17/solution_day_17.py | 2,262 | 3.703125 | 4 | FILE_TYPE = "file"
DIR_TYPE = "dir"
'''
Space Complexity: O(MAX_LEVEL)
Time Complexity: O(N)
Test solution at: https://leetcode.com/problems/longest-absolute-file-path
'''
class Token:
def __init__(self, string:str, level:int, ttype:str):
self.string = string
self.level = level
self.ttype = ttype
def __str... |
e1ff6c2bf622155564dde2f6fd2e4bc4127c2d33 | Palash51/Python-Programs | /coding-interview-que/two_repeated_ele.py | 550 | 3.546875 | 4 | '''
def tworep(A):
#new = []
for i in range(0,len(A)):
for j in range(i+1,len(A)):
if A[i] == A[j]:
#new.append(A[i])
print A[i]
#j += 1
#print new
A = [3,5,7,4,3,1,5]
#A = [4,2,4,5,2,3,1]
tworep(A)
'''
def twoHash(A):
table = {}
for element in A:
if element in table and ... |
3175cc30214718774cee0cad401b151917fd4c05 | ZiDuNet/PythonTest | /爬虫/数据提取和分类.py | 1,598 | 3.84375 | 4 | # 数据提取概念和数据的分类
# 使用 json 模块提取数据
# 使用正则表达式提取数据
# 使用 xpath 提取数据
# 使用 beautifulsoup 提取数据
# json、csv 数据转换
#######如果是json或XML结构化数据通过 json 模块等直接转成 Python 数据类型
#######如果是html、word等非结构化数据,通过正则表达式 、 xpath 、beautifulsoup 等模块提取数据
# 导入模块
import json
# json.loads json字符串 转 Python数据类型
json_string = '''
{
"name": "crise",
... |
a4d7744afdbae9a933eb2c1bb0c3a946fafe0132 | dovu93/PyRamen_Data_Analysis | /run_financial_analysis.py | 2,355 | 3.875 | 4 | import csv
months = []
profit = []
monthly_change = []
count = 0
end_profit = 0
random = 0
greatest_increase = 0
greatest_decrease = 0
starting_profit = 0
with open("Data/budget_data.csv", "r") as csv_file:
df = csv.reader(csv_file)
next(df)
for row in df:
count = count + 1
... |
ef916d4221ad69300ff08a19825fb22b28e3e409 | JaeZheng/jianzhi_offer | /40.py | 1,467 | 3.5625 | 4 | """
题目描述:
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
解决思路:
第一种:放入字典,再检索字典
第二种:先排序,再比较当前值与前后值是否相等,如果都不相等,则只出现一次。注意边界。
"""
# -*- coding:utf-8 -*-
# 第一种
# class Solution:
# # 返回[a,b] 其中ab是出现一次的两个数字
# def FindNumsAppearOnce(self, array):
# number_set = set(array)
# number_dict = {}
# fo... |
9e1881bb1959ff5f1fb72b008c6f50681278afb6 | Kritika997/python-practice-question | /sumofdictionary.py | 194 | 3.53125 | 4 | my_dict = {
'data1':100,
'data2': -54,
'data3': 247
}
sum = 0
value = list(my_dict.values())
for i in range (len(value)):
sum+=value[i]
print(sum)
|
96ef156d46702763fe8e1ddca035c214f2f88879 | andrealmar/algorithm-practice | /interview_cake/stock-price.py | 495 | 3.765625 | 4 | def stock_prices_everyday(price_list):
maior_preco = 0
menor_preco = price_list[0]
for price in price_list:
if price > maior_preco:
maior_preco = price
if price < menor_preco:
menor_preco = price
print maior_preco, menor_preco
return maior_preco - menor_preco
... |
b691e015753bdf6d520293e25582138bf33dfbb5 | memonsbayu/phyton | /dulu/member.py | 1,719 | 3.578125 | 4 | import mysql.connector
import connect
db=connect.koneksi()
#menambahkan data baru ke dalam table member
def add(data):
cursor=db.cursor()
sql="""INSERT INTO member(nama,alamat)VALUES(%s,%s)"""
cursor.execute(sql,data)
db.commit()
print('{}Data member berhasil ditambhkan!'.format(cursor.rowcount))
... |
16e6db539a6c95acd0fff39f67904e190dce8e2b | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/3960/codes/1734_2504.py | 462 | 3.765625 | 4 | virus = int(input("Quantidade inicial de copias do virus: "))
leucocitos = int(input("Quantidade inicial de leucocitos: "))
percVirus = float(input("Percentual de multiplicacao diaria do virus: "))
percLeucocitos = float(input("Percentual de multiplicacao diaria dos leucocitos: "))
dias = 0
while(leucocitos <= (virus... |
ff47001e8febdc4c770a8d8ce9f4d6dde6808bb1 | anushree71199/CourseProject | /Use of Python to access web data Projects from week 2/Assignment5.py | 1,508 | 4.21875 | 4 | """
Extracting Data from XML
In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geoxml.py. The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data, compute the sum of the numbers in ... |
3a0f000e140873b795bcb6165cdef834368b6ec6 | apu1995/appucodes | /balancedTree.py | 533 | 3.78125 | 4 | class Node:
def __init__(self,val,right=None,left=None):
self.val=val
self.left=left
self.right=right
def balanced(root):
if root==None:
return 0
left=balanced(root.left)
right=balanced(root.right)
if left==-1 or right==-1:
return -1
if abs(left-right)>1:
return -1
if right>left:
return right+1
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.