blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0f93b3d44b227bfde3335a4084ea6f391ab7623b | devansh5/DSA | /Sorting/bubblesort.py | 393 | 3.6875 | 4 | def bubblesort(a,n):
for i in range(n-1):
flag=False
for j in range(n-1):
if a[j]>a[j+1]:
flag=True
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
if flag==False:
break
return arr
n=int(input())
... |
3110cbca7fde295570a8494efb17a9f435b712cc | huigefly/Python | /design/singleton/2.py | 669 | 3.6875 | 4 | class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '__instance'):
print('before new')
print(cls)
cls.__instance = object.__new__(cls, *args, **kwargs)
print('after new')
cls.__instance.__Singleton_Init__(*args, *... |
4b4da8845c0d68d9aa8eca1662b339ae7d81da9f | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/278/82056/submittedfiles/testes.py | 253 | 3.5625 | 4 | x1 = 0
x2 = 100
soma = 0
x1+=1
while (x1<=x2):
if x1%2==0:
soma+=x1
x1+=1
print("%.d" %(soma))
print("\n")
x1=0
x2=100
soma=0
while (true):
x1+=1
if x1>=x2:
break
if x1%2==0:
soma+=x1
print("%.d" %(soma))
|
f137e1d39b78906968d106ab0b5a0395a98a2bcf | mmrraju/Coding-interview-preparation | /Linked Lists/04_Remove_linkedList_elements.py | 1,198 | 3.734375 | 4 | """Given the head of a linked list and an integer val, remove all the nodes of
the linked list that has Node.val == val, and return the new head."""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def p... |
98e6b2e7253df153b9c5078c11e52477ef9c6c33 | habroptilus/AOJ | /v0/v001/0012.py | 2,478 | 3.625 | 4 | class vector(object):
def __init__(self,a,b):
self.x=b.x-a.x
self.y=b.y-a.y
@staticmethod
def cross_product(a,b):
return a.x*b.y-a.y*b.x
class vertex(object):
def __init__(self,a):
self.x=a[0]
self.y=a[1]
class circle(object):
def __init__(self,p,r):
s... |
24b81a3cde65d168b270a31bf400833882bcdb98 | himanshu98-git/python_notes | /whle lup.py | 1,672 | 4.03125 | 4 | #while loop....
#while loops depend on the condtion. when condition false then while loop is terminated it doesnt give any output
"""
x=1
while x<5:
print("hello",x)
x+=1
print("terminated")
"""
"""
x=0
while x<5:
print("hello",x)
x+=1
print("terminated")
x=1
while x<=10:
x+=1
... |
e51c8077dcc79f81db29bfd1e1999cbd60f20298 | arnabid/QA | /utility/combinations.py | 546 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 13 20:08:29 2017
@author: arnab
"""
"""
generate all 2^n combinations
"""
def comb1(s):
comb1Util("", s)
def comb1Util(prefix, s):
print (prefix)
for i in range(len(s)):
comb1Util(prefix + s[i], s[i+1:])
def comb2(s, k):
comb2Util("", s, k)
de... |
f200e60af34002ef61d9d5c3ec2d4a420a2863d7 | camilaffonseca/Learning_Python | /Prática/ex012.py | 256 | 3.578125 | 4 | # coding: utf-8
# Aluguel de carros
distancia = float(input('Distância percorrida em Km: '))
dias = int(input('Quantos dias alugados? '))
preço = (0.15 * distancia) + (60 * dias)
print(f'O valor total a pagar por {dias} dias e {distancia}Km é de R${preço}')
|
fde3087ee2c8cd47bab8f3e80933aefbdcd69ff7 | gerglion/aoc2020 | /day01/solution.py | 1,567 | 3.890625 | 4 | #!/usr/local/bin/python3
import sys
num_list = []
def read_file(inputfile):
f = open(inputfile,"r")
for x in f:
num_list.append(int(x))
f.close()
def find_goal_sum1(goal):
ans = 0
for big in num_list:
for small in num_list[:0:-1]:
if big + small == goal:
... |
fa04afa4528ce26dd9cc5682410de9fb6b47ae7e | gjq91459/mycourse | /Scientific Python/Numpy/06.basic-functions.py | 755 | 3.859375 | 4 | ############################################################
#
# basic functions
#
############################################################
import numpy as np
np.set_printoptions(precision=3)
a = np.array( np.random.random(12) * 100, dtype="int" ).reshape(3,4)
print a
# perform operations along ... |
15b738ff17b198389fa84dc497795e78a5675ee5 | GabrielF9/estudo-tecnologias | /python/bin2dec/bin2dec.py | 468 | 3.703125 | 4 | # Using normal multiplication logic
def bin2dec_v1(_bin):
decimal = 0
count = 0
for b in _bin[::-1]:
decimal += int(b)*(2**count)
count += 1
return decimal
# Using the same logic but with list comprehension
def bin2dec_v2(_bin):
return sum([2**i for i in range(len(_bin)) if int(_bin[::-1][i]) == ... |
7906f29c66c30989aa611eb81cc39e2648aef928 | saji021198/set-10 | /recursively.py | 125 | 3.5625 | 4 | N=int(input())
while(N>0):
if (N%2)!=0:
print(N)
break
else:
N=N//2
|
4150b5a5f0cbf1398ff139eb485d65af9aefd229 | alpha4408/Find-mean-and-mode | /find mean and mode of a list.py | 774 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # **Find mean and mode of a list of numbers **
# In[31]:
"""
Find mean and mode of a list of numbers
"""
import statistics
class math_cal:
def __init__(self,listNumber):
self.listNumber = listNumber
def mean_list(self,listNumber):
total = 0
... |
c01b712ed26c7f2cfe1acbc5bb1d00c000a8766e | MiyamonY/quick-python | /chap3/chap3.py | 4,965 | 4 | 4 | # /usr/bin/env python3
# -*- coding:utf-8 -*-
x = 5 + 2 - 3 * 2
print(x)
# 割り算
print(5 / 2)
# 切り捨て
print(5 // 2)
# 余り
print(5 % 2)
print(2 ** 8)
print(1000000001 ** 3)
print(4.3 ** 2.4)
print(3.5e30 * 2.77e45)
print(10000000001.0 ** 3)
print((3+2j) ** (2+3j))
x= (3 + 2j) * (4 + 9j)
print(x)
print(x.real,... |
1a2dc5cc1765e76d372274dd7b79f1024ab096f9 | george39/hackpython | /modulos/modulo_calculadora.py | 402 | 3.671875 | 4 | #!/usr/bin/env python
#_*_ coding: utf8 _*_
def sumar(valor1, valor2):
print("La suma es: {}".format(valor1 + valor2) )
def restar(valor1, valor2):
print("La resta es: {}".format(valor1 - valor2) )
def dividir(valor1, valor2):
print("La division es: {}".format(valor1 / valor2) )
def multiplicar(val... |
c9521baef0ef69641e8dd3798ba552b7c403b5e2 | yoyocheknow/leetcode_python | /150_Evaluate_Reverse_Polish_Notation.py | 1,196 | 3.546875 | 4 | # -*- coding:utf-8 -*-
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack=[]
while(tokens):
t=tokens.pop(0)
if t=='+':
operator1=stack.pop()
operator2=stack.pop(... |
a0f32433b8a4e63eb530e28fb60894be9847657d | doguhanyeke/30dayChallenge | /day2.py | 839 | 3.5 | 4 | import math
class Solution:
def isHappy(self, n: int) -> bool:
def is_one(num: int) -> bool:
str_num = str(num)
# print(str_num)
sum_num = 0
for i in str_num:
# print(i)
sum_num += int(i)
return sum_num == 1
... |
1595a26a907b6a2ec61ed4c05a82c89b56bbc3ee | Miesvanderlippe/ISCRIP | /Oplevering 2/palindroom-s1096607-ifict-poging1.py | 706 | 4.09375 | 4 | import math
def is_palindrome(word: str) -> bool:
# Word length
word_length = len(word)
# Half word length, floored. This ensures middle character isn't checked
# if the word is of uneven length
half_length = math.floor(word_length / 2)
# First half of the word
first_half = word[0:half_leng... |
da00c15c1b70bb29a68798d126d19b711fb94296 | mmueller/project-euler | /p56.py | 699 | 4.125 | 4 | #!/usr/bin/env python
"""
A googol (10^100) is a massive number: one followed by one-hundred zeros;
100^100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, a^b, where a, b < 100, what is the
m... |
a0a8500d2a300552c18cc18e428039e3e2cb2863 | Presac/Tic-Tac-Toe | /Players.py | 8,073 | 3.9375 | 4 | from random import randint, choice
from collections import Counter
from Board import Board
# Player class for saving name and which sign to use
class Player():
def __init__(self, name, sign):
"""
Initialize a human player
:param name: the name of the player
:param sign: the sign t... |
44a9a4ecd2307690023fa09d7f3de589d509d2b2 | MHuang2001/COMP3308 | /Assignment 1/src/ThreeDigits.py | 11,259 | 3.71875 | 4 |
import re
import sys
import numpy as np
import math
def main():
alg = sys.argv[1]
with open(sys.argv[2]) as f:
lines = f.read().splitlines()
if len(lines) == 2 or len(lines) == 3:
start = lines[0]
goal = lines[1]
forbids = []
if len(lines) == ... |
f4eebbc8456bc699865bb6a034274c7b20e0f0d3 | gustavomarquezinho/python | /study/w3resource/exercises/python-basic/001 - 030/python-basic - 022.py | 193 | 3.71875 | 4 | # 022 - Write a Python program to count the number 4 in a given list.
def fourCount(pNumbers):
return pNumbers.count(4)
print(fourCount([1, 2, 9, 4, 3, 4]), fourCount([4, 2, 3, 4, 4, 0])) |
49049727ef4674de6d27290fc04ba181d6745b54 | SenpaiKirigaia/Laboratory-work-1-sem | /Turtle 1/Turtle11.py | 194 | 3.609375 | 4 | import turtle as t
a = 10
t.speed(10)
t.setheading(90)
for i in range(5):
for i in range(36):
t.forward(a)
t.left(10)
for i in range(36):
t.forward(a)
t.right(10)
a = a+1
|
1c19ff205574964d06f4c7786fa625e3f074d2fe | scantwell/cs_fundementals | /algorithms/mergesort.py | 946 | 4.28125 | 4 | #!/usr/bin/python
def mergesort(_list):
if len(_list) < 2:
return _list
mid = len(_list)/2
left, right = _list[:mid], _list[mid:]
mergesort(left)
mergesort(right)
merge(left, right, _list)
def merge(left, right, _list):
nleft = len(left)
nright = len(right)
i = j = k = 0
while i < nleft and j < nright:
... |
c28b57b9fc871f7dddac8179dd0466b0c7fdb8c8 | maxweldsouza/rosalind | /solutions/lexf.py | 140 | 3.875 | 4 | from itertools import product
def lexf(symbols, n):
for x in product(symbols, repeat=n):
print ''.join(x)
lexf('ABCDEFGH', 3)
|
b8776d2c4534962ae1e9e529c36e8a5389d2d0f2 | adnanjaber/Money-Change | /MoneyChange.py | 548 | 4.125 | 4 | number = int(input("Enter the Amount of Israeli money you want:"))
s = {1, 2, 5, 10, 20, 50, 100, 200}
#this function finds the biggest number that is smaller than the input number
def find_biggest(s, number):
result = 0
for k in s:
if k > result and k <= number:
result = k
ret... |
ec05336e93cc1398b506f06b4a4ff92584e8e0de | ivankonatar/SP-Homework05 | /T2.py | 1,449 | 4.65625 | 5 | """ T2. Write a Python program that can simulate a simple calculator, using the console as the
exclusive input and output device. That is, each input to the calculator, be it a number, like
12.34 or 1034, or an operator, like + or =, can be done on a separate line. After each such input,
you should output t... |
c20caf370d194b9662c07e2a956fabc729cc6e50 | tapsevarg/1st-Semester | /Session 11/Activity 5 v2.py | 1,764 | 3.921875 | 4 | # This is an automated Monty Hall problem solver
import random
def hide_prize(doors):
prize = random.choice(doors)
return prize
def generate_choice(doors):
choice = random.choice(doors)
return choice
def test_samples1():
winners1 = 0
doors1 = ["door 1", "door 2", "door 3"]
for count1... |
b080ccfcb5b7365337766af7d64bf1cd1182ce5b | dmitryokh/python | /ДЗ-5. Функции и рекурсия/X. Только квадраты.py | 364 | 3.6875 | 4 | from math import sqrt
count = 0
def backsq(a):
if int(a) != 0:
a = int(input())
backsq(a)
if sqrt(a) == int(sqrt(a)) and a != 0:
count += 1
print(a, " ", sep="", end="")
a1 = int(input())
a = a1
backsq(a)
if sqrt(a1) == int(sqrt(a1)):
print(a1)
count += 1
p... |
e7cd674d1044aa3f6e994731d5de37cc3850df47 | itsolutionscorp/AutoStyle-Clustering | /assignments/python/wc/src/510.py | 297 | 3.578125 | 4 | def word_count(prompt):
wordArray = prompt.split()
wordCount = {}
for word in wordArray:
currentValue = 0
try:
currentValue = wordCount[word]
except:
pass
wordCount.update({word: currentValue + 1})
return wordCount
|
9c6b04513e8ac673ef1365bd3d8de1ccba8d5716 | Em3raud3/leetcode | /932_beautiful_array.py | 850 | 3.578125 | 4 | class Solution:
def beautifulArray(self, n: int) -> List[int]:
permutation = list()
i = 0
while len(permutation) != n:
if i == 0:
permutation = [1]
else:
for num in range(len(permutation)):
if num == 0:
... |
20e2c57db181e2d637e5b671446543abc7215cae | inyong37/Study | /V. Algorithm/i. Book/모두의 알고리즘 with 파이썬/Chapter 3.py | 500 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# Modified Author: Inyong Hwang (inyong1020@gmail.com)
# Date: *-*-*-*
# 모두의 알고리즘 with 파이썬
# Chapter 3. 동명이인 찾기 1
def find_same_name(a):
n = len(a)
result = set()
for i in range(0, n - 1):
for j in range(i + 1, n):
if a[i] == a[j]:
result.add(a[i... |
b3856816dff7100af669490f1c3c48a4a6b7c9b1 | dstch/my_leetcode | /Depth-first Search/Max Area of Island.py | 1,725 | 4 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: dstch
@license: (C) Copyright 2013-2019, Regulus Tech.
@contact: dstch@163.com
@file: Max Area of Island.py
@time: 2019/9/19 17:16
@desc: Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizo... |
199b9af6aa153ac7438af45e31ad3c9aca05c19f | AliciaVilchez/t06_Vilchez_Orlandini | /chambergo/Simple2.py | 318 | 3.515625 | 4 | #Programa 02
import os
usuario,cant_de_horas_por_dia="",0
#INPUT VIA OS
usuario=os.sys.argv[1]
cant_de_horas_por_dia=int(os.sys.argv[2])
#PROCESSING
#Si el numero de horas supera 12, mostrar "adiccion a las redes sociales"
if(cant_de_horas_por_dia > 12 ):
print(usuario, "adiccion a las redes sociales")
#fin_if
|
c7c24292fc473079cf9065adeacabed3b27efbe1 | nic0mp/rangers75_prework | /python-prework/test2.py | 2,124 | 4.15625 | 4 | # def hello_name(user_name):
# print("hello " + user_name + "!")
# hello_name("Chunks")
#Question 2
# Print first 100 odd numbers between 1 and 100 in Python.
# odd_numbers = list(range(1,100,2))
# print(odd_numbers) MY ANSWER
#print all odd numbers bet 1 and 100
# def add100():
# print([value for value i... |
95f4dd028dd850790f618864393fbe45b880bad0 | AbdulMohamed1994/temperature-converter | /main.py | 2,013 | 3.609375 | 4 | from tkinter import *
import tkinter as tk
#defin formular
def convert_C():
if E1:
fahrenheit = float(E1.get())
celcius = (fahrenheit-32)*5/9
result_entry.insert(0, celcius)
def convert_F():
if E2:
celcius = float(E2.get())
fahrenheit = (celcius*9/5)+32
result_en... |
fa8dd2018d7a7bf519244d1a3fe121d558c1e462 | dartmouth-pbs/psyc161-hw-factorial | /factorial.py | 706 | 3.671875 | 4 | #!/usr/bin/env python
"""Module for estimation of factorial (Homework #1)
Note: this is just a skeleton for you to work with. But it already
has some "bugs" you need to catch and fix.
"""
def factorial(n):
# TODO Define your logic for factorial here
return # TODO!
def test_factorial():
assert f... |
7839dff1009ecac3a6053ec5cf2363dd83d4343f | Saquib472/Innomatics-Tasks | /Task 3(Python Maths)/04_Power_MODPower.py | 364 | 4.03125 | 4 | # Task_3 Q_4:
# You are given three integers: a, b, and m. Print two lines.
# On the first line, print the result of pow(a,b). On the second line, print the result of pow(a,b,m).
# Input Format
# The first line contains , the second line contains , and the third line contains .
a = int(input())
b = int(input())
m = in... |
42b70291ce8192abae69d711feee3ecb2524bca7 | edmanolusanya/second-trial | /numberGame.py | 320 | 3.84375 | 4 |
def MyNumber():
count = 0
for i in range(0,100):
count += 1
print(count)
if(i % 3 == 0):
print("fizz")
elif(i % 5 == 0):
print("buzz")
elif(i % 3 == 0 and i % 5 == 0):
print("fizzbuzz")
MyNumber()
|
cba5f1216a756b1c00a8a6a99206968ed4901846 | JyotshnaReddyE/PythonAssignments | /Task 1/Question1.py | 205 | 4.0625 | 4 | #1. Create three variables in a single line and assign values to them in such a manner that each one of them belongs to a different data type.
a , b , c = 1, 2.01, "string"
print(a)
print(b)
print(c) |
8c164a41219dd43790f85017d34e9f8f5f5b7c3e | Aaryan-R-S/Python-Tutorials | /Tutorials/18break&cont.py | 320 | 3.84375 | 4 | i = 0
# Forever loop
while (True) :
if (i<=10) :
i = i+1
continue #don't leave the loop & don't read the code written in loop (after this)
print(i, end=' ')
i = i+1
if (i==45) :
break #leave the loop without reading code written in loop (after this)
print(i)
print('Stopped!') |
e30641e2500efdb928f97f57e9028efd0229eb17 | Aasthaengg/IBMdataset | /Python_codes/p03502/s794608193.py | 108 | 3.515625 | 4 | a=input()
b=int(a)
s=0
for i in range(len(a)):
s=s+int(a[i])
if b%s==0:
print("Yes")
else:
print("No") |
4b5cec40981bc80ec799091cbb87f18eb54dac43 | nathanwbrei/SquareTubeTangle | /lsys.py | 2,001 | 3.9375 | 4 | from random import random
class LSystem(object):
""" Implements a Lindenmeyer System. """
def __init__(self, alphabet, axiom, rules, depth):
"""
alphabet: {'A' : func_a, 'B' : func_b, ...}
A dictionary mapping each symbol to a callback, e.g. for graphics.
axiom: 'AB...... |
3e76148525270936f8e00c4bc6882c8cbc428bc1 | lj72808up/ML_Handcraft | /preproccess/HandleDatasets.py | 4,191 | 3.65625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
def getDataset():
data = pd.read_csv("../../datasets/census.csv")
#print(data.shape)
# 将数据切分成特征和对应的标签
# income 列是我们需要的标签,记录一个人的年收入是否高于50K。 因此我们应该把他从数据中剥离出来,单独存放。
income_raw = data['income']
features_raw = data.drop('income',axis=1)... |
d205f3ed1c61da5be38703fb348a5c3827f45049 | thecodingsophist/algorithms | /calc_fib.py | 1,110 | 3.953125 | 4 | # Uses python3
def calc_fib(n):
if (n <= 1):
return n
return calc_fib(n - 1) + calc_fib(n - 2)
def calc_fib_matrices(n):
# this method uses matrix exponentiation, where a is the matrix
# [[1,1], [1,0]] and n is the nth fibonacci number
fib = [[1,1],
[1,0]]
mul = [[1,1],
... |
f55ac58271fc05faa9eefcc3daefe77a8d0f011c | dal07065/CS10 | /Final Review/cards (dictionary).py | 2,228 | 3.75 | 4 | import random
deck = ['Spades', 'Clubs', 'Diamonds', 'Hearts']
def create_deck()->dict:
#dictionary = {'Ace of Spades':1, '2 of Spades':2, '3 of Spades':3
global deck
cards = {}
for deckType in deck:
for i in range(1, 14):
if i == 1:
string = "Ace" + " of " + deckT... |
dfdc47ad4235b712f3651100345ffe55ae47bd17 | funofzl/MyArgParse | /zipexplore.py | 2,810 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
import argparse
import string
import threading
import zipfile
import os
#读取参数
parser = argparse.ArgumentParser(description='Here is the help!')
parser.add_argument('-i','--input',required=True, type=argparse.FileType('r'),dest='input_file', help='the zip-file you \'d like to exp... |
ea717157f309433f8fc9ba9c50b15d96cb32a352 | 106070020/hw4 | /hw04-functions-106070020-master/hw4_gcd.py | 286 | 3.84375 | 4 | # -*- coding: utf-8 -*-
def compute_gcd(a,b):
while(b!=0):
c=a%b
a=b
b=c
return a
while True:
break
a = int(input("輸入第一個數字: "))
b = int(input("輸入第二個數字: "))
print(a, '和', b, '的最大公因數是', compute_gcd(a, b))
|
c5d635c16ce931e18d0078c62176044aba701f05 | zenovy/nand2tetris-vm | /VMTypes.py | 859 | 3.546875 | 4 | from enum import Enum
class CommandType(Enum):
ADD = "add"
SUB = "sub"
NEG = "neg"
EQ = "eq"
GT = "gt"
LT = "lt"
AND = "and"
OR = "or"
NOT = "not"
PUSH = "push"
POP = "pop"
LABEL = "label"
GOTO = "goto"
IF_GOTO = "if-goto"
FUNCTION = "function"
RETURN = ... |
ef5dfa8df1e62089c3110a90f218f488ca1f013a | lemeryb/yahtzee | /Yahtzee.py | 3,095 | 4.34375 | 4 | # Sam and Ben
# Yahtzee
import random as rand
# Sets a variable which tells the user how many times they've tried to roll the dice for the section they've decided to persue. (Ex: They rolled it once, they rolled it twice, now three times)
attempts = 0
# Sets a variable which is used for the program to discern how man... |
73e41a5e5ed370ef26ee2e3c6249db68c1d78dd3 | rubens17rodrigues/alien_invasion | /ship.py | 2,118 | 3.90625 | 4 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""Classe para armazenar as informações da nave"""
def __init__(self, ai_settings, screen):
"""Inicializa a espaçonave e define sua posição inicial."""
super(Ship, self).__init__()
self.screen = screen
self.ai_se... |
666e3f2ad8f8601e658f4aadb51bc038815c6696 | TimeMachine00/practicePy | /ghijp1/array asking user, search and give index.py | 319 | 3.84375 | 4 | from array import *
vals=array('i',[])
n = int(input('enter the length of a array'))
for i in range(n):
x=int(input('enter next value'))
vals.append(x)
print(vals)
search=int(input('enter val for search'))
k=0
for e in vals:
if e==search:
print(k)
break
k+=1
print(vals.index(search)) |
976dc59932f7f10fa7e4ef2ce65302fd6e11583e | saikiranmadimi/ctci | /icake/reverse_string_in_place.py | 327 | 3.890625 | 4 | def reverse_string(s):
s = list(s)
s = s[::-1]
s = ''.join(s)
return s
# print reverse_string('hello')
# T: O(n), S: O(1)
def reverse_string(s):
s = list(s)
# left pointer
l = 0
# right pointer
r = len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return ''.join(s)
print reverse_string('h... |
1020f200857aef084ffd366a0f5d40ba9a065ceb | Rushi21-kesh/30DayOfPython | /Day-4/Day_4_Adnan_Samol.py | 267 | 3.984375 | 4 | # Day-4
stars = int(input("Enter the row to display:"))
def draw(stars):
starCount = 0
for i in range(0, stars+1):
for j in range(0, i):
print("*", end='')
starCount += 1
print("")
print(starCount)
draw(stars)
|
a28241c4d7c7e9530980ee1b404393e341568c9c | OnlyBelter/machine-learning-note | /probability_basic/LLN_and_CLT/LLN.py | 1,200 | 3.71875 | 4 | import random
import matplotlib.pyplot as plt
def flip_plot(min_exp, max_exp):
"""
Assumes min_exp and min_exp positive integers; min_exp < max_exp
Plots results of 2**min_exp to 2**max_exp coin flips
抛硬币的次数为2的min_exp次方到2的max_exp次方
一共进行了 2**max_exp - 2**min_exp 轮实验,每轮实验抛硬币次数逐渐增加
"""
ratio... |
45d57a91c5fa6e28bfb448d19658cf520a3e2409 | YashVardhan-Programmer/Characters-and-Words-Counter | /countwords.py | 311 | 4.0625 | 4 | sentence = input("Enter The Sentence: ")
characterCount = 0
wordsCount = 1
for i in sentence:
characterCount = characterCount+1
if i == ' ':
wordsCount = wordsCount+1
print("No. of words in the sentence are:", wordsCount)
print("No. of characters in the sentence are:", characterCount) |
51c8f7090aaa990c0d30d1516c1c0db8cccd0cf2 | AnastasiaTomson/english_learning | /learn_english.py | 3,203 | 3.78125 | 4 | import fileinput
import random
import os
import shutil
def cls():
os.system('clear')
def read_file():
input_file = open('not_learning.txt', 'r+', encoding='utf-8-sig')
return input_file.readlines()
def write_file(file_name):
input_file = open(file_name, 'w+', encoding='utf-8-sig')
return input... |
f7cf0e4674be6f769949100c1d5cee0317eb9315 | theothershore2019/basic_01_python_basic | /hm_06_个人信息.py | 335 | 3.765625 | 4 | """
姓名:小明
年龄:18 岁
性别:是男生
身高:1.75 米
体重:75.0 公斤
"""
# 在 Python 中定义变量是不需要指定变量的类型的
# Python 可以根据 = 等号右侧的值,自动推导出变量中存储数据的类型
name = "小明"
age = 18
gender = True
height = 1.75
weight = 75.0
print(name)
|
bef2d7698838d49f6318b91d6c29cfb320107e2a | poojavarshneya/algorithms | /level_order_traversal.py | 2,164 | 3.984375 | 4 | from collections import defaultdict
from queue import Queue
class LinkedNode:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.root = None
def insertNode(self, val):
node = LinkedNode(val)
if self.root is None:
... |
a681e1ce9bc4b282318eaf5d3b7fdd1af3d08c83 | totoma3/Baekjoon-Algorithm | /2562번.py | 479 | 3.734375 | 4 | #9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오.
#예를 들어, 서로 다른 9개의 자연수
#3, 29, 38, 12, 57, 74, 40, 85, 61
#이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다.
num_list=[]
for i in range(0,9):
a=int(input())
num_list.append(a)
max_num = max(num_list)
print(max_num)
print(num_list.index(max_num)+1)
|
06826cedc33c52d0fb5e19b68debc0c475e0d9b2 | roca77/Coding | /ai_tictactoe.py | 5,568 | 4.15625 | 4 | import copy
import random
# Setting a board with an empty list of list
board = [
['','',''],
['','',''],
['','','']
]
# A function to display the board
def displayboard(board):
print(board[0][0] + " | " + board[0][1] + " | " + board[0][2])
print(board[1][0] + " | " + board[1][1] + " | " + board[1... |
bc22f81758f3e28f83384ea956b851af73c761ec | AndreyIvantsov/PythonEx | /ex05.py | 3,063 | 3.9375 | 4 | # -*- coding: utf-8 -*-
my_name = 'Андрей'
my_age = 47 # лет
my_height = 178 # см
my_weight = 76 # кг
my_eyes = 'Карие'
my_teeth = 'Белые'
my_hair = 'Русые'
print('Давайте погворим о человеке по имени %s' %my_name)
print('Его рост составляет %d см.' %my_height)
print('Он весит %d кг.' %my_weight)
prin... |
7ebc9ee2e2774d301ee195a83722afc4511e3a1e | mgmorales1/CNN-cats-dogs | /CNN/convolutional.py | 1,060 | 3.953125 | 4 | import numpy as np
class Conv3x3:
# A Convolution layer using 3x3 filters.
def __init__(self, num_filters):
self.num_filters = num_filters
# filters is a 3d array with dimensions (num_filters, 3, 3)
# We divide by 9 to reduce the variance of our initial values
self.filters = np.random.randn(num_filters, 3,... |
05987044017700b32a9ce4b77f61ed8b3e47f345 | heman577/WebScrapping_python | /age_years.py | 799 | 3.71875 | 4 | #x=input('enter the value in years;')
#y=int(x)
#z=(y*365)
#print(z)
#print('you are ',z,'days old')
#user_response=input('enter the integer value:')
#x=int(user_response)
#y=x*x -12*x+11
#print(y)
#user_response=int(input('enter the integer value:'))
#my_list=['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDA... |
d8d746cfe0524222536d33a8f62dbedd3e0b3eeb | magdeevd/gb-python | /homework_4/second.py | 828 | 4.09375 | 4 | def main():
"""
2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего
элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка.
Для формирования списка использовать генератор.
Пример исходного списка: [300, 2, 12, 44... |
009a764f30abdeae8efd679a634694c213e8b99d | madhavinamballa/de_anza_pythonbootcamp | /loops/solved/while_loop.py | 178 | 4.09375 | 4 | #=======while loop print 1 to 10 numbers
number=1
while number<=10:
print(number)
number=number+1
#========for loop================
for num in range(10):
print(num) |
7602cccd19bbe7481365a449240eb82cccecb4c3 | Alex0Blackwell/python-projects | /space-text-animation.py | 542 | 3.828125 | 4 | # Text animation where a space goes through the string
import time as t
def spaceAnim(phrase):
# Runs in time O(n)
phrase += ' ' # Need an extra iteration to not print the last letter twice
L = len(phrase)
c = 0
while(c < 2): # Do animation 2 times
for i in range(L):
if(i ==... |
6aed7a3c453ce140a80d9189b8e59bc739659250 | tayciryahmed/data-structures-and-algorithms | /add-two-numbers.py | 1,067 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = ListNode()
curry = 0
root = ans
... |
bbf8f813be8f7143bf113f1a13ad6170b374e37b | kimjoshjp/python | /loop_3.py | 169 | 4.125 | 4 | #
#
#
#
answer = []
while len(answer) < 3:
new_name = input("Please add a new name: ").strip().capitalize()
answer.append(new_name)
print("Sorry list is full")
|
ea997879fddb718a7a1ea941b475934721edab75 | IamFive/note | /note/python/recipel.py | 1,313 | 3.6875 | 4 | class RomanNumeralConverter(object):
def __init__(self, roman_numeral):
self.roman_numeral = roman_numeral
self.digit_map = {
"M":1000,
"D":500,
"C":100,
"L":50,
... |
81652de510eb2ac59ce5badd2c05ac0591194cf9 | andonyan/Python-Fundamentals | /dictionaries exercise/company users.py | 535 | 3.890625 | 4 | companies = {}
while True:
tokens = input().split(' -> ')
if tokens[0] == 'End':
for key, value in sorted(companies.items(), key=lambda x: x[0]):
print(f'{key}')
for emp in value:
print(f'-- {emp}')
break
else:
company = tokens[0]
empl... |
ad0069c44ba4ef1d15c0fe5ced9161e5a6cdb97a | AlessandroCanel/Cybersecurity | /Base64.py | 768 | 3.796875 | 4 | # Let's see how this base 64 stuff works
import base64
def based():
with open('InputBase64.txt', 'r') as file:
phase = file.read()
c = input("decode or encode? ")
times = int(input("How many times? "))
while times != 0:
if c == "encode":
phase = base64.b64encode(bytes(ph... |
1ec8425a6da6ca4450aa59f9c032667c1d7f57a6 | jgriffith23/cci-python | /ch3/queue_ll.py | 2,390 | 3.9375 | 4 | """Implements a queue using reqs from Cracking the Coding Interview Ch 3.
Should be O(1) for all operations.
Philosophical question: Should I be returning Nodes when I dequeue, or
should I be returning the data? I'd argue the data, so the interface
btw the two queue types is the same.
"""
from linkedlist import Link... |
3810176ee9bc3612d38bf86c028788acfab09b16 | wards21-meet/meet2019y1lab4 | /funturtle.py | 1,297 | 3.6875 | 4 | import turtle
turtle.bgcolor('purple')
turtle.shape('turtle')
finn=turtle.clone()
finn.shape('square')
finn.goto(100,0)
finn.goto(100,100)
finn.goto(0,100)
finn.goto(0,0)
charlie=turtle.clone()
charlie.shape('triangle')
charlie.left(90)
charlie.forward(100)
charlie.goto(50,150)
charlie.goto(100,100)
finn.penup()
finn.g... |
73cd60fcaea5e5611568f337320029c9ed9ea743 | LeeeeDain/Algorithm | /프로그래머스/래벨2_DFSBFS_타겟넘버.py | 243 | 3.546875 | 4 | def solution(numbers, target):
answer_list = [0]
for i in numbers:
answer_list = list(map(lambda x: x+i, answer_list)) + list(map(lambda x: x-i, answer_list))
return answer_list.count(target)
print(solution([1,1,1,1,1],3)) |
33c14aa8717aa84c4830b1e41dfd06996ab135ed | Ben-Baert/Exercism | /python/hexadecimal/hexadecimal.py | 196 | 3.640625 | 4 | from string import hexdigits
def hexa(hex_string):
return sum(hexdigits.index(current_digit) * 16**current_position for current_position, current_digit in enumerate(hex_string.lower()[::-1])) |
4bef4dbda6842b1988760934b72ad4007ca80c6b | Jayabharathi-Thangadurai/program | /leap.py | 100 | 3.75 | 4 | year=int(input())
if year%400==0 or (year%100)!=0 and year%4==0:
print("yes")
else:
print("no")
|
3179e131f93eb19fa5f48d5c90d179b8e654ba30 | daimengqi/Coding4Interviews-python-DMQ | /Coding4Interviews-python-DMQ/剑指offer/053-表示数值的字符串/code.py | 974 | 3.890625 | 4 | class Solution:
# s字符串
def isNumeric(self, s):
# write code here
sign, point, hasE = False, False, False
for i in range(len(s)):
if s[i].lower() == 'e':
if hasE: return False
if i == len(s)-1: return False
hasE = True
... |
32ecb9b4cfe42fc63007e72ac3c8778fa8121ad5 | huang-zp/pyoffer | /my_queue.py | 646 | 4.125 | 4 | class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stack_in.append(x)
def pop(self)... |
66b4844c7e17191f58f27ac4b1cba6907805e5ea | pranavv999/js-graphs | /pyfiles/indian.py | 1,026 | 3.75 | 4 | import csv
# We are refering data from year 2004 to 2014
def extract_data(file):
"""Return the population data for India for year 2004 to 2014"""
population_data = {
"gTitle": "Indian Population For Year 2004 - 2014",
"xLabels": [
"2004",
"2005",
"2006",
... |
6f0c96fb181d53b3210c99d4477af49546067aec | Brkgng/HackerRank_Solutions | /Warmups/time-conversion.py | 415 | 3.796875 | 4 | #
# See the problem
# https://www.hackerrank.com/challenges/time-conversion/problem
#
#
def timeConversion(s):
if s[-2:] == "AM":
if s[:2] == "12":
return "00" + s[2:-2]
return s[:-2]
if s[:2] == "12":
return s[:-2]
return str(int(s[:2]) + 12) + s[2:-2]
# if __name__ =... |
daf69275ea6a376dca21b8fa90b2518106acd33f | itsolutionscorp/AutoStyle-Clustering | /assignments/python/anagram/src/88.py | 404 | 3.671875 | 4 | from collections import Counter
def detect_anagrams(word, word_list):
if word in word_list:
return []
word_c = Counter(word.lower())
word_list_counters = dict(zip(word_list, (Counter(w.lower()) for w in word_list)))
anagrams = [w for w in word_list_counters if (word_list_counters[w] == wor... |
5a71aad09b865045b9d1d72cb0e4e3906fd90074 | lusineduryan/ACA_Python | /Basics/Homeworks/Homework_6/Exercise_2_fast determinant.py | 615 | 4.21875 | 4 | # https://www.khanacademy.org/math/algebra-home/alg-matrices/alg-determinants-and-inverses-of-large-matrices/v/finding-the-determinant-of-a-3x3-matrix-method-1
def fast_deter(arg):
res = 0
N1 = arg
for i in range(len(arg)):
if i > 0:
N1 = N1[1:]
N1.append(arg[i-1])
N... |
a6a7437b89d7de2801c54933df145a5b0c3123b3 | yesiaikan/pythonlearn | /luoji/myfor.py | 154 | 3.5 | 4 | __author__ = 'muli'
for i in range(1,4,2):
print(i)
else:
print("-----------")
for i in xrange(5):
print(i)
print(range(2, 5, 2)) |
0d28a1976c05fcd891f962c408721f5c2f675d70 | roxanacaraba/Learning-Python | /25-Frequently-Asked-Python-Programs/Clear_a_list.py | 460 | 4.125 | 4 | list=[6,0,4,1]
print("List before clear:", list)
#Varianta 1 folosind clear()
#list.clear()
#print("List after clear:", list)
#Varianta 2 : initializes the list with no value
#list=[]
#print("List after clear:", list)
#Varianta 3 utilizand "*=0", aceasta metoda inlatura toate elementele si o face goala
#list *=0 #d... |
31daf353c4116031af0f029ec76d0379c1c4b067 | orsenthil/coursedocs | /gatech/cs8803-O01/circular_motion.py | 6,635 | 4.375 | 4 | # -----------------
# USER INSTRUCTIONS
#
# Write a function in the class robot called move()
#
# that takes self and a motion vector (this
# motion vector contains a steering* angle and a
# distance) as input and returns an instance of the class
# robot with the appropriate x, y, and orientation
# for the given motion... |
5653f4d749ad89f9b4e56323b3333f685ba9afe3 | anurag3753/courses | /david_course/Lesson-07-Classes_and_Objects/holding_v1.py | 1,985 | 3.828125 | 4 | """Understanding the classes:-
We are not using Holding(object) syntax, because in python3 all the classes by default
inherit from object classes
"""
class Holding:
def __init__(self, name, date, shares, price):
self.name = name
self.date = date
self.shares = shares
self.p... |
149924670b5e81bb5d879155c2068e91a99a6546 | qqlzfmn/AutomateTheBoringStuffWithPython | /PatternMatching/stripRegex.py | 483 | 3.546875 | 4 | import re
def stripRegex(str, char=' '):
# re.compile()的参数本质上是一个字符串,所以可以用字符串拼接的方式写
# 要提取出中间的字符串,就需要变成非贪心模式,否则将会匹配后续的分割字符
regex = re.compile(r'^[' + char + r']*(.+?)[' + char + r']*$')
return regex.search(str).group(1)
print(stripRegex(' fnewuih564asui '))
print(stripRegex('-------------- f... |
da31b78ea66c60f1fdcc55dea87a1f5aa77e694f | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_118/285.py | 945 | 3.625 | 4 | fair_squares = []
def is_fair(n):
return all(a == b for a,b in zip(str(n), reversed(str(n))))
def precompute_fair_squares():
for i in range(1, 10 ** 7 + 1):
if is_fair(i):
i2 = i ** 2
if is_fair(i2):
# print(i2)
fair_squares.append(i2)
def binary_search(x, is_upper_bound):
a = 0
... |
c3750ae75a5d41864a666cb9e9465783305eb396 | nashirj/PathPlanner | /pathfinding.py | 2,128 | 3.859375 | 4 | def a_star(arena, start, end):
'''Implementation of algorithm from this video: https://www.youtube.com/watch?v=-L-WgKMFuhE
'''
open_nodes = {}
closed_nodes = {}
open_nodes[start] = start.f_cost
while open_nodes:
# https://stackoverflow.com/questions/3282823/get-the-key-corresponding-to-t... |
cacd744bf14997dc534f07cf1e5c5253875f8e1a | baewonje/iot_bigdata_- | /python_workspace/01_jump_to_python/5_APP/1_Class/188_4_cal_class4.py | 1,170 | 3.609375 | 4 | class FourCal:
# first = 0
# second = 0 # 중간에 멤버 변수를 정의할 수 있어도 명시적으로 클래스
# 멤버 변수를 class 다음에 지정하는 것은
# 프로그램 유지보수와 가독성에 더 좋다고 볼 수 있다.
def setdata(self,first, second):
self.first = first # 멤버 변수가 없음에도 객체생성이후에
# 클래스의 멤버변수를 생성하는 것이 가능하다.
... |
c6c3cc1b8f1e6142c254251a7f21aa3ec40bd5a9 | Xia-Dai/Data-exploration-Python | /countchar_quiz.py | 459 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 20 17:05:41 2017
@author: Daisy
Email: dxww01@gmail.com
Never too late or old to study!
"""
#count alpha
def countchar(str):
list1 = [0]*26
for i in range(0,len(str)):
if (str[i] >= 'a' and str[i] <= 'z'):
list1[ord... |
8baa27d1b4008b21a659f86bf32fa18254b4b7a7 | paras2106/brampton | /Hi.py | 71 | 3.5 | 4 | # DECLARE Myname : STRING
Myname = "Paras"
print("Hi ",Myname)
input()
|
c5d55e95a8cd505986ec8114211e1140a9b9bd0e | palakbaphna/pyprac | /Conditions if, then, else/10minimumOf2Numbers.py | 202 | 4.25 | 4 | #Given the two integers, print the least of them.
a = int(input("a = ?"))
b = int(input("b = ?"))
if a < b:
print("least of them is a = %s" %a)
elif b < a:
print("least of them is b = %s" %b)
|
0f646b0e942bca83ca6e2770cc7e2c37fbf4e32e | testcg/python | /code_all/day15/exercise01.py | 619 | 4.28125 | 4 | """
练习1:定义函数,根据年月日,计算星期。
输入:2020 9 15
输出:星期二
"""
import time
def get_week_name(year,month,day):
"""
获取星期名称
:param year:年份
:param month:月份
:param day:天
:return:星期名称
"""
# "2021/03/18 11:48:56","%Y/%m/%d
tuple_time = time.strptime(f"{year}/{month}/{day}","%Y/%m/%d... |
9765eba70256582e8b0bf354ae20df1f8d55149d | AIClubUA/Weekly-Meetings | /September 2018/Week of 9-24-2018/basic-csv-processing/kagglepre.py | 983 | 3.625 | 4 | import pandas as pd
df = pd.read_csv("train.csv")
df.fillna(0, inplace=True)
print(df.head())
"""
predict death or life (1 or 0)
GOAL: process data so that we have our inputs in a logical order on a per person basic
"""
labels = df['Survived']
features = list(df.columns)
features.remove("Survived") # removes "Sur... |
945209eb540f84ad30975ee1a657f50b347de7d7 | alexchou094/Python200804 | /Day2-6.py | 765 | 3.859375 | 4 | nP = input("how many student in your class?")
nP = int(nP)
total = 0
avg = 0
name = []
grade = []
for i in range(nP):
N = input("Please enter students' name : ")
name.append(N)
G = input("Please enter the student's grade : ")
grade.append(G)
for i in range(nP):
total = total + int(grade[... |
0a81901deee7820bcc78a20d33b9aa319056c661 | ZanderYan-cloud/PythonRepository | /GuessnumberGame/cn/csu/python/intDemo.py | 1,000 | 3.578125 | 4 | #1. x 是数字的情况:
print(int(3.14) ) # 3
print(int(2e2)) # 200
#int(100, 2) # 出错,base 被赋值后函数只接收字符串
#2. x 是字符串的情况:
print(int('23', 16) ) # 35
#int('Pythontab', 8) # 出错,Pythontab不是个8进制数
#3. base 可取值范围是 2~36,囊括了所有的英文字母(不区分大小写),十六进制中F表示15,那么G将在二十进制中表示16,依此类推....Z在三十六进制中表示35
#print(int('FZ', 16... |
45dc3bc04089b469a4ba2fd8d6525b97679d9d72 | 18516264210/MachineLearning | /python00/day04/Gaojiehanshu.py | 713 | 4.21875 | 4 |
# 高阶函数(通俗的讲就是函数返回函数)
# 函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数
def f1(x,y):
return x+y
def calc(x):
# 接收的是一个函数名,加()执行传递过来的函数
return x(1,2)
# 这里将函数作为参数传递到另一个函数中进行执行
n = f1
print(calc(n))
print("-----------------------------------------------")
# 这里的函数返回的是一个元组,在外层获取参数后使用下标的形式获取到对应的函数和参数
def f2(x,y)... |
507b132247785a0143d19bc32cebac469e18447f | yojimat/100_plus_Python_Programming_Exercises | /day_6_desafio_100_ex_python.py | 1,924 | 4.15625 | 4 | ####################################
print("\nQuestão 16:")
print("Use a list comprehension to square each odd number in a list.")
print("The list is input by a sequence of comma-separated numbers.")
print("Suppose the following input is supplied to the program:")
print("--> 1,2,3,4,5,6,7,8,9")
print("Then, the output ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.