blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1a2d42875f4e6f7c6bada4a94f8d43063e5ad867 | kevintomas1995/die_zeit_churn_prediction | /functions_data_handling.py | 12,475 | 3.953125 | 4 | # importing required library
import pandas as pd
# Function for collinear features finding
def remove_collinear_features(df, threshold):
'''
Objective:
Remove collinear features in a dataframe with a correlation coefficient
greater than the threshold. Removing collinear features can help a mod... |
1cf102ba65691ab7052e10c95b24db766096a349 | mickey0524/leetcode | /297.Serialize-and-Deserialize-Binary-Tree.py | 1,833 | 3.8125 | 4 | # https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
#
# algorithms
# Hard (39.96%)
# Total Accepted: 169,471
# Total Submissions: 424,062
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = Non... |
617bc417e110cac1852682835c4647a2f831fb47 | dhanraj404/ADA_1BM18CS027 | /factorial.py | 258 | 3.9375 | 4 | # Finding factorial of a given number
import time
start = time.process_time()
def factorial(N):
if N == 0 or N == 1:
return 1
return N*factorial(N-1)
print(factorial(int(input("Enter Any +ve integer :"))))
print(str(time.process_time()-start)+'s')
|
77de5a1d47f4bcc0983753ffb9e4337f19bdaff6 | wikun/code-learn-gitrepo | /python/helloworld/list2.py | 461 | 3.9375 | 4 | magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
print(f"{magician.title()},that was a great trick")
for value in range(1,5):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
squares = []
for value in ran... |
405bec21ab5e5dbaac5842688ecd9232b8ce456b | VineetKhatwal/Python | /DataStructure/BinaryTree/Traversal_inOrder.py | 648 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.data = data;
self.right = None;
self.left = None;
def inOrder(root):
if root is None:
return
stack = []
curr = root;
while(curr is not None or len(stack) > 0):
while(curr is not None):
stack.append... |
2f1c81193843e78927a5175cb15aca36436f218d | Ilade-s/Sorting-Algorithms | /TriFusion.py | 1,537 | 3.625 | 4 | """
Second sorting algorithm
Principle : https://fr.wikipedia.org/wiki/Tri_fusion
"""
from time import perf_counter_ns # mesure du temps d'exécution
def TriFusion(l):
"""
Implementation of the "tri fusion" algorithm
"""
n = len(l)
if n<=1: # Si vide ou un seul éléments, alors déjà trié
ret... |
edc306f5f111a61b2659f3e451afae4e783b6514 | nosrefeg/Python3 | /mundo1/exercicios/033.py | 356 | 4.0625 | 4 | n1 = int(input('Digite um número: '))
n2 = int(input('Digite um número: '))
n3 = int(input('Digite um número: '))
menor = n1
maior = n2
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
if n2 > n1 and n2 > n3:
maior = n2
if n3 > n1 and n3 > n2:
maior = n3
print('{} é o menor e {} é o... |
02c9bc6c4c275823b0bd730911b00cc7a218abd1 | JPWS2013/SoftwareDesign | /chap12/ex12-3.py | 567 | 3.984375 | 4 | def most_frequent(s):
letters=dict()
reversedHistogram=[]
finalresult=[]
for c in s:
letters[c]=letters.get(c, 0) + 1
for letter, frequency in letters.items():
reversedHistogram.append((frequency, letter))
reversedHistogram.sort(reverse=True)
for frequency, letter in reversedHistogram:
finalresult.appe... |
c2a21498d864dc24068b4a8ccc6703eb6955fa3a | NathanaelV/CeV-Python | /Aulas Mundo 2/aula13_estrutura_de_repetição_for.py | 905 | 4.09375 | 4 | # Challenge 46 - 56
# Funciona bem quando sei até onde eu quero ir.
# Estrutura de repetição com variável de controle
for a in range(0, 6): # Repetirá 5 vezes. Conta o 1 mas não conta o 6
print('Hello') # Ele para no 6
print(a)
print('Fim')
for a in range(6, 0, -1): # Sem o -1 não funciona. O 3º diz a d... |
02fa0cb403a1c1e9fac441718d8a8615d5d6654d | sutulovat2611/Algorithms-and-Data-Structures | /Tries and Trees/DNA_fragments.py | 6,745 | 4.0625 | 4 | """
__author__ = "Tatiana Sutulova"
date: 7/5/2021
"""
class Node:
"""A node in the trie structure"""
def __init__(self, char):
# in case it is final
# the character of the node
self.char = char
# in case it is final
self.counter = 0 # times the word which ends at this... |
9c88a22b907a6d627e4c0d4aa037ab97b9f7a054 | chenjj28/crossin | /编程实例/21. 数字组合.py | 426 | 3.796875 | 4 | # 1,2,3,4 四个数字,能组成多少个互不相同且无重复数字的三位数?分别是多少?
# 要求:输出 1,2,3,4 组合出的所有无重复数字的三位数。
count = 0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i != j and i !=k and j !=k:
print(str(i)+str(j)+str(k))
count += 1
print('There are total %d numbers.' %count)
|
64576c5c398ab07db530829cdb5f3e3c2d4c183d | dashm8/p2p_layer | /core/encoder.py | 394 | 3.53125 | 4 | import json
class Encoder(object):
"""
encodes and decodes string
"""
@staticmethod
def json_encode(str_msg):
"""
encode into json object from string
"""
return json.loads(str_msg)
@staticmethod
def json_decode(object_msg):
"""
decode into s... |
7a6767e6b4dd6dd607cf4d89be34bddcc3c43eba | ViMitre/sparta-python | /1/functions/for.py | 747 | 4 | 4 | # nested_list = [[1, 2, 3], [4, 5], [6]]
#
# for x in nested_list:
# print(x)
# for y in x:
# print(y)
# book = {
# "name": "The Iliad",
# "author": "Homer",
# "rating": 7
# }
#
# for key, value in book.items():
# print(f"The {key} is {value}")
library = [
{
"title": "The Iliad... |
6a4a267db273c3c252aecae9dfeb63937afcaf0e | ukchong/code1161 | /week2/XP.py | 3,803 | 4.125 | 4 |
"""Make 10 stars.
Using a for loop
return a list of 10 items, each one a string with exacly one star in it.
E.g.: ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*']
"""
def loops_1a():
list=[]
i=0
for i in range(0, 10):
i+=1
list.append("'*'" + " ")
return list
def f... |
68cbf27f6a2aeb5882ac0fe3cbd4c89b40e66e6a | siva6160/lists | /becomelist1.py | 93 | 3.5 | 4 | n=int(input())
s=[]
for i in range(n):
val=int(input())
s.append(val)
print(s)
|
f7294518823ccbecfdda53bb8193d146767c915f | previsualconsent/projecteuler | /p066.py | 739 | 3.8125 | 4 | from fractions import Fraction
from Tools import repeating_fraction_sqrtn, repeating_fraction_conv
from math import sqrt
max_depth = 100
max_x = 0
max_D = 0
# using this algorithm
# http://en.wikipedia.org/wiki/Pell%27s_equation#Fundamental_solution_via_continued_fractions
for D in xrange(2,1001):
if round(sqrt(... |
711a1856105de2be9dd0450282d229ecb957af8a | Ankit-Developer143/Programming-Python | /edabit/edaaaaaaabit.py | 86 | 3.5 | 4 | def how_many_times(num):
return "Ed{}bit".format("a"*num)
print(how_many_times(8)) |
314bac3924f71bffefe12fe6df4650d74cf51a0f | sn1572/leetcode | /236_lowest_common_ancestor_of_a_binary_tree.py | 1,513 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 28 16:02:04 2020
@author: mbolding3
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__( self ):
self.root = None
... |
2ea4138ae144845d79ef2612220bac89005b185f | yskang/AlgorithmPractice | /leetCode/convert_sorted_array_to_binary_search_tree.py | 2,238 | 3.640625 | 4 | # Title: Convert Sorted Array to Binary Search Tree
# Link: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
from typing import List
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
sel... |
57af380a7d1a6480ca09b472772cd26913d49e28 | zdravkob98/Python-OOP-November-2020 | /Lab Iterators and Generators/03-vowels.py | 543 | 3.65625 | 4 | class vowels:
def __init__(self, string: str):
self.string = string
self.i = 0
def __iter__(self):
return self
def is_vowel(self, char):
vowels_word = 'aeiuyo'
return char.lower() in vowels_word
def __next__(self):
while self.i <= len(self.string) - 1:
... |
8a6274d5bccb09ce3852f4045232216b40471e7c | bgmnbear/learn | /Python/Fluent-Python/5,1.py | 311 | 4.09375 | 4 | '''
函数也是对象
'''
def factorial(n):
'''
return n
'''
return 1 if n < 2 else n * factorial(n - 1)
print(factorial.__doc__)
print(type(factorial))
print(factorial(3))
# 列表推导式的使用
fact = factorial
print(list(map(fact, range(6))))
print([fact(n) for n in range(6)])
|
7e0fd9d5ad208435e6b3a3d28f1b37f9ebfe0393 | claytonjwong/Sandbox-Python | /guessing_game.py | 1,748 | 4.28125 | 4 | """
374. Guess Number Higher or Lower
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible resu... |
ec249618dd82515940b0122e9e6f4a4b346c9746 | AVNest/py-checkio-solutions | /home/sun_angle.py | 783 | 4.03125 | 4 | def sun_angle(time):
minutes_per_hour = 60
sunrise = 6 * minutes_per_hour
sunset = 18 * minutes_per_hour
sunset_angle = 180
sun_period = sunset - sunrise
hours, minutes = map(int, time.split(':'))
current_time = hours * minutes_per_hour + minutes
if sunrise <= current_time <= sunset:... |
649b68c23d19d2b2106a52b72aaecfd5ce61353a | jingruhou/python3Learning | /ifTraining/if3.py | 98 | 3.59375 | 4 | s = input('birth:')
birth = int(s)
if birth < 2000:
print('00 qian')
else:
print('00 hou') |
206f66d416950e685de0f3103a5cfc1c9d915cb3 | yguo18/Zero-Stu-Python | /PygameForKey/randomCircle.py | 686 | 3.5625 | 4 | '''
Created on 2016.11.29
@author: yguo
'''
import pygame
import random
pygame.init()
size = [400, 300]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
count = 0
red = pygame.Color('#FF8080')
blue = pygame.Color('#8080FF')
white = pygame.Color('#FFFFFF')
black = pygame.Color('#000000')
done = False... |
f935c98dc2acd78f7c2ead7dbd3e1426b55611c5 | FarabiAkash/Pyhton | /EverydayCode/Elevator_Move.py | 267 | 3.796875 | 4 | user_floor = 5
difference = user_floor - current_floor
if difference < 0 :
current_floor = user_floor
print ( " Move down ")
elif difference > 0 :
current_floor = user_floor
print ( " Move up ")
else :
print ( " Open door ")
|
a7036a34fbe955082770f02a66591b8ea5addbe8 | wwnis7/256 | /Jungwoo-Kang/57prob/13.py | 703 | 3.625 | 4 | # What is the principal amount? 1500
# What is the rate? 4.3
# What is the number of years? 6
# What is the number of times the interest
# is compounded per year? 4
# $1500 invested at 4.3% for 6 years
# compounded 4 times per year is $1938.84.
principal=input("What is the principal amount? ")
rate=input("Wha... |
ae62778c9f6ca439d172219211f87dcf5198e390 | tHeMD03/Opencv_codes | /shape_text_chap4.py | 1,041 | 3.921875 | 4 | import cv2
import numpy as np
# To generate pixels using numpy ((height,width,channels))
img = np.zeros((512, 512, 3), np.uint8)
print(img.shape)
# : is used for the range in which we want the color
# img[:] = 0, 0, 255
# range as per the cropping (height,width)
# img[200:300,100:300] = 0, 255, 0
# (img name, start... |
f22c1f300b918678e89c2b889d7d1e30ca3d7c4c | Indrashish/Python-Projects | /List.py | 814 | 4.59375 | 5 | #Python script for list
#Creating a list
thislist = ["apple", "banana", "cherry"]
#Creating a set
thisset = {"red", "green", "blue"}
print("Printing the list:")
print(thislist)
print("Printing the set:")
print(thisset)
x = lambda a : a + 10
print(x(5))
#Change the second item of the list
thislist[1] = "blackberry"
... |
c091cb99d08f2f474b96f76168800add80cf2c99 | tareqobaida/LeetCode | /medium/531 Lonely Pixel I.py | 1,418 | 3.71875 | 4 | """
Given a picture consisting of black and white pixels, find the number of black lonely pixels.
The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.
A black lonely pixel is character 'B' that located at a specific position where the same row and s... |
2c18494c174b4276e515bd46b9abda17222d56df | kunal951990/practice | /re.py | 591 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 18:17:41 2020
@author: kisku
"""
import re
"""
a. digit at the beginning of the string and a digit at the end of the string
b. A string that contains only whitespace characters or word characters
c. A string containing no whitespace characters """
# ... |
4d5ee97e9f69f1958501ef5cf258a359ae6c2d16 | bavipanda/Bavithra | /whether the given string is a palindrome using stack or linked list and print 'yes' otherwise print 'no'.py | 145 | 4.21875 | 4 | original_string = input()
reversed_string = original_string[::-1]
if(original_string == reversed_string):
print('yes')
else:
print('no')
|
39fbaba8bc9953883a605d86a587655e05e15790 | Napchat/Algorithms | /KochSnowflak.py | 663 | 3.53125 | 4 | import turtle
def KochCurve(level, length, t):
if level == 0:
t.forward(length)
elif level == 1:
t.forward(length/3)
t.left(60)
t.forward(length/3)
t.right(120)
t.forward(length/3)
t.left(60)
t.forward(length/3)
else:
KochCurve(level-1, length/3, t)
t.left(60)
KochCurve(level-1, length/3, t)
... |
21cb81a7cbefbd6fa3fbe9e1cbea0bfedc372e04 | cmumman/calculator | /calculator/Functions/practice.py | 548 | 3.96875 | 4 | print ("hello %s %s" %("vardhan","reddy"))
print ("hello " + "vardhan")
a = 1456789.23124214
print ("a value is : %0.4f" %a)
print ("a value is : %d" %a)
print ("a value is : %e" %a)
print ("a value is : %s" %a)
print ("decimal to octal %d %o" %(10,10))
print ("decimal to Hexa %d %x %X" %(10,100000,100000))
b = 5
... |
eb5f382672f0dbe8b765f620290f6483e3fc35e6 | achmadafriza/DDP1 | /Random Shiz/WS11.py | 1,829 | 3.59375 | 4 | from tkinter import *
def number3():
window = Tk()
window.title('Counter with Lambda')
counter = IntVar()
counter.set(0)
Button(window, text="Up", bg = "Yellow", command=lambda:counter.set(counter.get()+1)).pack()
Button(window, text="Down", bg = "Cyan", command=lambda:counter.set(c... |
4a66363d0e0ce3191708cfee77f14e1461a2379a | satyajeetdeshmukh/Python-OpenCV | /learning gui/2.py | 575 | 3.8125 | 4 | from tkinter import *
root = Tk() # constructor
# root is a blank window
topFrame = Frame(root)
topFrame.pack() #we have placed 1 invisible container
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(topFrame, text="Press me HAARRDD", fg="red")
button2 = Button(topFrame, text="Press me HARRDD... |
214dc4d205bcb5a1e53fe1be2b488d3a74323e1f | renan-eng/Phyton-Intro | /dictionarydatatype.py | 1,571 | 4.21875 | 4 | # para criar uma variavel do tipo dicionario vamos utilizar '{}',
# primeiro temos a keyword : valor serpados por ',' como no exemplo abaixo
myCat = {'size':'fat', 'color':'gray', 'disposition':'loud'}
print(myCat['size'])
print(myCat['color'])
# diferente de listas, o tipo de dados Dicionario nao tem ordem
myCat = {'... |
6bbf8d789a0cc6f52ad1ed514271a83d7f190306 | HanHyunsoo/Python_Programming | /University_Study/lab3_4.py | 955 | 3.71875 | 4 | """
챕터: day 3
주제: 문자열 함수
작성자: 한현수
작성일: 2018.9.6.
"""
"""
1. 이름을 입력 받는다.
2. 이름을 열 번 출력한다. (반복문을 사용하지 않는다.)
"""
name = input("이름: ")
print(name * 10)
"""
3.나이를 정수형으로 입력 받는다.
4. 이름과 나이를 다음 형식으로 s에 저장한다. 정수형인 나이를 문자열로 변환하여 연결한다.
예: "나의 이름은 홍길동이고, 21세입니다."
5. s를 다섯 번 출력한다. 매번 줄바꿈이 포함되어야 한다.
"""
age = int(input("나이: "))
s = ... |
04206564d4d7ed87726472a6bba641b4c054cd46 | icurious/Automate-The-Boring-Stuff-With-Python | /Chapter 7/Regex Version of strip.py | 734 | 4.59375 | 5 | # Write a function that takes a string and does the same thing as the strip()
# string method. If no other arguments are passed other than the string to
# strip, then whitespace characters will be removed from the beginning and
# end of the string. Otherwise, the characters specified in the second argument to
# the fun... |
6534d7bac75c76a7c4d937f88d4998cd12ece13f | has-sidd/Lab-Tasks-in-python-1st-Semester | /Cylinder.py | 458 | 4.25 | 4 | from math import*
def area(r, h):
x = (2*pi*r*h) + (2*pi*(r**2))
return x
def volume(r, h):
x = (pi*r**2)*h
return x
radius = float(input("Enter radius of cylinder : "))
height = float(input("Enter height of cylinder : "))
if radius <= 0 or height <= 0:
print("INVALID INPUT")
... |
fb3ec80f51be9de056499574f47b67c836c74bc3 | luciana-sarachu/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 319 | 3.96875 | 4 | #!/usr/bin/python3
"""This is a class called MyList that inherits from list"""
class MyList(list):
"""Public instance method that prints the list,"""
""" but sorted (ascending sort)"""
def print_sorted(self):
""" all the elements of the list will be of type int"""
print(sorted(self))
|
3cb1bb0ab0546635a5e9a79aad585e115cc8e25a | RudyHarun99/Morse | /ganjil_genap.py | 138 | 3.703125 | 4 | def gage(x):
if x%2==0:
print(x,'tergolong GENAP')
else:
print(x,'tergolong GANJIL')
gage(int(input('Ketik angka : '))) |
f808457728180b21ffdc105d654ae3260e092838 | Bobert127/python_and_postgresql | /ownerlern/test.py | 422 | 3.78125 | 4 | class Car:
def __init__(self, color='white', initial_speed=0):
self.color = color
self.speed = initial_speed
self.gear = 0
if self.speed > 0:
self.gear = 1
# def create_car():
# pass
car_dict = {}
car_dict['speed'] = 1
print(car_dict['speed'])
car = Car(initial_spe... |
9a53a3022efdeb792bb680c7b4fbe59fe9c4a0d3 | lishulongVI/leetcode | /python/650.2 Keys Keyboard(只有两个键的键盘).py | 3,388 | 3.6875 | 4 | """
<p>
Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:
<ol>
<li><code>Copy All</code>: You can copy all the characters present on the notepad (partial copy is not allowed).</li>
<li><code>Paste</code>: You can paste the characters which are copie... |
2c3e14589961ffdaed5412f7d9edb209341f9fd0 | MonikaMudr/pyladies | /Flask_test/piskvorky_flask/util.py | 419 | 3.734375 | 4 | def tah(pole, index, symbol):
if index >= len(pole) or index < 0:
raise ValueError
if pole[index] != '-':
raise ValueError
if symbol not in ('x', 'o'):
raise ValueError
return pole[:index] + symbol + pole[index + 1:]
def vyhodnot(pole):
if 'xxx' in pole:
return 'x'... |
e51948a0274a4548d7fef576045afdd528185224 | vecst/pasNthRoot | /pasNthRoot.py | 1,192 | 3.734375 | 4 | import decimal
from functools import reduce
#edit
def fact(o):
#creates factorial of number 'o'
return reduce(lambda x,y: x * y,range(1,o+1)) if o >0 else 1
def pas(r):
# Creates row 'r' of pascals triangle
pa=list(range(1,r))
return [1]+[fact(r) / (fact(x)*fact(r-x)) for x in pa]+[1]
def shuf(a,g):
#t... |
ecb84f93e2be3790f3338ac106e3179b362fe2e3 | Mary-test/Homework1_1 | /Mary.py | 144 | 3.703125 | 4 | First_name = "Mary"
Last_name = "Malumyan"
text = First_name+Last_name
for index in range(len(text)):
print(*text[:index + 1])
|
3e356f3c3be55efb41e9d8f51124ca28069846cc | kgarbutt/dsa | /list-comp.py | 312 | 3.78125 | 4 | # list comprehension in Python
l = [2,4,8,16]
m = [i**3 for i in l]
n = [i*2 for i in l]
print(m)
print(n)
print('#' * 8)
def f1(x):
return x*2
def f2(x):
return x*4
lst = []
for i in range(16):
lst.append(f1(f2(i)))
print(lst)
print([f1(x) for x in range(64) if x in [f2(j) for j in range(16)]])
|
4e4cb7563af2a7904d30cffe5c616552cca40154 | Darmawan17/PBO | /PBO_18136/latihan_5.7.while-continue.py | 623 | 3.578125 | 4 | status=False
batas=3
tabel_username =["admin","sayaadmin","sayajugaadmin"]
tabel_password =["ummu","ternate","akademik"]
while batas > 0:
tanya_username=input("masukkan user name anda: ")
tanya_password=input("masukkan password anda: ")
for password in tabel_password:
for username in tabel_username:
i... |
d64eaa00215550f811267822e464383d5115d9d5 | Roykssop/pytraining | /06-Loops/for.py | 361 | 4.03125 | 4 | """
Bucle for
"""
contador = 0
for contador in range(1,11):
print(f"Vamos por el indice {contador}")
"""
Ejer: Tabla de multiplicar
"""
numTabla = int(input("Que tabla de multiplicar quiere ver?"))
counting = 0
for counting in range(1,11):
print(f"El número elegido fue {numTabla} x {counting} = {counting*n... |
d0e5c2ec7ec97aa2a6e9e62bea75db79c6db251e | lizhe960118/TowardOffer | /专题学习/二分法/Rotated_sorted_array_halfHalf.py | 1,209 | 3.53125 | 4 | class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n = len(nums)
if nums is None or n == 0:
return -1
start = 0
end = n - 1
# half half模型:使用增加判断条件的方法... |
50c26f6b8c54d604777ccd0be128f6083214ac33 | mpsonntag/snippets | /python/bc/abstracts_uploadkey_csv.py | 2,280 | 3.65625 | 4 | """
Opens a CSV file containing GCA abstract server data, identifies the "id" column,
containing GCA server abstract UUIDs and uses it to create salted and hashed strings
from the corresponding values.
A new column "upload_key" is added to the CSV data and a new file is saved.
"""
import argparse
import hashlib as hl
... |
58c60ece6937034f0c644250a3ca0b3b4f5a1f59 | rsainaveen/Natural-language-processing | /Training/Bigram/unigramvocabulary.py | 1,217 | 3.578125 | 4 |
def unigramvocabulary(data,vocabfile):
reviews_file = open(data, "r")
megadoc = ""
unigrams = {}
for line in reviews_file:
megadoc = megadoc + line
words = megadoc.split()
words.sort()
count=1
freq=[]
vocab =[]
while len(words) > 0:
temp = words[0]
... |
7c72f6db0f65b89f925f15952af1e7596160fa12 | ilodi/masterPython | /ejerciciosMed/01.py | 962 | 4.40625 | 4 | '''
tiene un lista con 8 numeros
recorrela y mostrala
hacer una funcion que recora lista de numeros
ordenarla y mostrarla
buscar un elemento que usuario pida por teclado
'''
# crear la lista
lista = [3, 5, 6, 2, 5, 6, 7, 2]
def mostrarLista(lista):
resultado = ""
for elmento in lista:
resultado += s... |
aea9220f4b0ad7aa5a265e8e46483cdbfb408b96 | vickyarp/MITx-6.00.1x | /Problem sets/Problem set 1/Problem 3.py | 788 | 4.5 | 4 | #Assume s is a string of lower case characters.
#
#Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
#
#Longest substring in alphabetical order is: beggh
#In the case of ties, print the firs... |
a7bd3be0cd8c08c6a68b22e6b9d590bdc50fc5de | Priyanshasharma520/Flaskblog | /python_practice_program/Anstrome_number.py | 676 | 3.796875 | 4 | print("Hello")
class anstrome_numer():
def __init__(self):
pass
def getting_numbers(self,number):
number_list=[]
while number!=0:
p=number%10
number_list.append(p)
number=number//10
return number_list
def finding_anstrome(self,number):
... |
abfb87b5d69133e70f5c2c0be2e84d22bc265ba6 | wangheng17/Python | /python/十进制转化成二进制函数.py | 229 | 3.625 | 4 | def change(x):
ls=[]
while x>0:
m=x%2
x=x//2
ls.append(m)
ls.reverse()
print("转化为二进制{}".format("".join(map(str,ls))))
x=eval(input("请输入一个十进制数: "))
change(x)
|
802bd78257c0713d94b19c84d39696f578501682 | Vendea/summer-research-2016 | /MCMC/Metropolis_Hastings_Evolutionary.py | 7,965 | 3.890625 | 4 | '''
A Multilayer Perceptron implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
# Import MINST data
from tensorflow.examples.tutorial... |
5603c5f6dbd827bbbdcdcc7d83af82924fd1e58e | aesavas/Project-Euler | /Problem 005/Python/Problem 5.py | 1,154 | 3.875 | 4 | """
author: aesavas
Problem 5:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
def divible1to20():
listOfNumbers = list(range(2, 21)) # range(2, 21) mea... |
6b42a241a38430cf589f56bbfb3270ce19ce0b61 | shankar7791/MI-10-DevOps | /Personel/Vinayak/Python/Practice/1 March/Program 2.py | 171 | 4.09375 | 4 | #Accept number from user and calculate the sum of all number between 1 and given number
a=int(input("Enter Number:"))
sum=0
for x in range(1,a+1):
sum=sum+x
print(sum) |
161a6785d5984b9dbb7e017fa33b6fc6b4e76b3c | drFabio/boxDetector | /lineSegment.py | 3,783 | 3.734375 | 4 | # -*- coding: latin-1 -*-
import numpy as np
def vector_length(vector):
return (vector[0]**2+vector[1]**2)**0.5
class LineSegment:
"""Represents a line segment on a pixel plane
Since we are handling pixels there all coordinates are discrete(int)
Attributes:
a (Tuple(int,int)): start point n... |
f0f18db4392cb7c04333894af61fb102be4d48a9 | hanrick2000/LeetcodePy | /leetcode/bfs_dfs/binary_tree_vertical_order_traversal_bfs_2.py | 946 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import defaultdict
class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List... |
0c8863ef80c2f03247344d0f4cf6958dbddbbaa2 | HidoCan/Programlama_dilleri_yaz_okulu | /2021/2021 tyt fonksiyonlar 12.py | 204 | 3.5625 | 4 |
b=0
print("f(a)*g(a)=8")
f(a)+g(a)=b
f(a)-g(a)=2
f(a)+g(a)-b+(f(a)-g(a)-2)
2*f(a)=b+2
f(a)=(b+2)/2
f(a)+g(a)-b-(f(a)-g(a)-2)
2*g(a)=b-2
g(a)=(b-2)/2
((b+2)/2)*((b-2)/2)=8
b=6
print("b=",b)
|
c6174ec4378f0dbfbe2977079d1561f8e5d87dfd | ToR-0/python-exercises | /aufgabe3.py | 281 | 3.9375 | 4 | #Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn. Go to the editor
#Sample value of n is 5
#Expected Result :
a = int(input("input an intager : "))
n1 = int( " %s" %a)
n2 = int("%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
print(n1+n2+n3)
|
05c6b279441d1d17e861d0aa7c57f5d1c5dfcbbf | BakJungHwan/Exer_algorithm | /Programmers/Level1/SumMatrix(jpt)/sumMatrix.py | 248 | 3.671875 | 4 | def sumMatrix(A,B):
answer = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j]+B[i][j])
answer.append(row)
return answer
print(sumMatrix([[1,2], [2,3]], [[3,4],[5,6]])) |
db22da2c7527b71519cb014c41954ac0cb4b9175 | Melissious/cylenian-calendar | /cylenian.py | 5,052 | 3.640625 | 4 | import collections
import gregorian
# The leap eras in a 100-era timespan
leap_eras = [4,12,21,37,46,54,71,79,87]
# The names of the Cylenian months
month_names = [
"Elsy'ondleð", "Nae Boryeð", "Seniðin",
"Liðin Boryeð", "Emmiðiða", "Omilnin",
"Karðondleð", "Seðaneðr", "Liliðin",
"Liðin Maroo", "Fðileð", "... |
d35ed28ae71ab53f059762d90843dca65d29ded6 | IamBikramPurkait/100DaysOfAlgo | /Day 64/HBT.py | 2,214 | 4.25 | 4 | '''Given Inorder traversal and Level Order traversal of a Binary Tree. The task is to calculate the height of the tree without constructing it.
Example:
Input : Input: Two arrays that represent Inorder
and level order traversals of a
Binary Tree
in[] = {4, 8, 10, 12, 14, 20, 22};
level... |
3275a245249d25b54210b8ad4496d27e5bbdfce9 | rgrishigajra/Competitive-Problems | /Random Coding tests/string transform.py | 1,579 | 3.546875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'getMinTransform' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING source
# 2. STRING target
#
def getMinTransform(source, target):
count = 0
... |
9b3278438db50f9887f97fe4363260a6b7bcb0c5 | Gwellir/gb_py_algo | /lesson3/task4.py | 639 | 3.703125 | 4 | # Определить, какое число в массиве встречается чаще всего.
import random
SIZE = 100
MIN_ITEM = 0
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
numbers = {}
for i in range(0, SIZE):
numbers[array[i]] = numbers.get(array[i], 0) + 1
max_amount = 1
top_number = array... |
f1a54ef36e65913488065b6151138fa34d24675f | xy2333/Leetcode | /leetcode/spiralOrder.py | 521 | 3.5625 | 4 | class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
res = []
while len(matrix[0]) != 0:
res += matrix[0]
matrix.pop(0)
if len(matrix) == 0:
matrix = [[]]
else:
lst = []
for i in range(len(... |
87149782893b4be4d3998dc1b0f2adcade0a188f | karthikpalavalli/Puzzles | /leetcode/climbing_stairs.py | 355 | 3.5 | 4 | class Solution:
def climbStairs(self, n: int) -> int:
if n == 1 or n == 0:
return n
mem_table = list()
mem_table.append(0)
mem_table.append(1)
mem_table.append(2)
for idx in range(3, n + 1):
mem_table.append(mem_table[idx - 1] + mem_table[idx... |
ee1a3a70f800e452850122325b3f7490405527b0 | alexsalo/algorithms | /Sorting/quicksort.py | 466 | 3.765625 | 4 | __author__ = 'alex'
basicOperationCounter = 0
def qsort(arr):
#print arr
global basicOperationCounter
if len(arr) < 2:
return arr
pivots = [x for x in arr if x == arr[0]]
lo = qsort([x for x in arr if x < arr[0]])
hi = qsort([x for x in arr if x > arr[0]])
return lo + pivots + hi
... |
84cb7ea9825da6aa2d3e85c390571585e6e1f7d9 | gaeunPark/Bigdata | /01_Jump_to_Python/Chap03/board_Pagng.py | 279 | 3.515625 | 4 | # coding: cp949
m = int(input(" Ǽ Էϼ: "))
n= int(input(" Խù : "))
if n<=0:
print("ٽ Էϼ")
else:
if m==0:
result=0
else:
result=(m//n)+1
print("%d %d %d" %(m, n, result))
|
3c9a6c7d249a3474c4ab1ca6b4d2a7eef87811b4 | amir-jafari/Data-Mining | /01-Pyhton-Programming/2- Lecture_2(Python Intermediate)/Lecture Code/1-Squar_Root_Example.py | 302 | 4.15625 | 4 | from math import sqrt
num = eval(input("Enter number: "))
root = sqrt(num);
print("Square root of", num, "=", root)
x = 16
print(sqrt(18))
print(sqrt(x))
print(sqrt(2 * x - 5))
y = sqrt(x)
print(y)
y = 2 * sqrt(x + 10) - 3
print(y)
y = sqrt(sqrt(56.0))
print(y)
print(sqrt(int('23')))
print('#',50*"-") |
37537fa6d0223b5109dad627c914b4b39b76d34a | Dvshah13/Python_Class | /python1.py | 445 | 3.96875 | 4 | from random import randint;
secret_number = 5
guess = randint(1,10)
guesses = 0
print("I am thinking of a number between 1 and 10")
while guesses < 9:
print("What's the number?")
num = int(raw_input())
guesses = guesses + 1
if (num > secret_number):
print("%d is too high")
elif (num < ... |
4467ae2fd623ac14f2b629987f89591e09250e58 | joy-kitson/udel_course_scraping | /intro.py | 859 | 3.640625 | 4 | #!/usr/bin/python
#based on tutorial from
#https://medium.freecodecamp.org/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe
import urllib2 as url2
from bs4 import BeautifulSoup as bs
#specify url
quote_page = 'http://www.bloomburg.com/quote/SPX:IND'
quote_page = \
'http://catalog.udel.edu/search_adv... |
d2334194e6bce81f4fa68464bc010567f9018521 | chiragnayak/python | /LearningPy/concepts/queue.py | 906 | 3.6875 | 4 | import threading
from time import sleep
def do_work(item):
print("Processing !! --> {} by --> {} ".format(item, threading.current_thread().name))
sleep(1)
def worker():
while True:
# get processing item from queue when available
item = q.get()
if item is None:
break
... |
816085e82744c06f8e0da195e797034f12737afc | LipsaJ/PythonPrograms | /X005-A-Dictionary/Dictionary1.py | 1,423 | 4.3125 | 4 | # List are ordered sequences, both dictionary and set are unordered,
# set is unordered so indexes doesnt make sense. Dictionary are key value paired.
fruits = {"Orange": "a sweet sour orange coloured fruit",
"Lime": "a green coloured sour fruit",
"Apple": "Keeps doctor away",
"Lime... |
49171666a9fce84c3add059a48e053b7527bc26e | cuiy0006/Algorithms | /leetcode/845. Longest Mountain in Array.py | 994 | 3.5 | 4 | class Solution:
def longestMountain(self, arr: List[int]) -> int:
res = 0
curr = 1
up = True
for i in range(1, len(arr)):
if up:
if arr[i] > arr[i - 1]:
curr += 1
elif arr[i] < arr[i - 1]:
if curr == ... |
726abe4323923852c384830e1174968e8487015c | PanlopRaman/CP3-Panlop-Raman | /Exercise21_Panlop_R.py | 1,283 | 3.734375 | 4 | from tkinter import *
import math
def LeftClick (event):
#labelResult.configure(text = float(textBoxW.get())/math.pow(float(textBoxH.get())/100,2))
BMI = float(textBoxW.get())/math.pow(float(textBoxH.get())/100,2)
print(BMI)
if BMI > 30:
labelResult.configure(text="อ้วนมาก")
print(BMI)
e... |
23befa0c1d4d45b83c174ee6e3d13e412e7dd23e | log2timeline/plaso | /plaso/cli/time_slices.py | 1,303 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""The time slice."""
class TimeSlice(object):
"""Time slice.
The time slice is used to provide a context of events around an event
of interest.
Attributes:
duration (int): duration of the time slice in minutes.
event_timestamp (int): event timestamp of the time slice or None... |
f6e286ce805e1005c22bba16d2908f70ab37df0e | tony-ml/jiuzhangAlgo | /Joe Zheng/week 3/539. Move Zeroes.py | 510 | 3.546875 | 4 | class Solution:
"""
@param nums: an integer array
@return: nothing
"""
def moveZeroes(self, nums):
# write your code here
left = 0
right = len(nums) - 1
while(left + 1 < right):
if(nums[left] == 0):
del nums[left]
nums.app... |
43311471060d0a0ec549a02a9409c80a87770362 | Pm1995/Leetcode- | /Arrays(Leetcode).py | 1,395 | 3.640625 | 4 | #Remove Duplicates from Sorted Array
nums = [0,0,1,1,1,2,2,3,3,4]
i=0
while i<len(nums)-1:
if nums[i]==nums[i+1]:
nums.pop(i)
else:
i=i+1
print(len(nums))
print("\r")
#Merge Sorted Array
nums1 = [1,2,3,9,10]
nums2 = [2,3,5,6,10,12]
a=0
while a<len(nums1):
if nums1[a]==0:
nums1.pop(a)
else:
a=a+1
i=0... |
b144587b227f90bc48394f4f2c4e1e7f9cc0bcf9 | gabriellaec/desoft-analise-exercicios | /backup/user_110/ch23_2020_10_06_21_37_40_451108.py | 223 | 3.671875 | 4 | def multa(v):
return (v-80)*5
velocidade = int(input('qual a velocidade do seu carro? '))
if velocidade > 80:
print('ecebeu multa otario')
int(print('pague {}'.format(multa))
else:
print('Não foi multado') |
e06c14c6abf7e6b82f8f8c83c75f704d6ef465eb | Abhivarun19/Python-1-09 | /L9-27-10-PUSH A SPECIFIC ELEMENT.py | 152 | 3.609375 | 4 | #Push A ELEMENT IN STACK
stack = ["NTR", "RAM", "RRR"]
print (stack)
# PUSH ELEMENT
stack.append("MS")
stack.append("SAM")
print(stack)
|
062be64ffec131094c89b4d72da14f71813ab30c | carinazhang/deeptest | /第二期/杭州-张月萍/快学python3/类/learn class1.py | 1,171 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# __author__ = 'Carina'
# 类的属性
class CocaCola:
# 配方
formula = ['caffeine','suger','water','soda']
# 实例方法,方法就是函数
def drink(self): # self其实就是被创建的实例本身
print('Energy')
# 更多参数
def drink1(self, how_much):
if how_much == 'a ship':
print('cool~')
... |
a692c56671cd8a6d6afe70fd6b7a85ee04799c18 | antares681/Python | /PythonAdvanced/L.04.Comprehensions/COMPREHENSIONS`_ALL.py | 280 | 3.765625 | 4 | #DICTIONARY COMPREHENSION
nums = [1, 2, 3]
cubes = {num:num **3 for num in nums }
#TODO SET COMPREHENSION
nums = [1, 2, 3, 1, 3, 4]
unique = {num for num in nums} # a = set()
print(ord('a'))
print(chr(97))
#TODO NESTED COMPREHENSION
[[j for j in range(2)] for i in range(4)] |
00937d3091e86965fe7028eb326cc63a96a04b9e | RainhugTiny/commom_algorithm | /binary_search.py | 369 | 3.828125 | 4 | def binary_search(nums, value):
l, r = 0, len(nums) - 1
while(l <= r):
m = (l + r) // 2
if nums[m] == value:
return m
elif nums[m] > value:
r = m - 1
else:
l = m + 1
return -1
if __name__ == '__main__':
input = [1, 3, 3.5, 4, 4.5, 5]
... |
dfbf4b1ce3d565a9ffaf09769e9624ac4cb2925e | daddyawesome/CodingP | /stacktrek/toykingdom.py | 780 | 3.859375 | 4 | target=float(input("target:"))
puzzle=float(input("puzzle:"))
talkingDoll=float(input("talkingdoll:"))
teddyBear=float(input("teddybear:"))
pokemonPlushie=float(input("pkemonplushi:"))
bigToyTruck=float(input("bigtoytruck:"))
totalToys= puzzle + talkingDoll + teddyBear + pokemonPlushie + bigToyTruck
pPrice = puzzle *... |
8f2b46452c8de42646b41200a92a9debc7b3c4d0 | kleimkuhler/snippets | /Python/PriorityQueue.py | 1,880 | 4.09375 | 4 | from utils import *
class PriorityQueue:
"A Priority Queue in a binary heap"
dist = {}
prev = {}
Q = []
def __init__(self, n, start=1):
"Initialize node dists and prevs to infinity and None respectively."
for node in range(1, n+1):
self.dist[node] = inf
sel... |
6286ac8c54b2f9bd339dc96b4e51f4820fa17c80 | sysadwcai/AWS-Re-Start | /progs/stoplight_demo.py | 1,052 | 3.78125 | 4 | # stoplight demo
import time
import turtle
wn = turtle.Screen()
wn.title("Stoplights by Winnie")
wn.bgcolor("white")
# Draw box around the stoplight
pen = turtle.Turtle()
pen.color("black")
pen.width(3)
pen.hideturtle()
pen.penup()
pen.goto(-30, 60)
pen.goto(-30, 60)
pen.pendown()
pen.fd(60)
pen.rt(90)
pen.fd(120)
pe... |
9a18f047004c4870048e11cd6ed04c1edb55883c | mia-fu/LeetCodeAnimation | /LeetCode第101号问题:对称二叉树.py | 904 | 4.15625 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def check(node1, no... |
31c841f2b17d592c534138dd0d01fd8ea6bf04e1 | talesCPV/VideoChess2600 | /chess_move.py | 8,688 | 3.734375 | 4 |
'''
chess_move:
call: move(lit, tabuleiro)
where: lit
-> String
-> position on board, ex: 'a2'
tabuleiro
-> matrix (8x8) of list with 2 Strings, first represent the color and second the piece
... |
3e011d043aa373f8cab9c9fba3a94c217abbf7d3 | basharatw/Python | /ex33.py | 1,231 | 4.03125 | 4 | # Exercise 33: While Loop
print "================ Exercise 33: While Loop ======================"
i = 0
numbers = []
'''
while i < 6:
print '\n'
print "At the top i is %d" % i
numbers.append(i)
i = i+1
print "Numbers now:", numbers
print "At the botton i is %d" % i
pr... |
2c102c241479d4e82ded8ace45dcde0e569f7bd8 | puneet672003/SchoolWork | /PracticalQuestions/09_question.py | 225 | 4.125 | 4 | # Write a python program to implement python string functions.
string = input("Enter string : ")
print("In captial : ", string.upper())
print("In lower : ", string.lower())
print("Total number of characters : ", len(string)) |
2764b601ef3df041593d9b7b12d0ef590ef2768c | ttpro1995/code_gym | /challenge/is_smooth.py | 661 | 3.703125 | 4 | # __name__ = "Thai Thien"
#
# __link__ = "https://app.codesignal.com/challenge/7kZavbM3FBC85FtNA"
__author__ = "Thai Thien"
__email__ = "tthien@apcs.vn"
def isSmooth(arr):
"""
An array is called smooth if its first and its last elements are equal to one another and to the middle
:param arr: the array of in... |
c01c90cec2119d2b3e7f490c0531144bb9e9dfe6 | Yashpal-Besoya-2222/Python-p2p-programming-class | /vote.py | 128 | 4.0625 | 4 | age=int(input("Enter Age:"))
if age>18:
status="Eligible"
else:
status="Not Eligible"
print("You are",status,"for vote") |
012ab172576e4caa22fa0661ae304825a6e0f3a5 | Linh-T-Pham/Study-data-structures-and-algorithms- | /merge_ll.py | 2,625 | 4.15625 | 4 | """ Merge Linked Lists
Write a function that takes in the heads of two singly Ll that are
in sorted order, respectively. The function should merge the lists
in place(i.e, it should not create a brand new list and return the head
of the merged list; the merged list should be in sorted order)
Each l... |
d1bdb7d6a3021b67a1b026bd1f6de7abc578032c | northy/calculo-numerico | /zeros_de_funcao/strings.py | 459 | 3.921875 | 4 | def cordas(f,a,b) :
fa = f(a)
fb = f(b)
return (a*fb-b*fa)/(fb-fa)
def findRoot(f,a,b,e) :
x = cordas(f,a,b)
n = 0
while abs(f(x))>e :
if f(a)*f(x)>0 : a=x
else : b=x
x = cordas(f,a,b)
n+=1
return x, n
def printRoot(f,a,b,e) :
try :
pri... |
33dd1947ef5ae9d53f2d22384b7c9e47304ce9ba | shearn6/MyRepo | /savingandreadingdata_assignment.py | 916 | 4 | 4 | import datetime
date = datetime.date.today()
question = input("Have you previously used this program?\n Y|n: ").lower()
if question != "n":
while True:
try:
with open("goodbad.txt","r") as f:
print(f.read())
break
except FileNotFoundError:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.