blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
0d74d350f93fe1e2d12024f7cc24f48d27e5224f | pzabauski/Homework | /Homework2/#2.py | 3,641 | 4.25 | 4 | # Модуль calendar
# Пользователь вводит дату своего рождения в формате DD.MM.YYYY.
# Вывести название дня недели, в который родился пользователь.
# Пользователь вводит название дня недели. Вывести ближайший месяц и год, когда этот день недели выпадал на 1-ое число.
import calendar
import datetime
# Часть 1 v.1
a = i... |
a0f4da105b8fe154a002be9c26ffb4e938cd32fd | Djphoenix719/rl-search | /benchmarks/misc_util.py | 368 | 3.5 | 4 | def print_banner(text: str, header_char: str = "-", footer_char: str = "-", size: int = 50) -> None:
"""
Print a nicely formatted banner with a line of header and footer characters
:param text:
:param header_char:
:param footer_char:
:param size:
:return:
"""
print(header_char * size... |
ad36a00ddb252a48269726cce87f575e047c7b5a | itnks/Dominos | /Node.py | 3,683 | 4 | 4 | class Node(object):
def __init__(self, data, next):
self.data = data
self.next = next
###########################################
###########################################
class SingleList(object): ... |
eb048e9a054390e51acf4cfe935fad82002eb834 | asiegman/learning_snippets | /boolean.py | 1,327 | 3.921875 | 4 | #!/usr/bin/env python
# Truth in python means the built-in boolean True, or a non-zero, non-None value
# False means zero, none, or the boolean False
# "Truthiness" may vary from language to language, but boolean logic does not
true = True
true = bool(17)
true = bool(-1.25)
false = bool(None)
false = bool(0)
false = ... |
0aad5b4eadf57b44acea4384ffebeb4498dc7d88 | LeonardoBrabo/Informatorio | /Programacion Web/EstructurasdeControl/3_NivelFacil.py | 455 | 3.671875 | 4 | usuario = str(input("id: "))
password = str(input("pass: "))
print("usuario creado")
print(" ")
print("loguearse:")
us =str(input("id: "))
contra = str(input("pass:" ))
cont= 0
while cont <5:
if us != usuario or contra != password:
us =str(input("id: "))
contra = str(input("pass:" ))
cont+= ... |
b77587f138ad09828aeb999ebb915b2c292c777a | kaisjessa/Project-Euler | /pe058.py | 803 | 3.8125 | 4 | import math
'''
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
'''
def spiral(x):
diagonals = []
count = 0
increment = 2
i=1
while(i <= x**2):
diagonals.append(i)
count += 1
i += increment
if count % 4 ==0:
increment += 2
return(diagonals)
def is_prime(x):
if(x<2):
retu... |
ab1b942c870d1bb964c6e9e8eb2e7c41fa505e0a | kaisjessa/Project-Euler | /pe028.py | 272 | 3.515625 | 4 | '''
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
'''
def cycle(x):
total = 0
count = 0
increment = 2
i=1
while(i <= x**2):
total += i
count += 1
i += increment
if count % 4 ==0:
increment += 2
return(total)
print(cycle(10)) |
ecea765e44dae66b75770ea5f0a1ce7fbcb831cc | SurajSarangi/Python | /Python/chefdil.py | 138 | 3.53125 | 4 | t=int(input())
while(t>0):
s=input()
c=s.count("1")
if(c%2==1):
print("WIN")
else:
print("LOSE")
t=t-1 |
446b90dd052e0c3b0101711aa94ee2ea223cb5c2 | SurajSarangi/Python | /Python/File_encryption/encrypt_file.py | 447 | 3.703125 | 4 | """Encrypting an entire file"""
f1=open("input.txt",'r')
f2=open("output.txt",'w')
for m in f1:
for i in m:
if i==' ':
f2.write(' ')
elif i=='.':
f2.write('.')
elif i=='\n':
f2.write('\n')
elif ord(i)>=65 and ord(i)<=90:
j=ord(i)+5
if j>ord('Z'):
k=j-ord('Z')
j=ord('A')+k-1
f2.write... |
8493bad14ffd7c0f298789e3fafc55469c9f8476 | KarthikPeneti/test | /hungry.py | 103 | 3.890625 | 4 | hungry = input("are you hungy?")
if hungry =="yes":
print("eat something")
else:
print("okay")
|
c11d7e04f135c6249c737f71924ea1e3d610027e | ParagDasAssam/Calculator_pythontk_code | /testing_cal.py | 1,171 | 3.671875 | 4 | from tkinter import*
import tkinter.messagebox
def beenClicked():
radioValue = relStatus.get()
tkinter.messagebox.showinfo("you clicked", radioValue)
return
def changeLabel():
name= "Thanks for the click " + yourName.get()
labelText.set(name)
yourName.delete(0,END)
yourName.inser... |
74ab3200ab835a3fffc9f9a457e354b9e3ca92e0 | miguelgrubin/python-examples | /concurrencia/hilo.py | 567 | 3.578125 | 4 | import threading
import time
class Hilo(threading.Thread):
"""
El hilo dura tanto como dure el main().
El stdout y stderr (print y errores) es es mismo que el main()
"""
def __init__(self):
threading.Thread.__init__(self)
self.setDaemon(True)
self.contador_segundos = 0
... |
f5041687b224782c671fbbeaeb79dcd7dcca9524 | ChrisPoche/Coding_Dojo_Work | /Python/Python_basics/findChar.py | 287 | 4 | 4 | #Take a list of words, print a new list of those words that contain a specific character
word_list = ['hello','world','my','name','is','Anna']
char = 'a'
new_wl = []
for x in range(0,len(word_list)):
if word_list[x].find(char) != -1:
new_wl.append(word_list[x])
print new_wl
|
9cac20b09bf506f6bc3ac592f124239772ab1f18 | ChrisPoche/Coding_Dojo_Work | /Python/Python_basics/compareList.py | 426 | 3.875 | 4 | list_one = ['celery','carrots','bread','cream']
list_two = ['celery','carrots','bread','cream']
if len(list_one) != len(list_two):
same = False
else:
for x in range(0,len(list_one)):
if list_one[x] == list_two[x]:
same = True
elif list_one[x] != list_two[x]:
same = False... |
f9ab383be53502c4965649e02942735da0e937a0 | ChrisPoche/Coding_Dojo_Work | /Python/OOP/car.py | 1,116 | 4.09375 | 4 | #Create a class that allows the user to input price, speed, fuel, and mileage. Place a conditional that any car above $10,000 receive a 15% tax, the default otherwise being 12%
#Create 6 instances
class Car(object):
def __init__(self,price,speed,fuel,mileage):
self.price = price
self.speed = speed
... |
df0897a57a4ff7b72d57c0ee153a2171435e6d23 | weaver-viii/hh_scraping | /HH_crawler/statistics.py | 1,247 | 3.6875 | 4 | # This module is for calculating and analysing scraped data.
import csv
import re
import collections
import pandas as pd
def analyse_data(filename):
with open('./' + filename, newline='') as data:
reader = csv.reader(data, delimiter='"')
for row in reader:
if len(row) > 2:
... |
f4ac6f727eda468a18aaaeb59489940150419e63 | Tanushka27/practice | /Class calc.py | 423 | 4.125 | 4 | print("Calculator(Addition,Subtraction,Multiplication and Division)")
No1=input("Enter First value:")
No1= eval(No1)
No2= input("Enter Second value:")
No2= eval(No2)
Sum= No1+No2
print (" Sum of both the values=",Sum)
Diff= No1-No2
print("Difference of both values=",Diff)
prod= No1*No2
print("Product of both the values... |
122fcf7b577d4fb5e5c7c3f45f0c267a0fcf6939 | leonardodma/robot202_AL | /aula02/Atividade2/atividade4.py | 3,551 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Referências:
# https://www.geeksforgeeks.org/circle-detection-using-opencv-python/
# https://www.geeksforgeeks.org/python-opencv-cv2-line-method/
import math
import cv2
import numpy as np
from matplotlib import pyplot as plt
import time
import sys
import auxiliar as au... |
cf440450ee2e0f43cb330bc4bb1d9807fac865da | NickGervais/geocoder | /request_impl.py | 1,442 | 3.796875 | 4 | # this library works best on linux running python2.*
import requests
# this is my registered api key for google maps I recieved from Google
apiKey = "AIzaSyBdHvCMgUN-3Oy7HdkzW3AguKBDpuodSYw"
# the base url endpoint to retreive our json data from
url = "https://maps.googleapis.com/maps/api/geocode/json"
#asks the user t... |
1a291ceda2a85d32ffe909d388b2eccde42fac93 | mgrelewicz/metaheur | /funkcja_celu.py | 1,053 | 3.796875 | 4 | # -*- coding: utf-8 -*-
#
#### Funkcja celu: chcemy uzyskać różnicę (diff) żeby móc ją minimalizować
def goal(subset):
size = len(subset)
print('size: ', size)
if (size%2 == 0):
A_size = size//2
B_size = size//2
else:
A_size = size//2
size +... |
9d92a7bc359ecc7b3e6417c0cd58130f6902c181 | XxAGMGxX/Python | /Ejercicio 3 - comisión.py | 689 | 3.984375 | 4 | # 3 Un vendedor recibe un sueldo base más un 10% extra por comisión de sus ventas.
# El vendedor desea saber cuánto dinero obtendrá por concepto de comisiones por las tres
# ventas que realiza en el mes y el total que recibirá en el mes tomando en cuenta su sueldo
class comisión:
SalarioBase=float(input("El sal... |
26acbd3eee6d7771699b14d9ce641302ca48a204 | XxAGMGxX/Python | /Ejercicio 8 - NumMayor.py | 547 | 3.78125 | 4 | class NMay:
def __init__(self):
pass
def NM(self):
num1 = int(input("Ingrese el primer número: "))
num2 = int(input("Ingrese el segundo número: "))
num3 = int(input("Ingrese el tercer número: "))
if num1 > num2 and num1 > num3:
print("El número mayor e... |
55f3518c31f9c80c2f41761aea229bfddad4f748 | 5nizza/spec-framework | /structs.py | 2,784 | 3.671875 | 4 | from enum import Enum
class Automaton:
"""
An automaton has three types of states: `acc`, `dead`, normal.
For a run to be accepted, it should satisfy:
G(!dead) & GF(acc)
Thus, in the automaton `dead` states has the property that they are `trap` states.
If there are no `acc` states, acc is se... |
f6f148f4868656e492c2e059ba7447dc6728cc3e | wahabtobibello/coding-challenges | /palindrome.py | 233 | 3.953125 | 4 | def is_palindrome(word):
word_len = len(word)
for i in range(word_len // 2):
if word[i] != word[word_len - i - 1]:
return False
return True
print(is_palindrome('level'))
print(is_palindrome('levels')) |
f07a39588b1aa7f5152e5d226c392037883a2630 | DincerDogan/VeriBilimi | /Python/2-)VeriManipulasyonu(NumPy&Pandas)/22-gruplama.py | 465 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 18:13:18 2020
@author: baysan
"""
# Genellikle gruplama ve toplulaştırma işlemleri bir arada kullanılır
import pandas as pd
df = pd.DataFrame({'gruplar':['A','B','C','A','B','C'],
'veri':[10,11,52,23,42,55]},
... |
4097c8f49d7b54290561a950db2f8adeb229251e | DincerDogan/VeriBilimi | /Python/2-)VeriManipulasyonu(NumPy&Pandas)/15-dataframe_olusturmak.py | 907 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 18:25:44 2020
@author: baysan
"""
# Pandas DataFrame Oluşturmak
import pandas as pd
import numpy as np
df = pd.DataFrame([1,2,45,67,879,90],columns=["degisken_adi"]) # ilk argüman hangi veriyi DataFrame'de kullanacağımız ve 2. argüman ise kol... |
7b55b2a1410f0a58b21441cb6a4e8573b348ae4d | DincerDogan/VeriBilimi | /Python/2-)VeriManipulasyonu(NumPy&Pandas)/11-matematiksel_islemler.py | 575 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 13:45:08 2020
@author: baysan
"""
import numpy as np
nd = np.arange(1,10)
print(nd*2) # tüm elemanları 2 ile çarptık
# Tabi bunun diğer matematiksel operatörler ile kullanmak da mümkündür
print(nd - 1) # tüm elemanlardan 1 çıkarttık
# ufu... |
b4769ee2822cfa377653c8def27939fd2f9f9df5 | barcelona123456/python3 | /eeree.py | 194 | 3.53125 | 4 | def baesu_sum(start, end, baesu):
hap=0
i=start
while i<=end:
if i%baesu==0:
hap=hap+i
i=i+1
return hap
print("합계:",baesu_sum(1,10,4))
|
e077b1c72ee610365cb97ee67ef6df3a09388609 | yangdissy/TDClass01 | /Lesson-2-开发环境的搭建/homework/01007-朱旭/十进制转换工具.py | 618 | 3.59375 | 4 | print('欢迎使用十进制转换器!\n')
while True:
parm = input('请输入一个整数(输入Q结束程序)\n:')
check = parm.isdigit()
if parm == 'Q' or parm == 'q':
print('\n谢谢您的使用!\n')
break
elif check != True:
print( '\n\n请输入一个整数类型!\n')
continue
num = int(parm)
parm = st... |
32358716203d93542ec747525edbf0402d745558 | madhavpalshikar/branch-cicd | /s.py | 586 | 3.59375 | 4 | def countStaircases(N):
memo = [[0 for x in range(N + 5)]
for y in range(N + 5)]
for i in range(N + 1):
for j in range (N + 1):
memo[i][j] = 0
memo[3][2] = memo[4][2] = 1
for i in range (5, N + 1) :
for j in range (2, i + 1) :
if (j == 2) :
memo[i][j] = memo[i - j][j] + 1
else... |
8c5b3fea27a70800e65b257a501d4eb91eef6b62 | peterevans/Project-Euler | /6sum-square-difference.py | 305 | 3.671875 | 4 | #!/usr/bin/env python
# encoding: utf-8
import sys
import os
def squarediff(max):
i = 0
sumsquare = 0
while i <= max:
sumsquare = sumsquare + i**2
i = i + 1
i = 0
squaresum = 0
while i <= max:
squaresum = squaresum + i
i = i + 1
return squaresum**2 - sumsquare
print squarediff(100)
|
29e06294d27ef41d9b4644924c25b8f77b8b919c | rahulgitsit/codeforces | /Petya and Strings.py | 161 | 3.859375 | 4 | line1 = input()
line2 = input()
if str.lower(line1) == str.lower(line2):
print(0)
elif str.lower(line1) > str.lower(line2):
print(1)
else:
print(-1) |
7f9b965f9bff8e93521fc37b4ccf8387acae461f | rajeevvarma16/cs101 | /lists.py | 480 | 4 | 4 | # Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.
def greatest(list_of_numbers):
greatest = 0
if len(list_of_numbers) > 0:
for elem in list_of_numbers:
... |
9ab6fc2ba3ae33bc507d257745279687926d62d2 | khushbooag4/NeoAlgo | /Python/ds/Prefix_to_postfix.py | 1,017 | 4.21875 | 4 | """
An expression is called prefix , if the operator appears in the expression before the operands. (operator operand operand)
An expression is called postfix , if the operator appears in the expression after the operands . (operand operand operator)
The program below accepts an expression in prefix and outputs the cor... |
9adc4c2e16a6468b7c39231425c0c7f2a3b6f843 | khushbooag4/NeoAlgo | /Python/ds/Sum_of_Linked_list.py | 2,015 | 4.25 | 4 | """
Program to calculate sum of linked list.
In the sum_ll function we traversed through all the functions of the linked list and calculate
the sum of every data element of every node in the linked list.
"""
# A node class
class Node:
# To create a new node
def __init__(self, data):
self.data = data
... |
ca903edb902b818cd3cda5ad5ab975f12f99d467 | khushbooag4/NeoAlgo | /Python/search/three_sum_problem.py | 2,643 | 4.15625 | 4 | """
Introduction:
Two pointer technique is an optimization technique which is a really clever way of using
brute-force to search for a particular pattern in a sorted list.
Purpose:
The code segment below solves the Three Sum Problem. We have to find a triplet out of the
given li... |
f9e6bfee3042b3a877fe84856ed539acc1c6f687 | khushbooag4/NeoAlgo | /Python/math/Sieve-of-eratosthenes.py | 980 | 4.21875 | 4 | '''
The sieve of Eratosthenes is an algorithm for finding
all prime numbers up to any given limit. It is
computationally highly efficient algorithm.
'''
def sieve_of_eratosthenes(n):
sieve = [True for i in range(n + 1)]
p = 2
while p ** 2 <= n:
if sieve[p]:
i = p * p
whil... |
8d08dac477e5b8207c351650fef30b64da52c64a | khushbooag4/NeoAlgo | /Python/math/roots_of_quadratic_equation.py | 1,544 | 4.34375 | 4 | ''''
This is the simple python code for finding the roots of quadratic equation.
Approach : Enter the values of a,b,c of the quadratic equation of the form (ax^2 bx + c )
the function quadraticRoots will calculate the Discriminant , if D is greater than 0 then it will find the roots and print them otherwise it will ... |
e88f786eb63150123d9aba3a3dd5f9309d825ca1 | khushbooag4/NeoAlgo | /Python/math/positive_decimal_to_binary.py | 876 | 4.59375 | 5 | #Function to convert a positive decimal number into its binary equivalent
'''
By using the double dabble method, append the remainder
to the list and divide the number by 2 till it is not
equal to zero
'''
def DecimalToBinary(num):
#the binary equivalent of 0 is 0000
if num == 0:
print('0000')
r... |
170fef88011fbda1f0789e132f1fadb71ebca009 | khushbooag4/NeoAlgo | /Python/cp/adjacent_elements_product.py | 811 | 4.125 | 4 | """
When given a list of integers,
we have to find the pair of adjacent
elements that have the largest product
and return that product.
"""
def MaxAdjacentProduct(intList):
max = intList[0]*intList[1]
a = 0
b = 1
for i in range(1, len(intList) - 1):
if(intList[i]*intList[i+1] > max):
... |
99f2401aa02902befcf1ecc4a60010bb8f02bc32 | khushbooag4/NeoAlgo | /Python/other/stringkth.py | 775 | 4.1875 | 4 | '''
A program to remove the kth index from a string and print the remaining string.In case the value of k
is greater than length of string then return the complete string as it is.
'''
#main function
def main():
s=input("enter a string")
k=int(input("enter the index"))
l=len(s)
#Check whether the ... |
1904bdc89188cfe9834d5a50ca780780a9c44680 | Lwq1997/leetcode-python | /primary_algorithm/array/moveZeroes.py | 972 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/4/12 21:37
# @Author : Lwq
# @File : plusOne.py
# @Software: PyCharm
"""
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
"""
class Solution:
@staticmethod
def moveZeroes(arr):
"""... |
051ee1ec695fa379fab13a5a72e9914e5773b1ef | Lwq1997/leetcode-python | /primary_algorithm/array/twoSum.py | 1,029 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/4/12 21:37
# @Author : Lwq
# @File : plusOne.py
# @Software: PyCharm
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
cl... |
787f0fa89302f42e391d89e853be6ca2b8172f77 | trancongtu550/Python4 | /lab1.py | 1,213 | 3.640625 | 4 | #Chương 3 bài 1
print(min(2,3,4))
print(max(2,(-3),7,4,5))
print(max(2,(-3),min(4,7),-5))
#Chương 3 bài 2
print(min(max(3, 4), abs(-5)))
print(abs(min(4, 6, max(2, 8))))
print(round(max(5.572, 3.258), abs(-2)))
#Chương 3 bài 3
def triple(num):
return num * 3
triple(3)
#Chương 3 bài 4
def absolute_difference(number1... |
e0a1152fc86e3c24a44baa42a4ad2cc5f0baa460 | GerardProsper/Python-Basics | /Lesson 4_10152020.py | 4,341 | 3.828125 | 4 |
##Find Longest Substring / Guessing Game - Python Basics with Sam
##sen = 'Hi Sam, nice to meet you'
##split = sen.split()
##>>> split
##['Hi', 'Sam,', 'nice', 'to', 'meet', 'you']
##
##
##comma = 'Sam,Tom,Pete,Matt'
##new = comma.split(',')
##>>> new
##['Sam', 'Tom', 'Pete', 'Matt']
##name = input("Pl... |
e45468bee33c3ba54bed011897de4c87cdf5b669 | GerardProsper/Python-Basics | /Lesson 1_10102020.py | 2,366 | 4.3125 | 4 |
## Intro to Python Livestream - Python Basics with Sam
name = 'Gerard'
####print(name)
##
##for _ in range(3):
## print(name)
##
##for i in range(1,5):
## print(i)
l_5=list(range(5))
##
##for i in range(2,10,2):
## print(i)
##for num in l_5:
## print(num)
## print... |
22d29d020b8139c01351ead5349f8a113532db32 | salonisingh-23/completePy | /speechToText.py | 415 | 3.546875 | 4 | import speech_recognition as sr
AUDIO_FILE = ("sample.wav")
r=sr.Recognition() #initialize the recognizer
with sr.AudioFile(AUDIO_FILE) as source:
audio=r.record(source)
#reads the audio file
try:
print("audio file contains "+r.recognize_google(audio))
except sr.UnknownValueError :
print("Google Speech ... |
b212b74cc8399bfaf1e38e9d03aee77cf1c1baff | kevintfrench/python | /lists3_ages.py | 232 | 4.0625 | 4 | ages=[]
age = int(input("Enter an age of a group member. Enter -1 when done")
# operators "!=" means "does not equal"
while (age != -1):
ages.append(age)
age = int(input("Enter an age of a group member. Enter -1 when done")) |
7db4fe90424179bd3c01b5c2c567b9256ed9c2d7 | asadalarma/python_crash_course | /basic_calculator.py | 158 | 4.21875 | 4 | # In this calculator we will add two numbers
num1 = input("Enter Number1: ")
num2 = input("Enter Number2: ")
result = float(num1) + float(num2)
print(result) |
571a49102f9a3ec4f8263c31ae17223662191e1f | KhalidHaji/Digital-Clock-with-Python | /clock.py | 535 | 3.578125 | 4 | from tkinter import *
from tkinter import Label, Tk
from time import strftime
root=Tk()
root.title("SAACAD")
root.geometry("350x150")
root.resizable(0,0)
text_font=("ds-digital",50)
background = "#f2e750"
foreground= "#363529"
border_width = 25
def time_clock():
string= strftime("%H:%M:%S")
... |
f5af116e98419b83db0fa3e9a155dba805773e22 | lananovikova10/learn_python_l1 | /price.py | 690 | 3.546875 | 4 |
#Создайте функцию format_price, которая принимает один аргумент price
#Приведите price к целому числу (тип int)
#Верните строку "Цена: ЧИСЛО руб."
#Вызовите функцию, передав на вход 56.24 и положите результат в переменную
#Выведите значение переменной с результатом на экран
def format_price(price):
int_price = in... |
9cc813a9c85692783780488b2a7e0bd8ad1a3546 | Veklis/Veklis | /move zeroes to left.py | 404 | 3.875 | 4 | def move_zeros_to_left(A):
if len(A) < 1:
return
lengthA = len(A)
write = lengthA - 1
read = lengthA - 1
while(read >= 0):
if A[read] != 0:
A[write] = A[read]
write -= 1
read -= 1
while(write >= 0):
A[write]=0;
write-=1
v = [1, 10, 20, 0, 59, 63, 0, 88, 0]
print("Ori... |
58100c6dc1fc24c789e2e560fc4c2b818a5d1b4b | ania4data/HTML_SQL_Webscraping | /Python/excercise/oop3_j_udemy.py | 1,119 | 3.8125 | 4 |
class Account():
'''
create an account with account ower and
initial money, capable of adding removing (conditional)
from the account
'''
def __init__(self, name, amount=0):
self.owner = name
self.amount = amount
def deposit(self, add_amount):
self.amount += add_amount
return f'Deposit Accepted'
def... |
f056f4e1ec699fb1f6ff0157f3afabae4d081dfc | Wrangler416/afs200 | /week5/lambda/lambda.py | 233 | 4.09375 | 4 | #create a function that takes one argument,
# and that argument will be multiplied with an unknown given number.
def func_compute(num):
return lambda x : x * num
result = func_compute(2)
print("Double the number =", result(30))
|
a5336ab6b2ac779752cab97aee3dcca16237a4d7 | dkrajeshwari/python | /python/prime.py | 321 | 4.25 | 4 | #program to check if a given number is prime or not
def is_prime(N):
if N<2:
return False
for i in range (2,N//2+1):
if N%i==0:
return False
return True
LB=int(input("Enter lower bound:"))
UB=int(input("Enter upper bound:"))
for i in range(LB,UB+1):
if is_prime(i):
print(i... |
a4f7aa89a626dc4c5615c2d8eab8fd8a39f77fd7 | dkrajeshwari/python | /assignment 1/fib.py | 308 | 4.03125 | 4 | def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
num = int(input("Enter the number"))
#temp=0
if num <= 0:
print("Cannot find fibonacci")
else:
print("Fibonacci series:")
for i in range(num):
#temp=fibo(i)
print(fibo(i))
|
204a83101aee7c633893d87a111785c3884829de | dkrajeshwari/python | /python/bill.py | 376 | 4.125 | 4 | #program to calculate the electric bill
#min bill 50rupee
#1-500 6rupees/unit
#501-1000 8rupees/unit
#>1000 12rupees/unit
units=int(input("Enter the number of units:"))
if units>=1 and units<=500:
rate=6
elif units>=501 and units<=1000:
rate=8
elif units>1000:
rate=12
amount=units*rate
if amount<50:
amou... |
644828ddfcfb3079cb8e429e3e6457cc9481d669 | dkrajeshwari/python | /python/sum.py | 188 | 4.03125 | 4 | #program to find the sum of series of factorial
N=int(input("Enter the number:"))
sum=0
for i in range (1,N+1):
for j in range(1,i+1):
sum+=1/i
print(f"result is {sum}")
|
6115e3eac9a36d7298c5668846494abd78dae49c | dkrajeshwari/python | /lab question/13.py | 191 | 3.859375 | 4 | def showInfo(student_dict):
for key,value in student_dict.items():
print(f"{key}:{value}")
student_dict={"ncet-ec01":"rajesh","ncet-ec02":"mahesh"}
showInfo(student_dict) |
ef9edd99d38e1c343caee4f82c1dbcadd72b1ef3 | dkrajeshwari/python | /ds/4.py | 404 | 3.859375 | 4 | def binarysearch(lst,key):
l=0
h=len(lst)-1
while l<=h:
mid=(l+h)//2
if lst[mid]==key:
return mid
elif key>lst[mid]:
l=mid+1
else:
h=mid-1
return -1
ele=20
res=binarysearch([1,2,3,4,5,6,7,8],ele)
if res==-1:
print(f... |
3481309475c25990054d95fcf8d5aa9bc8dd7fa0 | peRFectBeliever/TechNotes | /pythonNotes/samplePgms/basics/3_AllBasics.py | 158 | 3.859375 | 4 | print("Python basics - all in 1")
myInt=7
print(f'Integer value stored on myInt is : {myInt}')
myFloat1=7.0
print(myFloat1)
myFloat2=float(7)
print(myFloat2)
|
660f154a44ced73336e03755dd3e66f3a35ee152 | Wintellect/WintellectWebinars | /2017-04-06 - Pythonic Code Through 5 Examples/tip5_slots/clses.py | 346 | 3.5 | 4 | class House:
def __init__(self, beds, price, date=None):
self.date = date
self.price = price
self.beds = beds
house = House(3, 102000)
print(house.price)
house.other = "New!"
print(house.other)
print(house.__dict__)
house2 = House(5, 104000)
print(house2.__dict__)
print(id(house2.__dic... |
00a42f3e5c64d5cdc9d1dabfb1de2398e46da0df | Wintellect/WintellectWebinars | /2017-04-20-python-for-dotnet-kennedy/dungeon_game/game.py | 2,204 | 4.0625 | 4 | #! /usr/bin python3
from creature import Creature
from room import Room
def main():
print_header()
room = build_rooms()
play(room)
def print_header():
print("*" * 80)
print(" Welcome to the dungeon")
print(" Where dragons come to play")
with open('logo.txt') as fin:
text = fi... |
63b8ac0396ab073fbdc8072f82601c585d90c47a | Wintellect/WintellectWebinars | /2017-04-06 - Pythonic Code Through 5 Examples/tip3_lambdas/lambdas.py | 413 | 3.96875 | 4 | # as predicate
def find_numbers(nums, test):
lst = list()
for i in nums:
if test(i):
lst.append(i)
return lst
#
# def is_even(n):
# return n % 2 == 0
result = find_numbers([1, 2, 3, 8, 3, 2, 87, 54, 55, 88, -2, -10],
lambda n: n % 2 == 0)
print(result)
# ... |
6a92d1aa3bd84b46fa6bb4736db0a426558215b2 | talvane-lima/Cryptography | /CifradorCesar.py | 1,528 | 3.71875 | 4 | #coding: utf-8
def cifrador_cesar(texto, key=1):
texto_cifrado = ""
for n in texto:
if n < 'a' or n > 'z':
texto_cifrado += n
continue
if n == 'z':
texto_cifrado += 'a'
else:
texto_cifrado += chr(ord(n) + key)
return texto_cifrado
file = open('pt-BR.dic', 'r')
aux_dic = file.read().split("\n")
dic... |
10e72372df58c2e9aec57a9c175e0402b464144a | thinhntr/pos | /utils.py | 2,901 | 3.9375 | 4 | from typing import Collection, Iterable, List, Sized, Tuple, Union
import readline
def lcs(s1: str, s2: str, len1: int, len2: int) -> int:
"""Longest Common Subsequence using recursive method"""
if 0 in (len1, len2):
return 0
elif s1[len1 - 1] == s2[len2 - 1]:
return 1 + lcs(s1, s2, len1... |
458273bb73e4b98f097fbb87cfa531f994f55fc7 | vaishnavi59501/DemoRepo1 | /samplescript.py | 2,635 | 4.59375 | 5 | #!/bin/python3
#this scipt file contains list,tuple,dictionary and implementation of functions on list,tuple and Dictionary
#list
#list is collection of objects of different types and it is enclosed in square brackets.
li=['physics', 'chemistry', 1997, 2000]
list3 = ["a", "b", "c", "d"]
print(li[1]) #accessing first ... |
d70ecbb5a0f9044e20525c95899d8660edc77e11 | pure-escapes/FizzBuzzerAPI | /src/FizzBuzzer/testFizzBuzzer.py | 3,963 | 3.515625 | 4 | # -*- coding: utf-8 -*-
'''
Created on 22 Sep 2017
@author: Christos Tsotskas
'''
import unittest
import json
import xmlrunner
from FizzBuzzer import FizzBuzzer
class testFizzBuzzer(unittest.TestCase):
def setUp(self):
self.FizzBuzzer = FizzBuzzer()
def tearDown(self):
... |
ba69b0fe11f7c48d04be3ec552d73b265f7131ba | z3li3us/python-specialization-coursera-coding-assignments | /FILE ACCESS HARD/FAH.py | 469 | 3.59375 | 4 | #filename:mbox-short.txt
fname=input("Enter file name : ")
try:
fh=open(fname)
except:
print("WRONG FILE")
exit()
count=0
total=0
for line in fh:
line=line.rstrip()
if not line.startswith('X-DSPAM-Confidence'):
continue
count=count+1
#print(line,count)
#for x in li... |
0ea2a79b3ba2a4253f43b34e996f402ccd15020c | nachommartin/ejercicios-bucles | /ejer7.py | 346 | 3.90625 | 4 | year = int (input ("Introduce el año"))
if year > 0:
if year % 400 == 0:
print ("es bisiesto")
if year % 4 == 0:
if year % 100 == 0:
year = ("no es bisiesto")
else:
year = ("es bisiesto")
print (year)
else:
print ("no es bisiesto")
e... |
230140f32be64724d9a351c557ff853d258e7cee | lechodiman/IIC2233-Learning-Stuff | /Threads/lock_codebasics.py | 634 | 3.578125 | 4 | import time
import threading
class Value:
def __init__(self, value):
self.value = value
def deposit(balance, lock):
for i in range(100):
time.sleep(0.01)
lock.acquire()
balance.value += 1
lock.release()
def withdraw(balance, lock):
for i in range(100):
t... |
a373bb36bab20b9f5b20da3017693f0eb55f259a | lechodiman/IIC2233-Learning-Stuff | /Input Output/pickle_module.py | 415 | 3.53125 | 4 | import pickle
from linked_lists import LinkedList
# example_dict = {1: "6", 2: "2", 3: "f"}
#
# pickle_out = open('dict.pickle', 'wb')
# pickle.dump(example_dict, pickle_out)
# pickle_out.close()
pickle_in = open('dict.pickle', 'rb')
example_dict = pickle.load(pickle_in)
pickle_in.close()
my_list = LinkedList(2, 3, 4... |
c47c367fd30e78ed7c100e11b11cf2a03a63c401 | lechodiman/IIC2233-Learning-Stuff | /Simulation/ayu_9_sim.py | 3,029 | 3.609375 | 4 | import random
from collections import deque
class Jugador:
def __init__(self, id):
self.id = id
self.habilidad = random.uniform(1, 10)
self.jugados = 0
def win_vs(self, oponent):
p = random.choice([True, False])
if self.habilidad > oponent.habilidad and p:
... |
34d799a217052d39488adf4039d7f23e75dbcb48 | oscarmorrison/CodeChallenges | /30stringCompress.py | 338 | 3.796875 | 4 | string = "aaaabbbccaaa"
def compress(string):
compressed = ""
character = string[0]
count = 1
for i in range(1,len(string)):
if string[i] == character:
count += 1
else:
compressed += str(count)+character
character = string[i]
count = 1
compressed += str(count)+character
return compressed
print... |
88bacc3f7875b30717226c775557e592a790d306 | haachama/pythonPractice | /practice11.py | 459 | 3.546875 | 4 | import pandas as pd
# 題目:
# 將以下問卷資料的職業(Profession)欄位缺失值填入字串'others',更進一步將字串做編碼。 此時用什麼方式做編碼比較適合?為什麼?
q_df = pd.DataFrame([['male', 'teacher'], ['male', 'engineer'], ['female', None], ['female', 'engineer']],columns=['Sex','Profession'])
q_df = q_df.fillna('others')
a = pd.get_dummies(q_df[['Profession']])
q_df = pd... |
46d85c6a471072788ab8ec99470f0b27e9d1939d | cscosu/ctf0 | /reversing/00-di-why/pw_man.py | 1,614 | 4.125 | 4 | #!/usr/bin/env python3
import sys
KEY = b'\x7b\x36\x14\xf6\xb3\x2a\x4d\x14\x19'
SECRET = b'\x13\x59\x7a\x93\xca\x49\x22\x79\x7b'
def authenticate(password):
'''
Authenticates the user by checking the given password
'''
# Convert to the proper data type
password = password.encode()
# We... |
2aa12cdf32b8c5a527f0b6872704ed5287c829b7 | paulatoledo30/BCC325 | /definitions1.py | 1,060 | 3.765625 | 4 | class Agent():
"""
Implements the interface for an agent
"""
def __init__(self,env):
"""
Constructor for the agent class
Args:
env: a reference to an environment
"""
self.env = env
def act(self):
"""
Defines the agent action
... |
590af34c8f60677f8669c29d83830073422a75b4 | lewisc4/Song-Genre-Predictor | /Predictions/genre_predictor.py | 8,164 | 3.65625 | 4 | '''
Script to perform song genre classification based on their lyrics
'''
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import Multin... |
e4aca32ae003f3da4058cd3c0ff6ac5c59ecbf31 | KeehuanArthur/Pong-AI | /graphicstest.py | 451 | 3.75 | 4 | from graphics import *
beep = 5
def main():
print( beep )
win = GraphWin("My Circle", 500, 500)
c = Circle(Point(50,50), 10)
c.setFill('blue')
# c.draw(win)
# animation loop
x = 10
y = 10
while True:
x += 5
y += 5
# c.undraw()
j = c
j.undraw... |
8c0f814171fffa191c911d4369f9a0da1154bc1f | declarativitydotnet/declarativity | /p2_contrib/distinf/tests/runningintersection.py | 4,225 | 3.5 | 4 | #! /usr/bin/env python
# run the script:
import sys, re, os
print sys.argv
if len(sys.argv) != 2:
print 'Usage: printgraph.py <overlog output file>'
sys.exit(1)
filein = sys.argv[1]
def parse_line(line, splitter):
# print "splitter: "+splitter
temp = re.split(splitter, line)
items = re.split(',', temp[... |
8fe7382e7d05ccf1b310b1a8ea2d2abc4803da83 | anjali-patel21/Practice-python | /global.py | 460 | 3.953125 | 4 | # understanding global and local variables
a = 10 # global variable
def variables():
a = 9 # local variable
print("in function a:", a)
variables()
print("outside function a:", a)
print("---------------------------------")
# if i want to use global value of 'a' ... |
a000fa51d161f5f71bb881a4c50315489ab610db | anjali-patel21/Practice-python | /lambda.py | 303 | 3.96875 | 4 | # code to filter the values from given list and then changing those filtered values using anonymous function
nums = [5,6,2,9,8,7,10,12,5]
evens = list(filter(lambda n:n%2==0,nums))
print("filtered values: ",evens)
changevalue = list(map(lambda n:n+1,evens))
print("changed values: ",changevalue)
|
438658b5f7165211e7ec5dec55b63097c5852ede | alshore/firstCapstone | /camel.py | 527 | 4.125 | 4 | #define main function
def main():
# get input from user
# set to title case and split into array
words = raw_input("Enter text to convert: ").title().split()
# initialize results variable
camel = ""
for word in words:
# first word all lower case
if word == words[0]:
word = word.lower()
# add word to re... |
f6bbc49b11838775749c53fa20fec54990d44a5e | rodrigoschardong/Digital-Image-Processing | /png Open ( without Image Processing Libs )/image_Open.py | 4,866 | 3.5625 | 4 | """
author: Rodrigo Schardong
entity: UERGS - Universidade Estadual do Rio Grande do Sul
"""
#https://www.w3.org/TR/PNG/#8Interlace
#Libs to read file
import zlib
import numpy as np
#Libs Just to Display image and interact with them
from matplotlib import pyplot as plt
from ipywidgets import int... |
baee2ef5bb87ce680821d28324c8bb0609b7481b | mainuddin-rony/word-chain | /main.py | 1,872 | 3.6875 | 4 | import load_four_words_graph as four_words
import load_345_words_graph as words_345
import word_chain_finder as finder
def main():
graph_4_words = four_words.load_graph()
graph_345_words = words_345.load_graph()
while True:
chain_opt = raw_input("Enter 1 for 4-words chain or 2 for 345-wor... |
33735735d54ebe3842fca2fa506277e2cd529734 | georgemarshall180/Dev | /workspace/Python_Play/Shakes/words.py | 1,074 | 4.28125 | 4 | # Filename:
# Created by: George Marshall
# Created:
# Description: counts the most common words in shakespeares complete works.
import string
# start of main
def main():
fhand = open('shakes.txt') # open the file to analyzed.
counts = dict() # this is a dict to hold the words and the number of them.
... |
0a3ddca814b334c3681576934c12434bd4de02de | pyflask/uniqueIPvisitors | /redisOp.py | 819 | 3.625 | 4 |
class redisQ(object):
"""This class defines operations with redis queue which is used
to store all remote ip addresses sniffed from requests"""
def __init__(self, conn, qname=None):
self.conn = conn
if qname is None:
qname = "redis:Q"
self.queue = qname
def push(s... |
a6dcab0b8bd8c93ecc765c830d0374f6344f78d3 | BhargavKadali39/tips-to-decrease-executionTime-in-python | /using-temp.py | 393 | 3.71875 | 4 | x = 10
y = 20
temp = x
x = y
y = temp
print(x,y)
import time
start_time = time.time()
#------------------------- code area -----------------------------------------
x = 10
y = 20
temp = x
x = y
y = temp
print(x,y)
#------------------------- code area -----------------------------------------
end_time = time.time()
to... |
d85ef4cc9b3ec8018e4f060a1d5185782dcff088 | vikasb7/DS-ALGO | /same tree.py | 829 | 4.15625 | 4 | '''
Vikas Bhat
Same Tree
Type: Tree
Time Complexity: O(n)
Space Complexity: O(1)
'''
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.left=left
self.right=right
self.val=val
class main:
#Recursive
def sameTree(self,root1,root2):
if root1 and not ... |
dad225f0531069fe83292c4633c4c8edd20b54b1 | vikasb7/DS-ALGO | /Product of Array Except Self.py | 530 | 3.671875 | 4 | '''
Vikas Bhat
Product of Array Except Self
Time Complexity : O(n)
Space Complexity: O(n)
'''
class main:
def productExceptSelf(self,nums):
res = [1]
left = 1
for i in range(len(nums) - 1, 0, -1):
res.append(res[-1] * nums[i])
res=res[::-1]
for j in range(0... |
cd98de5966e85920483a3ae99ebf683c7b6a29d0 | vikasb7/DS-ALGO | /Container With Most Water.py | 528 | 3.9375 | 4 | '''
Vikas Bhat
Container With Most Water
Time Complexity: O(n)
Sapce Complexity: O(1)
'''
class main:
def maxArea(self,height):
area=1
s=0
e=len(height)-1
while s<e:
area= max(area,(e-s)*min(height[s],height[e]))
if height[s]<=height[e]:
... |
33d3ee382baddb949f25456e71547781bc195029 | eljefec/eva-didi | /python/util/average.py | 526 | 3.640625 | 4 | import collections
class AverageAccumulator:
def __init__(self, maxsize):
self.maxsize = maxsize
self.samples = collections.deque()
self.sum = 0
self.average = None
def append(self, value):
self.samples.append(value)
self.sum += value
if (len(self.sampl... |
3623a3d7e5497f9e4ce80cf559e0fdfa085c109b | Mohith22/CryptoSystem | /key_est.py | 1,438 | 4.15625 | 4 | #Diffie Helman Key Exchange
#Author : Mohith Damarapati-BTech-3rd year-NIT Surat-Computer Science
#Establishment Of Key
#Functionalities :
#1. User can initiate communication through his private key to get secretly-shared-key
#2. User can get secretly shared-key through his private key
#For Simplicity Choose -
#Pr... |
4ee114cbbacc138789cda08857a84f2a6c0ba8b4 | ryanSoftwareEngineer/algorithms | /math/1465_maximum_area_of_cake_after_cuts.py | 2,125 | 4.09375 | 4 | '''
https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/
Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut an... |
0f7446e0b925da206134a4a8448265f6bb567380 | ryanSoftwareEngineer/algorithms | /linked lists, queue, and stack/300_longest_increasing_subsequence.py | 1,462 | 3.59375 | 4 | '''
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without
hanging the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Cou... |
ddbedd13893047ab7611fe8d1b381575368680a6 | ryanSoftwareEngineer/algorithms | /arrays and matrices/49_group_anagrams.py | 1,408 | 4.15625 | 4 | '''
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically
using all the original letters exactly once.
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["... |
0dcee69f8a1fd140d89ae625308af2ae95917af5 | ryanSoftwareEngineer/algorithms | /linked lists, queue, and stack/143_reorder_list.py | 1,993 | 3.828125 | 4 | '''Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.ne... |
b3a10e7d1ff2eeaa7842ea556cbad3d4b3212f0c | ryanSoftwareEngineer/algorithms | /recursion and dynamic programming/91_decode_ways.py | 1,333 | 3.9375 | 4 | '''
https://leetcode.com/problems/decode-ways/
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there ma... |
695c0923e20fd9718ac60bc84d71d0f4279fe873 | ryanSoftwareEngineer/algorithms | /recursion and dynamic programming/45_jump_game_ii.py | 1,121 | 4.03125 | 4 | '''
Given an array of non-negative integers nums, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
You can assume that you can always reach the last index.
s... |
af6e84d7684517f18c24da101ebb998fe67ebcce | ryanSoftwareEngineer/algorithms | /arrays and matrices/57_insert_interval.py | 1,669 | 3.796875 | 4 | '''
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Bec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.