blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
82fb3eb6d76ee52e724771f34aaec8bd89adf992 | miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting | /Ejemplos_Python/05-numeros-1.py | 633 | 4.1875 | 4 | # impresion numeros enteros
print(2)
print(4)
# impresion numeros flotantes
print(2.5)
# Impresion operaciones aritmeticas
print(2 + 3)
print(8 - 4)
print(1 * 4)
print(10 / 3)
# Se expresario como 4 elevado a la 3 y su resultado es 64
print(4 ** 3)
print(3 ** 3)
# La operacion entre parentesis se ejecuta primero, y... |
19f895176da37ccce84dbc2f215d2ff2b5799a4a | hbsdev/circuits-demo | /sync/myhttp.py | 567 | 3.515625 | 4 | # Define a simple webserver .
# Answers "OK" on "/" on port 80
from circuits.web import Server, Controller
class Root(Controller):
def index(self):
"""Index Request Handler
Controller(s) expose implicitly methods as request handlers.
Request Handlers can still be customized by u... |
8e324a4aa112516f0628c6506c37a36652f3923c | rajendraboke/myrepo1 | /rock_paper_scissor.py | 1,302 | 3.9375 | 4 | list1 = ["r","p","s"]
print("Enter player1 name :")
player1 = raw_input()
print("Enter player2 name :")
player2 = raw_input()
while(True):
while(True):
print("player1 choose r,p,s : ")
player1Input = raw_input()
if(player1Input in list1):
break
else:
print("En... |
be4272e2357c18c50f38b5f01807718d629617ba | narayanareddy641/python_programs | /factorial.py | 141 | 4.0625 | 4 | def factorial(n):
return 1 if (n ==1 or n == 0) \
else n*factorial(n-1);
num = 5;
print("factorial of",num,"is", factorial(num))
|
9f9383d221cd4cdd5b8f8e3a3deb87664fed8f29 | peterj35/algorithmfun | /queue/hotPotato.py | 1,810 | 4.3125 | 4 | # Based on the children's game Hot Potato, using a Queue...
# Toss the potato 1-10 times and whoever is holding the potato is eliminated
# The last remaining person is the winner.
from queue import Queue
import random
def hotPotato(namelist):
# Instantiate a queue and insert everyone's names into it
simqueue ... |
f21db24bfd3cf47ed49b86093d1c958662666cfc | michlee1337/practice | /CTCI/c8_recurAndDp/robotGrid.py | 1,157 | 3.90625 | 4 | def robotGrid(grid, r, c):
# assume I'm given a grid of T and F
# O(rc) space
# O(rc) time
# can probably optimize this
# can you look ahead in the grid???
# check path
row = r -1
while row > 0:
col = c -1
while col > 0:
# set last cell ## could probs do this... |
a7d114cd23e1f41367e78eba97d8e094272f2b5b | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/5460.py | 281 | 3.734375 | 4 | def isTidy(num):
return sorted(str(num)) == list(str(num))
def tidify(num):
num = int(num)
while not isTidy(num):
num -= 1
return num
count = int(input())
for i in range(count):
case = input()
print("Case #" + str(i+1) + ": " + str(tidify(case)))
|
a5630fd84f543b5ca53dcf497e7cc397f72cc2fe | Searge/DiveinPython | /w_1/playground/stairs.py | 158 | 3.703125 | 4 | import sys
num_steps = sys.argv[1]
height = int(num_steps)
for step in range(1, height + 1):
space = " " * (height - step)
print(space + "#" * step)
|
f8c7cb0da429e4c9b0699ef7428fda69095a4979 | Harshilpatel134/cs5590_python_deep_learning | /lab 2/Scource/task1.py | 357 | 4.125 | 4 | st=input("enter the string:")
l=st.split(" ") ## it will split input string and store it in list
s=set(l) ## converting list in set to remove duplication
l1=list(s) ##converting set into list
l1.sort() ## apply sorting on list
ans=""
for x in l1: ##this for loop is to make the ou... |
3e62e7d2bbb5fd20ced44375644ee800fd2d391b | Ravisiswaliya/machine_learning_with_python | /Regression/Simple linear regression/simple_linear_regression1.py | 1,019 | 3.71875 | 4 | #for removing warning message
import warnings
warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")
#reading data
import pandas as pd
dataset = pd.read_csv('salary.csv')
#dividing data into x and y
x = dataset.iloc[:,0:1].values
y = dataset.iloc[:,-1:].values
#training and testing data
... |
55a31ccbd4ec9affe5b6e4dddf105820dc057c56 | timothy-mcroy/Python-Scripts | /graph.py | 1,780 | 3.5625 | 4 | """Created by Suely Oliviera
Not Timothy McRoy
"""
class Vertex:
def __init__(self,key):
self.id = key
self.connectedTo = {}
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x in se... |
e97740b2ddfd31e81d61801fef195611183aba4e | daniel-reich/turbo-robot | /QCXxnDHsfF7gtkxze_8.py | 729 | 4.09375 | 4 | """
This is a **reverse coding challenge**. Normally you're given explicit
directions with how to create a function. Here, you must generate your own
function to satisfy the relationship between the inputs and outputs.
Your task is to create a function that, when fed the inputs below, produces
the sample outputs sh... |
f597224597c0fe1cfe9de0c03cc78bca0f2b4e5c | carlodizon03/Efficient-Nets-on-Pytorch | /sparsification.py | 3,912 | 3.71875 | 4 | import math
import matplotlib.pyplot as plt
import numpy as np
def logistic( a, x, n_order = 1, X = []):
''' Logistic Function that creates a single hump
pattern using the equation:
F(X) = Xt+1 = a * Xt * (1-Xt)
This function can be used iteratively using a list of Xt
o... |
b06d55b7fec976c310f3ceb7d08e30ade71402b6 | kaushal1014/Registration | /main.py | 1,738 | 3.578125 | 4 | #By Kaushal Patil
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Resitration")
root.geometry("500x500")
text_input = StringVar()
def onclick():
messagebox.showinfo("Hello", "You have successful registered.")
username = Label(root, text="New Username", height=1).place(x=160, y=100)
... |
e359c79cd7dc617d1f468a18308b432b9d0478b4 | huiDragon81/PythonNetworkTest | /src/corutine/corutine.py | 2,211 | 3.875 | 4 |
def countdown(n):
while n > 0:
yield n
n -= 1
# 계속 이딴식으로 하면 StopIteration 익셉션이 나게 되어있음 그래서 트라이 캐치가 필요함 파이썬 개새끼야
# cnt = countdown(10);
# print (cnt.__next__());
# print (cnt.__next__());
# print (cnt.__next__());
# print (cnt.__next__());
# print (cnt.__next__());
# print (cnt.__next__());
# print... |
c4ddcef3eb80f1eda1be1c3af877f3c36fd67257 | Larissapy/aula-remota-oito | /comprimentos_1.py | 432 | 3.78125 | 4 | from random import *
print('Gerador de Cumprimentos')
print('----- ----------')
adjetivos = ['maravilhoso', 'acima da média', 'excelente', 'incrível', 'muito bom']
hobbies = ['andar de bicicleta', 'progamar', 'fazer chá', 'fazendo doces', 'idiomas' ]
nome = input("Qual o seu nome?: ")
print('Aqui está o seu cumprim... |
0f2dfcae1f3e8aa42e4800c54c564ae2f104e595 | LinLeng/xiaoxiyouran_all | /python3/201801821python3_7liaoxuefeng/unmd/tmp_pycharm_project/ch02/04.py | 757 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
filename: ch02/04.py
message: notes for liaoxuefeng in learning pyhon 3.7
'''
#
# height = 1.75
# weight = 80.5
hei = float(input('please enter your height(m):'))
wei = float(input('please enter your weight(kg):'))
bmi = wei/hei/hei
if bmi > 32:
print('您的bmi指数是%.... |
df081b0fd7590cc0c45704bd06fb650eecafc13d | asupertramp/work_repository | /work/Algorithms/Sort/Insertion/python/insertion.py | 277 | 3.765625 | 4 | def insertion_sort(n):
if len(n) == 1:
return n
b = insertion_sort(n[1:])
m = len(b)
for i in range(m):
if n[0] <= b[i]:
return b[:i]+[n[0]]+b[i:]
return b + [n[0]]
test=[10,9,8,7,6,5,4]
result=insertion_sort(test)
print result |
8f46ec61278cd58484bef398b38f27cdf832a269 | PleumSupakiart/data-structures | /sorting/radix_sort.py | 560 | 3.765625 | 4 | from collections import deque
arr = [ 1, 34, 23, 44, 2, 6 ,18]
def get_digit(number, n):
return number // 10**n % 10
def radix_sort(arr):
m = len(str(max(arr)))
queqe = deque(arr)
for nth in range(1, m+1):
d = {i: deque() for i in range(10)}
while (len(queqe) > 0):
num = queqe.popleft()
di... |
c7a2889aee706887a2c946ea878d8f65b13f04f6 | Ketan2793/movie-info-finder | /movie_rating.py | 1,494 | 3.578125 | 4 | # Import Module
from tkinter import *
from get_rating import *
# create root window
root = Tk()
# root window title and dimension
root.title("Movie Rating finder")
# Set geometry (widthxheight)
root.geometry('700x400')
lbl = Label(root, text = "Enter Movie Name")
lbl.grid()
# adding Entry Field
txt ... |
9ec85f806915ebdf01bb4bb91147a027b281d7f3 | JosevanyAmaral/Exercicios-de-Python-Resolvidos | /Exercícios/ex060.py | 301 | 4.0625 | 4 | numero = int(input('Digite um número para calcular o fatorial: '))
c = 0
fatorial = 1
print('{}! = '.format(numero), end='')
while c <= numero - 1:
print('{}'.format(numero-c), end='')
print(' x 'if c < numero - 1 else ' = ', end='')
c += 1
fatorial *= c
print('{}'.format(fatorial))
|
f542c46b71b9635a09e5969668f840252be6eb3e | aldimahardiansyah/tugasKuliah | /DDP/utsNo31.py | 256 | 3.5 | 4 | def no31(string):
vokal = "aiueo"
result = 0
for i in range(len(vokal)):
for j in range(len(string)):
if vokal[i].upper() in string[j].upper():
result = result + 1
return result
a = no31("mhj")
print(a)
|
86783386e2627a05c7e5fbf5a61ffe45046eab5e | manjeet008/Recursion_Examples-Python3- | /Factorial.py | 168 | 3.859375 | 4 | def fact(n):
if(n<=1):
return(1)
else:
return(n*fact(n-1))
num=int(input("\nEnter any digit here..."))
print("\nFactorial is -",fact(num)) |
d9817f196169d98976396974785f413bc32486e6 | ViridianaVM/ADA-Unit1-Project-Viewing-Party | /viewing_party/main.py | 6,486 | 4.03125 | 4 | #--------FUNCTIONS FOR WAVE01--------#
def create_movie(movie_title, genre, rating):
'''
This function initialize a dictionary with
title, genre and rating
'''
if not movie_title or not genre or not rating:
return None
movie_dictionary = {
"title" : movie_title,
"genre" ... |
54aee7188be7ef1f4ebbc6ce6ba34e7e8dbf7f43 | arguelloj/CFB-study | /CFB- LHEB/Chapter 1/length.py | 244 | 4.3125 | 4 | # This is a program used to calculate the length of a string.
def length(myString):
''' Computes the length of its input string.'''
counter = 0;
for myCharacter in myString:
counter = counter + 1;
return counter;
|
b241c0b6d06c68644732c11616e0bc3b5e70a3f9 | demoleas21/CrackingCodingQuestions | /src/Chapter 1/CheckPermutation.py | 1,202 | 3.65625 | 4 | """ 1.2 CheckPermutation """
from unittest import TestCase
def permCheck(stringA, stringB):
if len(stringA) != len(stringB):
return False
stringCount = {}
for val in stringA:
try:
stringCount[val] = stringCount[val] + 1
except:
stringCount[val] = 1
for... |
450870affee140da3b2bfead502f41fb173e55c2 | maydinn/clarusway_assg | /AssigmentQuestions/_01_question.py | 260 | 3.515625 | 4 | # If you had deposited a coin on the cryptocurrency exchange that brought 7% fixed profit daily for a week,
# how much would your $ 1000 reach at the end of the 7th day?
def weekly_profit(x):
return (x * 7) / 100
print(weekly_profit(1000))
a = "are"
|
a7ee1e979a336a506358ff93058c6d2c0ee1fff1 | nishio-kun/cell-automaton | /lifegame/bomb.py | 1,164 | 3.546875 | 4 | import random
#bomb
#return the explosion cell at random
def explode(field):
center = [random.randint(0,9),random.randint(0,9)] #select the cell which will be exploded
try:
field[center[0]][center[1]].newData = '*'
field[center[0]-1][center[1]].newData = '*'
field[center[0]-1][center[... |
315f943e8de47517e70bdbe219ef4d4d6636ed9f | v-antech/adventofcode | /src/main/python/day3/solution.py | 2,152 | 3.890625 | 4 | #!/usr/bin/python
from sets import Set
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self.__eq__(other)
def __has... |
8d6ff747a8d6819bf5a462abf28af7a84e17608c | LeslieWilson/python_playground | /chapter-four/cipher.py | 513 | 4.03125 | 4 |
# allow for users to input a number and a string
# have output that gives string back, shifted the input amount
def newWordchar():
userInputNum = raw_input("enter a number: ")
userInputStr = raw_input("enter a sentence: ")
chars = userInputStr.split()
indivChars = chars.split()
print indivChars
... |
2fe69716cf3dfcd090183030136378efb990b77c | refanr/2020 | /7/1b.py | 506 | 4.3125 | 4 | def find_index_of_nth_occurrence(sequence, element_to_find, occurrence):
""" Returns the location of the n-th occurrence of an element within a sequence """
# ... and the rest is up to you
if occurrence == 1:
return sequence.find(element_to_find)
elif occurrence == 3:
return sequence.rfi... |
e471ecac8b7d6e95b3fb01030299ad094c25851d | lukembalmer/Py-Junior-Year-Assignments | /cs160lab1.py | 1,685 | 3.640625 | 4 | #Luke Balmer 3/19/21 Per. 3
#Question 1:
#Loop- D
#Input- A
#Decision- B
#Process- C
#Question 2a:
#1- I = 32, J = 20
#2- I = 32, J = 20, R = 12
#3- I = 20, J = 12, R = 12
#2b- I = 20, J = 12, R = 8
#3b- I = 12, J = 8, R = 8
#2c- I = 12, J = 8, R = 4
#3c- I = 8, J = 4, R = 4
#2d- I = 8, J = 4, R = 0... |
bba938721c9b2f2e1c8081a5e0710a2e0a147707 | lbampo/airport_project | /run.py | 3,768 | 3.734375 | 4 | from flight_class import *
from people_class import *
from passengers_class import *
flight_1 = Flight('BA1465', 'Accra(Ghana)', 'London(Heathrow)', '12:45' )
flight_2 = Flight('RY1346', 'Lisbon(Portugal)', 'Lille(France)', '6:00')
flight_dict = {
'flight_1': [flight_1.flight_number, flight_1.destination, f... |
78569d94296dde41a857804f76471999ce0ca4a0 | dongsonsqtt/ITPM_07 | /test.py | 540 | 3.515625 | 4 | '''
* @author DongSon
* @email dongsonsqtt@mail.com
* @create date 2018-04-11
* @modify date 2018-04-11
* @desc test import
'''
#1324 - 1896
from BubbleSort import BbSort
from random import randint
a = []
for i in range(20):
a.append(randint(1324,1896))
'''count = 0
print("Input number to list or press Enter... |
c3a090e2536675066d17eb8fe24df7c24dfceb3d | jiajie999/funny-checkio | /Elementary/fzbuz.py | 733 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
"""
"Fizz Buzz" if the number is divisible by 3 and by 5;
"Fizz" if the number is divisible by 3;
"Buzz" if the number is divisible by 5;
The number as a string for other cases.
"""
def checkio(number):
return "Fizz Buzz" if int(num... |
23041f3f50b2ca91cef513e5487afb2f153f19a9 | Takerhythm/learning | /CLRS/sort/bubble_sort.py | 336 | 4.0625 | 4 | import random
def bubble_sort(nums):
for j in range(len(nums)-1, 0, -1):
for i in range(j):
if nums[i] > nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
if __name__ == '__main__':
nums = [random.randint(0, 1000) for i in range(10)]
print(nums)
bubble_sort(nums)... |
807ce9f69f2858f016c5c8cd3bb608a422ce8f9c | Shantanu0330/Reverse-string | /reverse_string.py | 77 | 4.125 | 4 | str = input("Enter string : ")
print(f"Reverse of your name is:{str[::-1]}")
|
4bbc141a0b0df5be5ab9270abc90474003d31f3b | muthonilucy/october_project | /variables.py | 132 | 3.75 | 4 | x = 50
name = "Lucy"
#inbuilt functions True and False
completed = False
print(name)
print("the name is "+name+" and the age is",x) |
b3679badc30d12a01bce207712b49d58003f4f60 | alicesilva/P1-Python-Problemas | /listas20.py | 851 | 3.5625 | 4 | #coding: utf-8
print "Projeção de Gastos com Abono"
print "============================"
print
salarios = []
abonos = []
cont = 0
while True:
salario = float(raw_input("Salário: "))
if salario == 0:
break
cont += 1
abono = 20 / 100.0 * salario
if abono < 100.0:
abono = 100
salarios.append(salario)
abonos.... |
ea99142906155dc1dde788b7eb91c871fd2eb176 | Pranil10/Python_Projects_2 | /rockpaperscissor.py | 1,488 | 4 | 4 | import random
import time
options=['rock','paper','scissor']
def Player1():
ch=input('enter rock or paper or scissor')
global choice1
choice1=ch.lower()
while choice1 in options:
Player2()
break
def Player2():
global choice2
if mode==0:
computer=['rock','... |
4de05d45017debdb9a8b2421e0ea52dc3b6dd2a1 | hanrick2000/algorithm-6 | /07 - Hash & Heap/M657insertDeleteGetRandom.py | 1,101 | 4.09375 | 4 | import random
class RandomizedSet:
def __init__(self):
# do intialization if necessary
self.data = set()
"""
@param: val: a value to the set
@return: true if the set did not already contain the specified element or false
"""
def insert(self, val):
# write your code her... |
3fe9fd10d63d85768299d445f65acd33388cdc7d | amanptl/LeetCode | /Medium/Pacific Atlantic Water Flow.py | 1,148 | 3.5 | 4 | def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix:
return []
self.directions = ((0,-1), (0,1), (1,0), (-1,0))
rows = len(matrix)
cols = len(matrix[0])
pacific = set()
atlantic = set()
res = []
for i in range(r... |
6033dd037619ccfb1d5a231c3660cf2c82c98fae | shengwudiyi/leetcode | /algorithms/python3/MergeIntervals.py | 796 | 3.6875 | 4 | """
Source: https://leetcode-cn.com/problems/merge-intervals/
Author: Lianfeng Shen
Date: 2018-12-19
"""
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def merge(self, intervals):
"""
:type inter... |
0b0693685474e2435ecabf1102f81ac89b0c7a02 | dhieru/LearnPython | /coursera_8.py | 230 | 3.609375 | 4 | import re
filename = raw_input("Enter the file name to open : ")
fopen = open(filename)
stringread = fopen.read()
total = 0
nums = re.findall('[0-9]+',stringread)
for num in nums:
num1 = int(num)
total = total + num1
print total |
b2b51a7fbebc8419bfbdf976cb2e2232e3288b53 | BenjaminMacNeille/nhts_test_app | /csv_to_pkl.py | 572 | 3.5 | 4 | import csv
import pickle
import pandas as pd
def make_pickle():
"""a_list = []
with open("nhts_data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
a_list.append((row[0]))
with open('nhts_data.pkl', 'wb') as output_file:
pickle.dump(a_list[0], output_file)
... |
2ad08a56932724643e9571c5ff8e3f94b32fc4c0 | KushagraK7/Python-Practice-Codes | /Python Codes/Arithmetic operations example.py | 560 | 3.78125 | 4 | A=100
B=200
C=A+B # Addition
D=A-B # Subtraction
E=A * B # Multiplication
F=B/A # Regular
G=B//A #Floor Division
H=A ** 3 # Exponential(power)
I=B ** 4
K=B % A # remainder
L=A % B # remainder
print("Sum of A and B=",C)
print("Difference of A and B=",D)
print("Product of A and B=",E)
print("Regular Divisio... |
49a03f176125d0b1b8578ee77041f32d1892a419 | ateeqmughal266/Python-Assignment | /Python Assignment1.py | 896 | 3.9375 | 4 | #%%
# TASK 1
print("Twinkle, twinkle, little star,\n \tHow I wonder what you are!\n \t\tUp above the world so high,\n \t\tLike a diamond in the sky.\nTwinkle, twinkle, little star,\n \tHow I wonder what you are!")
#%%
# TASK 2
import sys
print("Python version")
print (sys.version)
#%%
# T... |
394f931211a346803300bcf5065a292962f30cb2 | This-is-NB/CodeChef | /Turbo_Sort.py | 101 | 3.625 | 4 | l=[]
for i in range(int(input())):
l.append(int(input()))
for item in sorted(l):
print (item) |
854116d1a2b383d330c9dd5bfc5dd9998f875eff | cedriccaille/CSCI_1133 | /3rd Week/quiz03.py | 1,169 | 4.0625 | 4 |
#Problem A
def list_swap(vals, idx1, idx2):
#use a helper variable to store a value, or use this format
vals[idx1],vals[idx2] = vals[idx2],vals[idx1]
return vals
#Example 1
#print(list_swap([-12, 'carrot', '$12.57', 4.5, 9], 1, 3))
#Example 2
#print(list_swap(['A', 'B', 'C', 'D', 'E', 'F'], 2, 5))
#Proble... |
496377b4ba119d3b6f456025b138693888f53024 | KateRita/CV-lecture-quizzes-python | /2A-L1/answers/generate_gaussian_noise.py | 440 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Generate Gaussian noise
# sigma = standard deviation
sigma = 1
noise = np.random.normal(0, sigma, 1000)
histogram_count, bin_edges, ignored = plt.hist(noise, 21, density=True)
plt.show()
# TODO: Try generating other kinds of random numbers.
# How about a 2D g... |
edc1687e3f5deff51bcdb9bf15803854b88ee4ff | Jershia/Bank-ATM | /ATM.py | 882 | 3.8125 | 4 | class ATM(object):
def __init__(self,number,pin):
self.number = number
self.pin = pin
def CashWithdrawl (self,takenAmount):
amount = 85990 - takenAmount
print("Your Balance Amount is " + str(amount))
def BalanceEnquiry(self):
print("Your Balance Am... |
bfa819f2d61a1d8f470067e3eeee522477c167da | rgormley5/CodingDojo | /Python/rg_tuples.py | 469 | 3.78125 | 4 | my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
# def name(dic):
# # print dic.keys()
# newtup = ()
# for i in dic.keys():
# # print i
# newtup = newtup + (i,)
# newtup = newtup + ()
# print newtup
# name(my_dict)
def name(d... |
e14e3206b798371c1beead96d0c9af555f357dcd | kirihar2/coding-competition | /dorothy.py | 460 | 3.734375 | 4 | def travel(n):
marked = [False for i in range(n)]
moves = 0
city = 1
while False in marked:
moves += 1
if moves %2 == 0:
marked[city-1] = True
if not False in marked:
return city
count = 0
while count == 0 or marked[city... |
f77a2c65c4c89fe7fc73d733061808b55b8d1b61 | rjgonza/Lab | /python/lambda_junk.py | 336 | 3.71875 | 4 | #!/usr/bin/python
def func(x):
return x.isalnum()
seq = ["foo", "x41", "?!", "****"]
print
print "Starting list: %r" % seq
print
print "Filtered: %r" % filter(func, seq)
print
print "Using list comprehension: %r" % [ x for x in seq if x.isalnum() ]
print
print "Using lambda expression: %r" % filter(lambda x: x.isalnu... |
c1f93aee78a5129d4e1e30b7235725a9fc63b8a3 | jiuShiQi97/it3080c_scripts | /python/weatherapi.py | 383 | 3.53125 | 4 | import json
import requests
print('Please enter your city: ')
city = input()
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=%s&appid=ff49736f1e05b1054389059b3097fac3' % city)
data = r.json()
print("The weather in %s is: "%city +data['weather'][0]['description'] )
#dictionaries are in { } and use k... |
6111c6ba0af45cb83eb7254b7a01c9aabba24421 | Egor93/Climate_dynamics_and_statistics | /ex1/ex1_part_2.py | 3,668 | 3.5 | 4 |
import numpy.linalg as LA
import numpy as np
import matplotlib.pyplot as plt
class PDF:
# DESCRIPTION
# Class containing all methods necessary to generate
# two arrays of samples which have user-defined standart deviation,mean;
# correlate/do not correlate with each other according to user... |
e69c358eb70173c9128b3e9ea5bdd685b4de9ba9 | SchneiderJs/SistemasSeguros | /Exercicio 1-2/src/Questao1/Questao1.py | 2,687 | 3.671875 | 4 | import psycopg2
try:
# Cria uma conexão com o banco de dados
connection = psycopg2.connect(user = "postgres",
password = "4560",
host="localhost",
port = "5432",
database = "pg_db")
cur... |
3b20a4207c6845770a7aee4e8f2341c30c160610 | mattbruv/project-euler | /src/problem042.py | 460 | 3.625 | 4 | def charCode(char):
return ord(char) - 64
def wordToNum(word):
ns = list(map(charCode, word))
return sum(ns)
def tri(n):
return int(0.5 * n * (n + 1))
def problem42(args):
triNs = list(map(tri, range(1, 1000)))
path = args[0]
f = open(path).read().replace("\"", "").split(",")
a = wo... |
4a5f19d0bd2d31b27214f47ab109b694dfffc6b0 | jkzhao/algorithm_python | /Search_for_a_Range.py | 1,232 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
LeetCode 34.
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, ... |
f03ac82e6b4f5a7d004f604b7f71e545d65a973f | clo64/mobile-computing | /Scraper/scraper.py | 1,748 | 3.515625 | 4 | ##
# Charles Owen
# Python script for scraping PIP sensor data that has been
# saved usig the cat command.
# To direct the PIP data into a .txt file, from the
# linux CLI use the command:
#
# sudo stdbuf -o0 ./pip_sense.v2 l l | stdbuf -o0 grep TX:0$1 | cat > sensor_data.txt
# #
import time
class FileScraper()... |
caab8c5ba62762d74aaf6d6172e2f1ae575d7cac | StephenTanksley/Data-Structures | /stack/stack.py | 4,833 | 4.1875 | 4 | class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
class LinkedList:
def __init__(self, head=None, tail=None, length=0):
# Stores a node that corresponds to the first node in the list.
self.head = None
# Stores a no... |
f82d0ba63fd4922e7f28c7d3d1827eca794b5b8b | DevOpsStuff/Programming-Language | /Python/PythonTips/string_formatting.py | 297 | 3.859375 | 4 | """
1) Old-Style
>>> name = "Tesla"
>>> 'hello, %s' % name
'hello, Tesla'
2) New Style
>>> 'hello, {}'.format(name)
'hello, Tesla'
>>>
3) f'strings (python3.6+)
4) Template String
>>> from string import Template
>>> t = Template('Hey, $name')
>>> t.substitute(name=name)
'Hey, Tesla'
>>>
"""
|
2d922894f76c02ad093f3ecd6a576f02e2a16f5b | gayathriroy2/linkedlists | /spilit_into_2.py | 624 | 3.59375 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Circular:
def __init__(self):
self.head=None
def split(self,head1,head2):
fast=self.head
slow=self.head
while fast.next!=self.head and fast.next.next!=self.head:... |
4f82c94e184ab7205fb42db06c8575f488305238 | Py-Contributors/AlgorithmsAndDataStructure | /Python/Algorithms/SortingAlgorithms/Shellsort.py | 474 | 4.0625 | 4 | def shellSort(array, n):
interval = n // 2
while interval > 0:
for i in range(interval, n):
temp = array[i]
j = i
while j >= interval and array[j - interval] > temp:
array[j] = array[j - interval]
j -= interval
array[j] = ... |
e0dc412d1736e41c96b21ed7948a5c52749eaa6f | mcs07/pdfminer | /pdfminer/dumppdf.py | 9,467 | 3.515625 | 4 | #!/usr/bin/env python2
"""
dumppdf.py - dump pdf contents in XML format.
This script dumps the internal contents of a PDF file in pseudo-XML format. This program is primarily for debugging
purposes, but it's also possible to extract some meaningful contents (such as images).
Examples
$ dumppdf.py -a foo.pdf
... |
c400b0032ddf4b0e4f44e2265761c74ded07d4f2 | Gaya1858/-100daysofCode-Python | /day26-filehandling/snake.py | 1,625 | 3.65625 | 4 | '''
Snake game
this snake class will make sure all snake movements
'''
from turtle import Turtle
SEGMENTS =[(0,0),(-10,0),(-20,0)]
MOVE =10
class Snake():
def __init__(self):
self.seg =[]
for i in range(0,len(SEGMENTS)):
new_turt = Turtle()
new_turt.penup()
x_p... |
ce3c39aab1b8e04156e2356dc5198d44b114f422 | RandyJCodes/Python_Projects | /Web-Page-Generator-Project/web-page-Generator-Project.py | 2,478 | 3.8125 | 4 | # Author: Randall Jackson
# Python 3.9.5
# Tested in Win 10
#
#
# Purpose: Create an HTML page and allows the user to update the body under
# the header with anything they want to add to the body.
from tkinter import *
import tkinter as tk
import webbrowser
#Python File Write. Creates the webpage if user does not ha... |
8b5298e515915aa1ce6767c90f94a98b5e9867bb | ysk24ok/leetcode-submissions | /0463/iterative.py | 1,136 | 3.59375 | 4 | from queue import Queue
from typing import *
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 0:
continue
queue = Queue()
queue.... |
39942894f43ec9a18f63b390fdc95635ec601106 | yuridesideri/PythonCourse | /Exerc/Curso/exerc9.py | 216 | 3.859375 | 4 | val = int(input('Escolha uma valor para acessar sua tabuada: '))
print(val * 0)
print(val * 1)
print(val * 2)
print(val * 3)
print(val * 4)
print(val * 5)
print(val * 6)
print(val * 7)
print(val * 8)
print(val * 9)
|
2cc18a468faf1014b1bd1431d661d6b8ed1b0cf8 | caerbannogwhite/sypha | /python/utils.py | 414 | 3.515625 | 4 | ZERO_TOL = 1.E-20
def print_mat(mat):
print("[", end="")
for row in mat:
print("[", end="")
for e in row:
v = 0.0 if abs(e) < ZERO_TOL else e
print(f"{v:8.6f}, ", end="")
print("],")
print("]")
def print_vec(vec):
print("[", end="")
for e in vec:
... |
e507ae8431ef914b5bb551b98a631969f0c56231 | himanshu2922t/FSDP_2019 | /DAY-01/factorial.py | 252 | 3.890625 | 4 | # Facorial
"""
Created on Mon Jun 3 17:51:14 2019
@author: Himanshu Rathore
"""
# input number from keyboard
number = int(input("Enter a number >"))
# calculation of factorial
from math import factorial
print("Factorial of entered number = ",factorial(number)) |
2e627cd42cd337cc827fba2c23ebdeae06de3952 | RedL0tus/CSClassworks | /2017-11-PythonTasksII/palindrome.py | 629 | 4.1875 | 4 | #!/usr/bin/env python3
#-*- encoding:utf-8 -*-
"""Computer Science P classword finding palindrome words"""
def get_palindrome(filename):
"""Find palindrome words inside the given file"""
palindrome_list = []
file = open(filename)
for line in file:
if is_palindrome(line.strip()):
pal... |
a5fe1a3bd6bbf69b344e654a1bac4ace4c424c25 | hameditalha/NetworkSecurityCSSE512 | /Railfence.py | 659 | 3.59375 | 4 | def enc(txt):
out1 = ''
out2 = ''
count = 0
for ch in txt:
if count % 2 == 0:
out1 += ch
count += 1
count = 0
for ch in txt:
if count % 2 == 1:
out2 += ch
count += 1
return out1 + out2
def dec(txt):
count = 0
... |
e7d5aba0ea22dc13040a9b8d7e3516facd0e0147 | zndemao/PythonStudy | /note22递归.py | 416 | 3.734375 | 4 | # python 递归深度为一百层
import sys
sys.setrecursionlimit(1000) # 设置递归深度
# 非递归版本
def Factorial(n):
result = n
for i in range(1, n):
result *= i
return result
print('阶乘是', Factorial(5))
# 递归版本
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(fac... |
3be8e63b1dd82af344a55e0065464eabd74a9489 | naru380/AtCoder | /ABC/49/C/source.py | 521 | 3.8125 | 4 | S = input()
S = S[::-1]
DEBUG = False
if DEBUG:
print("S: {}".format(S))
while True:
if DEBUG:
print("S[:7]: {}".format(S[:7]))
if len(S) >= 5:
if S[:7] == "remaerd":
S = S[7:]
elif S[:6] == "resare":
S = S[6:]
elif S[:5] == "maerd" or S[:5] == "esar... |
1edf520061bcb887e5bc48b446e99e5ffd6d1925 | vamshics/Searching_Algorithm | /jumpSearch.py | 638 | 4.03125 | 4 | import math
def jumpSearch(arr, val):
length = len(arr)
jump = int(math.sqrt(length))
low, high = 0,0
while low < length and arr[low] <= val:
high = min(length - 1, low + jump)
if arr[low] <= val and arr[high] >= val:
break
low += jump
if low >= length or arr[low] > val:
return -1
high = min(length - ... |
f37188d72ded8c2f540f4a31969ef73167b1d09a | rafaelperazzo/programacao-web | /moodledata/vpl_data/28/usersdata/82/8117/submittedfiles/serie1.py | 265 | 3.65625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
n = input('Digite o valor de n:')
i=1
j=1
soma=0
while i<=n:
if (i%2==0):
soma=soma-(j/(j**2))
else:
soma=soma+(j/(j**2))
i=i+1
j=j+1
print ('%.5f' %soma)
|
af47e91bb150f6067970b718152168d2a29e8445 | NIGHTFIGHTING/python | /decrator/1.py | 480 | 3.78125 | 4 | #-*- encoding: utf8 -*-
def outer():
x = 10
def inner(): #1.inner就是内部函数
print(x) #2.外部环境的一个变量
return inner #结论:内部函数inner就是一个闭包
outer()()
f = outer()
f()
'''
闭包=函数块+定义函数时的环境
'''
def outer1(x):
def inner(): #1.inner就是内部函数
print(x) #2.外部环境的一个变量
return inner #结论:内部函数inner就是一个闭包
oute... |
9c1bbf711bd134ed9945678963479eea3e776381 | rbocchinfuso/python4everybody | /getting_started_with_python/week6/assignment_4.6.py | 1,115 | 4.34375 | 4 | ## 4.6 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of time-and-a-half in a function called computepay() and use the function to do the computation. ... |
a6687917f41c88d7a0bbbad272878f497be77caf | richherr/richherr.github.io | /data8/_build/jupyter_execute/chapters/05/1/Arrays.py | 6,106 | 3.84375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from datascience import *
path_data = '../../../assets/data/'
# # Arrays
#
# While there are many kinds of collections in Python, we will work primarily with arrays in this class. We've already seen that the `make_array` function can be used to create arrays of numbe... |
ccc839af8d04666cc8bfa2b8442247df40aa88fe | mtovmassian/funcpy | /recursion/quicksort.py | 697 | 4.125 | 4 | def quicksort(array):
def _sub_quicksort(sublists, array, pivot):
if array == []:
return sublists
head, *tail = array
if head < pivot:
sublists[0].append(head)
elif head == pivot:
sublists[1].append(head)
else:
sublists[2].appe... |
97389422820d529995fdf3be8f0bb13a4bc0a62d | tomtang110/comp9021 | /week9/Lecture_9/week9_2.py | 1,078 | 3.734375 | 4 | from stack_adt import *
from collections import defaultdict
from queue_adt import *
def tree():
return defaultdict(tree)
our_tree=tree()
our_tree[1][2][3] = None
our_tree[1][4] = None
our_tree[1][5][6][7] = None
our_tree[1][5][6][8][9] = None
our_tree[1][5][6][10] = None
our_tree[1][5][11][12] = None
our_tree[1][5... |
ad903d3647f7ff2fa6d0955653b4fe3efd256a5e | mjkhonline/python-caesar-algorithm | /encryption.py | 1,123 | 3.90625 | 4 | english_words = []
def encrypt(message, key):
message = message.lower()
key %= 26
cipher = ""
for letter in message:
if letter < 'a' or letter > 'z':
cipher += letter
else:
cipher += chr((ord(letter) + key - 97) % 26 + 97)
return cipher
def decrypt(cipher... |
61bd2bbce3236c828ac2e9766cb9c23aab7a40f2 | courtneyholcomb/oo-practice-melons | /harvest.py | 4,679 | 3.5 | 4 | ############
# Part 1 #
############
class MelonType(object):
"""A species of melon at a melon farm."""
def __init__(self, code, first_harvest, color, is_seedless, is_bestseller,
name):
"""Initialize a melon."""
self.code = code
self.first_harvest = first_harvest
... |
f7d4443a17b351eefa2e4891aa37ccc5334bf38b | MateoBacz/Python | /Day1.py | 7,893 | 3.6875 | 4 | a = 1
print (type(a))
a = "sample text"
print (type(a))
a = 1.0
print (type(a))
pi = 3.14
print (type(pi))
myChar = 'a'
print (type(myChar))
imie = "Anna"
adres_zamieszkania= "Nieznana 20"
#adres-zamieszkania = "Nieznana 20"
drugie_imię= "Beata"
#3ulubionePotrawy = "x, y, z"
#and = 51
and_Dana= 1023
And = "hello"
... |
16a6e62e2d5b399f1c7110308889fe387b7bd2e1 | MattHenao/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 166 | 3.734375 | 4 | #!/usr/bin/python3
def no_c(my_string):
none = ""
for count in my_string:
if count != 'c' and count != 'C':
none += count
return none
|
69aa638519fee3310f747abfa9b50d7c22d03860 | than0mua/python | /venv/ngay2/bai51.py | 165 | 3.625 | 4 | a=int(input("nhap vao mot so nguyen:"))
tong=0
giaithua=1
for i in range(a):
tong+=i
print (tong)
for i in range(1,a+1):
giaithua=giaithua*i
print (giaithua) |
522ff9f234ec5d985ce761e66e543f64581c953a | zsmountain/lintcode | /python/dfs/1360_symmetric_tree.py | 1,506 | 4.28125 | 4 | '''
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Have you met this question in a real interview?
Example
Example1
Input: {1,2,2,3,4,4,3}
Output: true
Explanation:
1
/ \
2 2
/ \ / \
3 4 4 3
This binary tree {1,2,2,3,4,4,3} is symmetric
Example2
Input: ... |
c0027fa460af0cf7e667933b7421cec043ec4fd3 | arun-thekkuden/project-euler | /problems/problem_010.py | 468 | 3.875 | 4 | """
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
from problem_007 import is_prime
import time
def summation_of_primes():
total = 0
value = 2
while value < 2000000:
if is_prime(value):
total += value
value += 1
... |
3ae5e6372914a096ef5c244edf03df5416ddb7ae | ronald0807/Running-python | /python_if_statement_practice1/문제7.py | 421 | 3.828125 | 4 |
# 문제 7.
# 3개의 정수를 입력받아 조건문을 이용하여 입력받은 수들 중 최소값을 출력하는 프로그램을 작성하시오.
# 입력 예: 18 -5 10
# 출력 예: -5
A = int(input("정수를 입력하시오."))
B = int(input("정수를 입력하시오."))
C = int(input("정수를 입력하시오."))
if A>C and B>C :
print(C)
elif B > A and C > A :
print(A)
else :
print(B)
|
39acda317a6ee249f04ba60677b24061dab9d3ff | zaBogdan/BasicAPI | /create_table.py | 346 | 3.59375 | 4 | import sqlite3
con = sqlite3.connect('database.db')
curs = con.cursor()
user = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username varchar(50),password varchar(100))"
item = "CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name varchar(25), price real)"
curs.execute(user)
curs.execute(item)... |
6d6787b157468e69093d6365f24012f87cedc990 | shivaninayakam/pycbit-hackathon | /7_palindrome.py | 194 | 3.953125 | 4 | i=0
flag=0
s1=input("enter string")
n=len(s1)
for i in range(1,n):
if(s1[i]!=s1[n-i-1]):
flag=1
break
if(flag==1):
print("string is not palindrome")
else:
print("string is palindrome")
|
f8d852d0badcf6463ca3db13e45d9b1b93b57dfd | eltonlaw/impyute | /impyute/contrib/count_missing.py | 742 | 3.53125 | 4 | """ impyute.contrib.count_missing.py """
import numpy as np
from impyute.ops import matrix
def count_missing(data):
""" Calculate the total percentage of missing values and also the
percentage in each column.
Parameters
----------
data: np.array
Data to impute.
Returns
-------
... |
6d6a4af726459f0a472526c8ae82538efda580b0 | linhuaxin93/LearnPython | /超星试卷处理/demo03.py | 545 | 3.5625 | 4 | import os
from docx import Document
#要读取的文件的上层文件夹路径
document = Document("C:/Users/萝卜ovo/Desktop/Python/超星试卷处理/西方经济学答案汇总.docx")
number = ['1','2','3','4','5','6','7','8','9']
with open('整理.txt','w') as f :
f.write("")
def printdocumet():
for para in document.paragraphs:
with open('整理.txt','a',enc... |
1adbd512d5b9b6c9d967ed9a569e96b4090a1da5 | sahiti0707/Python_Learning | /69.py | 108 | 4.1875 | 4 | fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
# "Reverse" command reverses the list
|
af71ec357e3e8509f9e8afb0e51d5d437062c4f3 | uabua/rosalind | /bioinformatics-stronghold/finding-a-spliced-motif/sseq.py | 1,072 | 3.65625 | 4 | """
ID: SSEQ
Title: Finding a Spliced Motif
URL: http://rosalind.info/problems/sseq/
"""
def fasta_file_parser(fasta_file_path):
"""
Parses Fasta files.
Args:
fasta_file_path {str}: path of Fasta file
Returns:
list: list of dnas
"""
with open(fasta_file_path, 'r') as f... |
f278f25e669d96b584e7489fdc732a57bb9c123e | devsungmin/Algorithm-Python | /Programmers/Level2/가장_큰수.py | 301 | 3.578125 | 4 | # 다시 한번 풀어 보기!!
# lambda식을 사용 할 것!
# x*3을 사용하는 이유는 numbers의 조건이 1000이하이기 때문에 사용
def solution(numbers):
numbers = list(map(str, numbers))
numbers.sort(key = lambda x: x*3, reverse=True)
return str(int(''.join(numbers)))
|
679dff78d1cbd2323d54242aeb0cee8156ff1de9 | yajurahuja/QuantumCGT | /Qtictactoe/player_c.py | 899 | 3.734375 | 4 | from graphics import *
from qiskit import *
from sys import*
import numpy as np
class player:
def __init__(self, number, game):
self.player_number = number
self.game = game
def move(self):
print("Please input as box number(1-9) probability(0-1) and press enter. type d and press enter to end turn.")
box_... |
561bf50245231382f202da5ea3be89fddb215314 | BrandenMillward/Projects | /Linear_Regression_Predict_student_grades.py | 1,255 | 4 | 4 | # basic linear regression model to predict students grades
import pandas as pd
import numpy as np
import sklearn
from sklearn import linear_model
# source of the data set https://archive.ics.uci.edu/ml/datasets/Student+Performance
df = pd.read_csv("student-mat.csv", sep=";")
print(df.head())
# limit to th... |
412c467c12d4aa3c5ae876f8bccbfbe43c6c2422 | rbtreesoft/python | /24-month.py | 220 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
months="JanFebMarAprMayJunJulAugSepOctNovDec"
n=input("请输入月份数(1-12):")
pos=(int(n)-1) * 3
monthAbbrev=months[pos:pos+3]
print("月份简写是"+monthAbbrev+".") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.