blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c2860a05ee2a98f8a2f938581fe588266f6c535a | jimibarra/cn_python_programming | /miniprojects/loops_test.py | 1,057 | 3.984375 | 4 | my_list = [1, 2, 3, 4, 5]
# 'break' ends the execution of the loop, skipping anything after
for num in my_list:
if num % 3 == 0:
break
print(num)
print("finished 'break' part")
for num in my_list:
if num % 3 == 0:
continue
print(num)
print("finished 'continue' part")
n = 10
while True... |
2dfff17f70a01dcaf4d742352055b160fbc06669 | jimibarra/cn_python_programming | /miniprojects/trip_cost_calculator.py | 396 | 4.375 | 4 | print("This script will calculate the cost of a trip")
distance = int(input("Please type the distance to drive in kilometers: "))
usage = float(input("Please type the fuel usage of your car in liters/kilometer: "))
cost_per_liter = float(input("Please type the cost of a liter of fuel: "))
total_cost = cost_per_liter *... |
a9cfee9934cc75445451574cfc4878cb11d39f4d | jimibarra/cn_python_programming | /07_classes_objects_methods/07_02_shapes.py | 1,539 | 4.625 | 5 | '''
Create two classes that model a rectangle and a circle. The rectangle class should
be constructed by length and width while the circle class should be constructed by
radius.
Write methods in the appropriate class so that you can calculate the area (of the rectangle and circle),
perimeter (of the rectangle) and cir... |
b1b191321e4f71bf57f4052aaa91cb01c8d60501 | jimibarra/cn_python_programming | /07_classes_objects_methods/07_01_car.py | 1,075 | 4.53125 | 5 | '''
Write a class to model a car. The class should:
1. Set the attributes model, year, and max_speed in the __init__() method.
2. Have a method that increases the max_speed of the car by 5 when called.
3. Have a method that prints the details of the car.
Create at least two different objects of this Car class and dem... |
8c1053a3d6092c244c89f36e11d60cc63b1d9090 | jimibarra/cn_python_programming | /03_more_datatypes/2_lists/03_11_split.py | 540 | 4.40625 | 4 | '''
Write a script that takes in a string from the user. Using the split() method,
create a list of all the words in the string and print the word with the most
occurrences.
'''
user_string = input("Please enter a string: ")
my_list = user_string.split(" ")
print(my_list)
my_dict = {}
my_set = set(my_list)
for item ... |
900c1185f0af45dd797ce33c0e0ce11fb759a449 | jimibarra/cn_python_programming | /02_basic_datatypes/2_strings/02_09_vowel.py | 991 | 4.4375 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
#Total Vowel Count
vowel = ['a', 'e', 'i', 'o', 'u']
stri... |
1c551d5fdea25beebc8b9c566d17fc4c23a1c3b1 | jimibarra/cn_python_programming | /04_conditionals_loops/04_10_squares.py | 237 | 4.34375 | 4 | '''
Write a script that prints out all the squares of numbers from 1- 50
Use a for loop that demonstrates the use of the range function.
'''
for num in range(1,51):
square = num ** 2
print(f'The square of {num} is {square} ')
|
4fdf4c4642416a538b45e9b58460e0b14b519993 | jimibarra/cn_python_programming | /15_aggregate_functions/15_02_sum.py | 346 | 4.03125 | 4 | '''
Write a simple aggregate function, sum(), that takes a list a returns the sum.
'''
def my_sum(sequence): #the sequence argument is a list of numbers.
sum = 0
for item in sequence:
sum += item
return sum
my_list = [100, 10, 20, 30 , 40 , 50]
result = my_sum(my_list)
print(f'The sum of the list... |
6bfee747928fa37a7cbcf03d73fd118133f6c930 | jimibarra/cn_python_programming | /01_python_fundamentals/01_07_area_perimeter.py | 277 | 4.1875 | 4 | '''
Write the necessary code to display the area and perimeter of a rectangle that has a width of 2.4 and a height of 6.4.
'''
area = 6.4 * 2.4
perimeter = 2 * (6.4 + 2.4)
print(f"The area of the rectangle is {area}")
print(f"The perimeter of the rectangle is {perimeter}")
|
8ecfad1dc56c0a61539994fd879748bfaefc32f0 | jimibarra/cn_python_programming | /miniprojects/dunder_test.py | 965 | 3.625 | 4 | class Letter:
def __init__(self):
self.mystring = 'abcdefg'
self.mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
self.mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6,}
self.index = -1
def __len__(self):
return len(self.mydict)
#def __getitem__(self, index):
... |
f33269dba0bcea5606ca8375ebaf0b65bd36dcf4 | brook-hc/py-study | /001-基本语法/007-while循环.py | 187 | 4.15625 | 4 | name='' # for循环的判断变量可以不需要先定义,而while不行。
while name !='your name':
print('please type your name!')
name=input()
print('名字匹配')
|
fb33562bf935bb6c92f7964cee8a24dc1eeb91a9 | brook-hc/py-study | /002-函数/016-函数01.py | 1,392 | 4.09375 | 4 | def find_max(a,b):
'''比较2个数的大小,并返回最大值。''' #函数里面的”号不是定义字符串了,而是函数注释。
if(a>b):
print(a,"a较大")
else:
print(b,"b较大")
find_max(10,20)
find_max(30,5)
help(find_max) #该语句可以查看函数里面的注释文档。
print('----------------------------')
def hello(a,b):
if a>b:
print("hello")
else:
... |
9f20883f48c73186a8e6b6e5e018801fde1a70f9 | brook-hc/py-study | /009-进程和线程/043-线程共享全局变量.py | 458 | 3.671875 | 4 | # 线程可以共享全局变量,但是进程不行~!!!
import threading
import time
num=1000
def reduce1():
for i in range(100):
global num
num-=1
print(num)
time.sleep(0.2)
def reduce2():
for j in range(100):
global num
num-=1
print(num)
time.sleep(0.2)
p1=threading.Thre... |
366715f4d392db1f78d7238e877762dc41745336 | brook-hc/py-study | /001-基本语法/009-字符串正序和逆序输出.py | 643 | 3.953125 | 4 |
name='abcdefghijk'
print(name[3:8]) # 切片技术,从字符串中取一段,包前不包后。
print(name[3:-1]) # 从后面数,第一个是-1,同样也是包前不包后,所以用负数取不到最后一个字符。
# 想去到最后一个字符可以[x:],什么都不填就默认取前面/后面的所有。
print(name[::-1]) # 两个冒号,最后一个位置的符号代表方向,1是从左往右,-1是倒序。
print(name[-1:-5:-2]) # 而最后一位的数值代表依次取后面第几个字符取值。
print(name[::3]) ... |
f884581a74b2fa33ba0754284fac126e5e7e9bd6 | namnamgit/pythonProjects | /emprestimo_bancario.py | 949 | 4.125 | 4 | # rodrigo, may0313
# escreva um programa para aprovar o empréstimo bancário para compra de uma casa.
# o programa deve perguntar o valor da casa a comprar, o salário e a quantidade de anos a pagar.
# o valor da presta;ão mensal não pode ser superior a 30% do salário.
# calcule o valor da presta;ão como sendo o valor da... |
d8dfdd0ab64c2408a82be5fcbbd1b37fddbe0fee | namnamgit/pythonProjects | /maior_e_menor_numero.py | 810 | 4.125 | 4 | # rodrigo, apr1013
# escreva um programa que leia três números e que imprima o maior e o menor
while True:
numero1 = int(input('Digite o primeiro número: '))
numero2 = int(input('Digite o segundo número: '))
numero3 = int(input('Digite o terceiro número: '))
if numero1 > numero2 and numero1 > numero3:
print('%d... |
5e38b43b9a3ffb883b5613e30c82cb91697ca813 | namnamgit/pythonProjects | /random_movie.py | 242 | 4.03125 | 4 | # This code is used to pick a random movie from 3 different dirs
import random
while True:
a = int(input("Dir: "))
b = int(input("Range: "))
print ("Next movie: ", end='')
print (random.randint(a, b))
input("Good choice, pseudo!\n")
|
3497e321c4f5e124ac01f82588bffc95e2dcf4dc | namnamgit/pythonProjects | /the_world_is_flat.py | 235 | 3.6875 | 4 | the_world_is_flat = 2 #variável recebe valor 2
while the_world_is_flat < 5: #enquanto variável tiver valor menor que 5...
print("Be careful not to fall off!") #mostrar comentário
the_world_is_flat = the_world_is_flat + 1
input()
|
e63f321d7f785cce92a94cb63cb738f81c56ea3b | namnamgit/pythonProjects | /tempo_de_viagemv2.py | 541 | 3.953125 | 4 | # n01, jul0513
# escreva um programa que calcule o tempo de uma viagem de carro.
# pergunte a distância a percorrer e a velocidade média esperada para a viagem.
distancia_percorrer = int(input('Digite a distância a percorrer: '))
velocidade_media = int(input('Digite a velocidade média prevista: '))
tempo_de_viagem = ... |
a527b1860a3ee3a60aa9e2cf51bbf312f6e04559 | namnamgit/pythonProjects | /aluno_aprovadov2.py | 669 | 4.03125 | 4 | # n01, jun3013
# escreva uma expressão que será utilizada para decidir se um aluno foi ou não aprovado.
# para ser aprovado, todas as médias do aluno devem ser maiores que 7.
# considere que o aluno cursa apenas três matérias e que a nota de cada uma está
# armazenada nas seguintes variáveis: matéria1, matéria2 e matér... |
e26d496b79288ac973c64f30f34fc4413ae06364 | namnamgit/pythonProjects | /carro_alugado.py | 472 | 3.734375 | 4 | # rodrigo, apr0413
# pergunte a quantidade de km percorridos por um carro alugado pelo usuário,
# assim como a quantidade de dias pelos quais o carro foi alugado.
# calcule o preço, sabendo que o carro custa R$ 60,00 por dia e R$ 0,15 por km rodado.
print('ALUGUEL DE CARROS\n')
while True:
dias = int(input('Quantidad... |
bfae82a3c50b3fb10c8a23cb0a3799fe7d79a6af | lgw2238/Python_practice | /goott_python/basic/stringFunction.py | 1,912 | 3.5 | 4 | print()
...
# 문자열 내장 함수 : 문자열 자료형이 자체적으로 가진 함수
# 사용 : 문자열 변수 이름 뒤에 dot(.)을 붙인 다음 적절한 함수 이름을 호출
...
# 문자 개수 세기 : count
str = 'apple'
#print(str.count)
print(str.count('p'))
# 위치 알려주기 : find
str = '오늘은 화요일, 내일은 수요일'
print(str.find('내일은'))
...
# 찾는 문자의 첫번째 글자가 처음으로 나온 위치를 반환
# 문자열이므로 인덱스 번호임에 유의
...
print(str.find... |
7aaa3e6da583733ee1bcea410c1d1d9dbc5f59f7 | lgw2238/Python_practice | /goott_python/function/functionEx02.py | 1,159 | 3.640625 | 4 | print()
'''
#함수 구조 3 - 함수 입력값(매개변수)이 몇 개 인지 모를 경우
def 함수명(*입력변수명)
<수행할 문장> ..
<return>
'''
def sum(*args): # args (arguments) - 관례적
sum = 0
for i in args :
sum += i
return sum
result = sum(1,2,3,4,5,6,7,8,9,10)
print(result)
print('----------------------------------------... |
60b1c71c847133004742e584525b21af47182696 | RmnSnk/testpycharm | /Chapitre12/5/mesmodules.py | 1,198 | 3.890625 | 4 | # coding:utf-8
import math
"""
Bibliothèque de class et fonction pour l'exercice
"""
class Cercle():
""""
Cette class permet d'intancier des cercles par leur rayon
"""
def __init__(self, rayon):
self.rayon = rayon
def surface(self):
"""
:return: La surface de l'o... |
c9a16b8d0d67107d8a1be30da224ca132c4b3b25 | RmnSnk/testpycharm | /Chapitre16/1/testcvs.py | 769 | 3.59375 | 4 | # coding utf-8
import csv
import sqlite3
f_csv = '/home/romain/PycharmProjects/testpycharm/Chapitre16/1/oeuvres.csv'
bdd = '/home/romain/PycharmProjects/testpycharm/Chapitre16/1/bdd.sq3'
conn = sqlite3.connect(bdd)
cur = conn.cursor()
with open(f_csv, encoding='utf-8', newline='') as f:
reader = csv.reader(f)... |
c9fcce02201e96cbd5ffb500099ec6e4cc265af8 | RmnSnk/testpycharm | /Premier/exo.py | 2,156 | 3.78125 | 4 | # coding:utf-8
"""Programme pour donner les 1000 premiers nombres premier, basé sur la méthode d'Eratosthène
l'argement donné à la fonction liste fixe le nombres de nombres premiers que l'on cherche"""
def liste(n):
"""La fonction donne une liste de n éléments tous initialisé à 1
Dans cette liste les indi... |
5a4aa03eb669e0643e4866e0399fcf918159ab84 | cymbym/LeetcodeNote | /python/CountandSay.py | 1,572 | 3.828125 | 4 | """
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 n 30, generate the nth... |
4ceecea8db365f973066080c65b809bf84cf4b4f | hasirto/1 | /7while.py | 163 | 3.71875 | 4 | anahtar = 1
while anahtar == 1:
cevap = input("elma dersen çıkıcam ")
if cevap == "elma":
print("çıkılıyor...")
anahtar = 0 |
4faf1db18895fa41c4fffd649e8fb3fb245e7472 | howard891016/python | /assignment4_108062302.py | 5,859 | 3.921875 | 4 | import sys
class Record:
"""Represent a record."""
def __init__(self, category, description, amount,num):
self._category = category
self._description = description
self._amount = amount
self._num = num
@property
def category(self):
return self._category
@pr... |
e5265f660ebf4aea7f272149d4caaa201e6a3199 | RafaelRiber/Python-Programs | /bataille_navale.py | 1,314 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from random import randint
from os import system
from os import name
def cls():
system(['clear','cls'][name == 'nt'])
plateau = []
for x in range(0, 5):
plateau.append(["O"] * 5)
def afficher_plateau(plateau):
for ligne in plateau:
print " ".join(ligne)
afficher_plateau(pla... |
054d931d0ccfae32b11d15b6264bf134f33252af | 22thomju/module-a | /modA_challenge.py | 389 | 3.890625 | 4 | print("A.")
for i in range (10):
print("Hello, Python")
print("B.")
counter = 0
for i in range (10):
print(counter)
counter = counter + 1
print("C.")
counter = 1
for i in range (10):
print(counter)
counter = counter + 1
print("D.")
counter = 2
for i in range (10):
print(counter)
counter... |
c6ad81cc7e71d78d30c3cf7c0f92ab4c5472093c | arahatashun/spacecraft_control | /spin_satellite_simulator/visualize_quaternion.py | 938 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Shun Arahata
# This module visualize motion of a spin satellite referring to
# https://blender.stackexchange.com/questions/6899/animate-with-position-and-orientation-from-txt-file
# usage : blender --python visualize_quaternion.py
import bpy
def main():
sate... |
d88b5f981ffb5897f15890cc1046d25caae3db5b | runzezhang/MOOCs | /Coursera/Introduction to Data Science in Python/Week 2-Basic Data Processing with Pandas/Week+2.py | 7,204 | 3.78125 | 4 |
# coding: utf-8
# ---
#
# _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._
#
... |
1f8a4b16412af479df18af8834106f2da03ad74e | Shubashkaran/Comprinno_test | /Comprinno_test_answers/Question 2/Question 2.py | 999 | 3.859375 | 4 | def better(a,b):
return (a[0]<=b[0] and a[1]<=b[1] and a[2]<=b[2]) and (a[0]<b[0] or a[1]<b[1] or a[2]<b[2])
#1. a[0]<=b[0] and a[1]<=b[1] and a[2]<=b[2] checking if b doesn't score less than a in any of the skills
#2. a[0]<b[0] or a[1]<b[1] or a[2]<b[2] checking if b scores more than a in atlea... |
f0daa51bfa1d23525e19d7826c928be7349b9d7d | petersNikolA/turtle1 | /turtle10.py | 422 | 3.921875 | 4 | import turtle as tr
import numpy as np
tr.shape('turtle')
#tr.tracer(False)
tr.speed(0)
def flower(n):
x = 0
for j in range(n // 2):
for i in range(360):
tr.forward(1)
tr.left(1)
for i in range(360):
tr.forward(1)
tr.right(1)
... |
3fa3eee6aa19701a04744515f28638050c0e3125 | DJJD2150/backend-test-these-katas-activity | /tests/test_katas.py | 1,251 | 3.625 | 4 | import unittest
import katas
class TestKatas(unittest.TestCase):
def test_add(self):
self.assertEqual(katas.add(3, 5), 8)
self.assertEqual(katas.add(-1, 1), 0)
self.assertEqual(katas.add(-4, -7), -11)
self.assertEqual(katas.add(14, 21), 35)
def test_multiply(self):
sel... |
d0e9358885e01dee964f826d9302180cb7d3ab90 | AmyShackles/LearnPython3TheHardWay | /ex7.py | 1,396 | 4.28125 | 4 | # prints the string 'Mary had a little lamb'
print("Mary had a little lamb.")
# prints 'Its fleece was white as snow', the {} indicated replacement and 'snow' was the replacement text
print("Its fleece was white as {}.".format('snow'))
# prints 'And everywhere that Mary went'
print("And everywhere that Mary went.")
# p... |
56a0e315d4a1d962895818015d6632a18c028e8b | AmyShackles/LearnPython3TheHardWay | /ex10.py | 804 | 3.890625 | 4 | #assigns the value of a tab followed by "I'm tabbed in" to variable tabby_cat
tabby_cat = "\tI'm tabbed in."
# assigns the value of "I'm split" followed by a new line followed by "on a line" to variable persian_cat
persian_cat = "I'm split\non a line."
#assigns the value of "I'm \ a \ cat" to variable backslash_cat
bac... |
7d9600f2d3b44ba69232a20d4586c61dc48fb8b6 | shkyler/gmit-cta-problems | /G00364753/Q2d.py | 957 | 4.375 | 4 | # Patrick Moore 2019-03-05
# This is a script to create a function that finds the max value in a list
# using an iterative approach, as directed by Question 2(d) of the
# Computational Thinking with Algorithms problem sheet
# define a function that takes a list as an argument
def max_iter(data):
# set the maximum v... |
de46aafa084129a881e9283245a0f74503d17b8a | IvAvde/Python-Homework | /hw3.py | 110 | 3.515625 | 4 | n = input('введи n: ')
nn = n+n
nnn = n+n+n
n = int(n)
nn = int(nn)
nnn = int(nnn)
print(n + nn + nnn)
|
88c86046c37d44418917ae2d1d564869a87ac2e0 | projeto-de-algoritmos/Greed_Cashier | /src/main.py | 8,475 | 3.640625 | 4 | import json, random
import pprint, os
class Product:
def __init__(self, code, name, price, description, quantity):
self.code = code
self.name = name
self.price = price
self.description = description
self.quantity = quantity
def get_data_of_json(path):
with open(path) a... |
598d698f802ee25c786576660005d073d56ff862 | DaCoolOne/sorting_algorithms | /ListF.py | 330 | 3.890625 | 4 | # ListF - Short for List Functions
import random
# returns a list of random unique integers
def randomIntList(length) -> list:
a = [ i for i in range(length) ]
random.shuffle(a)
return a
def listIsSorted(a) -> bool:
for i in range(len(a) - 1):
if a[i] > a[i+1]:
return False
re... |
02b23ab0fc07453792464283b611b4c74402fe62 | gregory-jean/Py4E-Python-Data-Structures | /Week01/Assignment_6.5_ParseNumberFromAString.py | 554 | 3.953125 | 4 | '''
Assigment 6.5
Write code using find() and string slicing (see section 6.10) to extract
the number at the end of the line below.
text = "X-DSPAM-Confidence: 0.8475";
Convert the extracted value to a floating point number and print it out.
'''
text = "X-DSPAM-Confidence: 0.8475"
# Find where the number... |
0eb30cbf112213813c852541c3dc22c52b2123cd | albininovics/python | /trial.py | 133 | 4 | 4 | a = 50
if a > 0:
print("The number is positive")
elif a < 0:
print("The number is negative")
else:
print("Zero number")
|
09fd29c8bb7833b7dab964ad1a2224d10a883433 | ariefzuhri/StrukturData | /2020-03-02/A - Letter T Array.py | 219 | 3.578125 | 4 | def push(T, data):
m = len(T)
T.insert(int(m/2), data)
n = int(input())
data = list(input().split())
T = []
for i in range(n):
push(T, data[i])
for i in range(n):
print(T[i], end=" ")
print()
|
a18ba57085ff86738a4d64960317cb2b1f0e3775 | ariefzuhri/StrukturData | /2020-03-02/B - CELENGAN KOIN.py | 719 | 3.5625 | 4 | def tabungAtas(S, data):
S.append(data)
def tabungBawah(S, data):
S.insert(0, data)
def ambilAtas(S):
if (not isEmpty(S)):
S.pop()
def ambilBawah(S):
if (not isEmpty(S)):
S.pop(0)
def isEmpty(S):
return S == []
n = int(input())
celengan = []
if (n>0):
f... |
7c704ae5e120d6ee6af5907ed3184cf0dabf6684 | tbrendle/knapsack | /knapsack.py | 3,101 | 3.609375 | 4 | import numpy as np
class Estimator():
def __init__(self, value, size):
self.value = value
self.size = size
self.n = len(value)
def bestRelaxedValue(self,index, capacity):
bestValue = 0
capa = 0
for i in xrange(index, self.n):
capa+= self.size[i]
... |
c79aceb7cee6b73184a68ca334e5a6935e39bd94 | ZoeSj/LeetCodeDay | /21_merge_two_sorted_lists/merge_two_sorted_lists.py | 846 | 3.984375 | 4 | # @File : merge_two_sorted_lists.py
# @Date : 2019-04-28
# @Author : shengjia
list_one = [1, 2, 4]
list_two = [1, 3, 4]
def mergeTwoLists(list1, list2):
list = list1 + list2
list.sort()
return list
mergeTwoLists(list_one, list_two)
# Time: O(n)
# Space: O(1)
# Definition for singly-linked li... |
4205e97fc32936dcf5c8e84a2b3441883bc9a356 | ZoeSj/LeetCodeDay | /2/2_s.py | 1,851 | 4 | 4 | class ListNode(): # init construct func
def __init__(self, value):
self.value = value
self.next = None
def Creatlist(n):
if n <= 0:
return False
if n == 1:
return ListNode(1) # only one node
else:
root = ListNode(1)
tmp = root
for i in range(2,... |
f36d9456bced6bd379ba2f93eefd920b464bb0d6 | ZoeSj/LeetCodeDay | /14_LongestCommonPrefix/longestCommonPrefix.py | 436 | 3.5 | 4 | # @File : longestCommonPrefix.py
# @Date : 2019-02-19
# @Author : shengjia
list1 = ["flower", "flow", "flight"]
out = "fl"
list2 = ["dog", "racecar", "car"]
out1 = ""
def longestCommonPrefix(strs):
if not strs:
return ""
for i, letter_group in enumerate(zip(*strs)):
if len(set(letter... |
907cc7e6c81256bc428424520fb8539446965a4b | AnushreeBaghwar/hackerRank | /Np transpose and flatten.py | 281 | 3.515625 | 4 | # https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem?isFullScreen=true&h_r=next-challenge&h_v=zen
import numpy
r,c = map(int,input().split())
arr = numpy.array([list(map(int,input().split())) for i in range(r)])
print(numpy.transpose(arr))
print(arr.flatten())
|
d49bcb89f7d49a7f3518d3327de41fd3cecd684b | AnushreeBaghwar/hackerRank | /Np shape reshape.py | 168 | 3.6875 | 4 | # https://www.hackerrank.com/challenges/np-shape-reshape/problem?isFullScreen=true
import numpy
s = numpy.array(list(map(int,input().split())))
print(s.reshape(3,3))
|
27f16bc3358bbe81f460cc9b63ce5d8d0e478a7c | AnushreeBaghwar/hackerRank | /Compress the string.py | 273 | 3.84375 | 4 | # https://www.hackerrank.com/challenges/compress-the-string/problem?isFullScreen=true
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import groupby
for i,j in groupby(map(int,list(input()))):
print(tuple([len(list(j)),i]),end=" ") |
44fa2d71ccebb7912bc990a432592076d74f79e8 | AnushreeBaghwar/hackerRank | /Itertools combinations with replacement.py | 429 | 3.78125 | 4 | # https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem?isFullScreen=true&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import combinations_with_replacement
s,k = input().split()
output = list(co... |
f941a82f9a063d6ff65eb1ce505390c8bb136b3e | AnushreeBaghwar/hackerRank | /Zipped.py | 292 | 3.6875 | 4 | # https://www.hackerrank.com/challenges/zipped/problem?isFullScreen=true
# Enter your code here. Read input from STDIN. Print output to STDOUT
N,X = map(int,input().split())
marks = []
for i in range(X):
marks.append(map(float,input().split()))
for i in zip(*marks):
print(sum(i)/X)
|
fb990aa7c0455d312e31b0179a1128136f7340c9 | davidhimer/Programoz-s_2 | /backend.py | 2,327 | 3.59375 | 4 | import sqlite3
"""
Ebben a functionban hozódik létre az adatbázis amiben a bolt termékai vannak
"""
def connect():
conn = sqlite3.connect("products.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, nev text, ar real) ")
conn.commit()
conn... |
d38ef9d47a8196c741bedb133abfd523e2e341c9 | umluizlima/ac309 | /04-algoritmos-da-teoria-dos-numeros/exponenciacao_por_quadratura.py | 547 | 3.5 | 4 | def exp_a(x: int, n: int) -> int:
"""Trivial O(n).
Exemplos
--------
>>> exp_a(2, 10)
1024
"""
res = x
for _ in range(1, n):
res *= x
return res
def exp_b(x: int, n: int) -> int:
"""Por quadratura O((n * log(x))^k).
Exemplos
--------
>>> exp_b(2, 10)
... |
0c398fbb1cd4da59ed33cdc0ef6d02152da1eae3 | CUMTB-RoboticFish/BITAI | /code/task2_3/Hopfield_Distance.py | 1,527 | 3.515625 | 4 | #!/usr/bin/python3
# Author : GMFTBY
# Time : 2017.1.19
# Link of help:
# 1. https://github.com/ChaiPL
# 2. Fix lots of things of the repo's script and do not work well
from math import sqrt
from typing import List, Tuple
def distance(p1, p2):
return sqrt((p1[0]-p2[0]) ** 2 + (p1[1]-p2[1]) ** 2)
# create... |
3d65fc63feed77b2c85775438c1152ef237b3443 | AlexHu0208/Demo | /FunctionBasic.py | 1,286 | 4.0625 | 4 | def my_function():
print("Hello from a function")
def my_function_with_params(fname):
print("{} Refsnes".format(fname))
def my_function_with_multi(*kids):
print("The youngest child is {}".format(kids[2]))
def my_function_with_key(a3, a2, a1):
print("The youngest child is {}".format(a3))
def my_f... |
21e547dddd0832b97cbb748fd77536e6a6770fb8 | UNREALre/LeetCode | /linked_lists/AddTwoNumbers.py | 1,396 | 4 | 4 | # -*- coding: utf-8 -*-
"""
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except... |
6765e54418810ef2dde1f39e9012aab35762ad76 | UNREALre/LeetCode | /arrays/SquaresOfASortedArray.py | 1,810 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 1000... |
de2e841b31a3742dd1bf7e2d927f1a3b9ed2943c | UNREALre/LeetCode | /linked_lists/IntersectionOfTwoLinkedLists.py | 3,261 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Reference... |
9d6e2e6e6d8c55965fe4206b140c78b2ee145772 | michaelobr/gamble | /Gamble.py | 1,667 | 4.3125 | 4 | #Short introduction of the purpose of this program
print("This short little program will help determine the probability of profitability and ROI from playing 50/50 raffles.")
#The number of tickets the user will purchase
num_user_tickets = int(input("How many tickets will you purchase? "))
#The total amount of... |
bca2eb0df154973cc48900b3493b812846429288 | Izabela17/Programming | /max_int.py | 727 | 4.25 | 4 | """If users enters x number of positive integers.
Program goes through those integers and finds the maximum positive
and updates the code. If a negative integer is inputed the progam stops the execution
"""
"""
num_int = int(input("Input a number: ")) # Do not change this line
max_int = num_int
while num_int >= 0:
... |
d610d873b2b25c92cd7e353c71e1ffccbff1e54f | nikaysd1ab/beroepsopdracht- | /tekst apelecatsie verhaal over imigrant.py | 3,089 | 4 | 4 |
print("geboren in amirika arazona ")
print("gang gewled, ik loop weg,niet weg lopen")
choice = input()
if choice == 'ik loop weg':
print(" je loopt weg en er gebeurd niks")
elif choice == 'niet weg lopen':
print(" ik word dood geschoten, start progamma opnieuw op")
else:
print(choice, "print wa... |
5d42d3f701d61188a7edee1305ca57695fb5c664 | tasbihaasim/Probability-Project | /task3.py | 2,242 | 3.65625 | 4 | import math
import random
import numpy as np
import matplotlib.pyplot as plt
class RandomWalk:
def __init__(self, l, R, seed=1000):
self.l = l
self.R = R
self.seed = seed
self.max_steps = 1000
self.x = None
self.y = None
def walk(... |
b590c51de02e2136763ffab5b28091f99b2d6d3c | rupagorthi/loops-files | /demo2.py | 115 | 3.90625 | 4 | #Print sum of all odd numbers from 1 to 10
sum=0
for i in range(1,10):
if i%2==1:
sum=sum+i
print (sum) |
b29d8d660f5b279769f22d39d2d03dbddc4a712a | Stepze/Frontend-Demo | /AbstractConnection.py | 904 | 3.921875 | 4 | # -*- coding: utf-8 -*-
from abc import ABC, abstractmethod
##
## @brief abstract class to show the usage of the connection interface.
##
class AbstractConnection(ABC):
##
## @brief Both ends of the connection are needed to have an unique id, with which they register at the connection object so that it... |
2d410d4172d0a7f66dd9e38ebb5d9ee479e77eef | kpatro/datastructure-python | /BinaryTree.py | 3,789 | 3.828125 | 4 | class BinarySearchTree:
def __init__(self, data):
self.value = data
self.left = None
self.right = None
def add_child(self, par):
if self.value == par:
return # node already exists
# traverse right
if par > self.value:
if self.right:
... |
18a801330b88f22dde6d85e1f0259ef8edb69234 | pzqkent/LeetCode | /24.py | 829 | 3.703125 | 4 | class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
pre = new_head = ListNode(0)
while head and head.next:
tmp = head.next
head.next = tm... |
d8b281a78ac6bdbc54de3516a9c2888c5965dc15 | pzqkent/LeetCode | /20_new.py | 897 | 3.765625 | 4 | class Solution(object):
def isValid(self, s):
if s == []:
return False
elif len(s) % 2 == 1:
return False
stack = []
a = {')':'(',']':'[','}':'{'}
for i in s:
if i in a.values():
stack.append(i)
else:
... |
af918eab91f5eba556a685f5c3d7c08f31bc16d3 | pzqkent/LeetCode | /179_python3.py | 982 | 3.515625 | 4 | # class Solution:
# def largestNumber(self, nums):
# from functools import cmp_to_key
# # nums.sort(key = cmp_to_key(lambda a,b: int(str(b)+str(a)) - int(str(a) + str(b))))
# # nums.sort(key = lambda a,b: int(str(b)+str(a)) - int(str(a) + str(b)))
# return ''.join(map(str,so... |
035eb13e6d9aa8429a0a1595c8317291196a6765 | pzqkent/LeetCode | /python_heap.py | 297 | 3.609375 | 4 | import heapq
heap = []
data = [1,3,5,7,9,2,4,6,8,0]
for i in data:
heapq.heappush(heap,i)
print(heap)
lis = []
while heap:
lis.append(heapq.heappop(heap))
print(lis)
data2 = [1,5,3,2,9,5]
heapq.heapify(data2)
print(data2)
lis2 = []
while data2:
lis2.append(heapq.heappop(data2))
print(lis2) |
d6441e82135b0f4804db56514e0837cd6c12b821 | pzqkent/LeetCode | /56.py | 1,277 | 3.859375 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
intervals = sorted(intervals,key = lambda x : x.start) #对intervals 进行排序
i = 0 #指针1指向第一个interval
... |
f0f15122306ab2e267ca96ff57a4e1a1b463c978 | pzqkent/LeetCode | /58.py | 343 | 3.5625 | 4 | class Solution:
def lengthOfLastWord(self, s):
if list(s.split()) == []:
return 0
else:
# return len(list(s.split(''))[-1]) if len(list(s.split(''))[-1]) != 0 else len(list(s.split(''))[-2])
return len(list(s.split())[-1])
"""
:type s: str
... |
501cc030a32988fb537bb2a0e0e3a6e0e5d31591 | yulqen/pledgertools | /scripts/comma_check.py | 447 | 3.609375 | 4 | #!/usr/bin/env python3
import sys
if sys.argv[-1].split("/")[-1] != "TransHist.csv":
print("Target file must be TransHist.csv")
sys.exit(1)
with open(sys.argv[-1], "r", encoding="utf-8") as f:
comma_count = 0
for line in f.readlines():
for char in line:
if char == ",":
... |
008e1b81b31166e4c19414d40f950d95b44ad5fe | bhushangy/coursera-python | /datastruc/lastass.py | 299 | 3.953125 | 4 | count = 0
total = 0
while True:
x=input('Enter number')
if x=='done':
break
else:
try:
x = int(x)
except:
print('enter only numbers or done')
continue
count = count+1
total = total+x
print(count,total,count/total)
|
59876ae3e02a35305541c8cb543ef047b41764a5 | gumbernator/MLP-from-scratch | /mlp/layer.py | 733 | 3.546875 | 4 | import numpy as np
class Layer:
def __init__(self, input_num, neuron_num, activation):
self.weight = (np.random.rand(input_num, neuron_num) - 0.5) / 10
self.bias = (np.random.rand(1, neuron_num) - 0.5) / 10
self.activation = activation
self.neuron_num = neuron_num
... |
62f9cca5ef39e633b5a20ffd6afb27772a5291fc | NikolaosPanagiotopoulos/python-examples-1 | /Addition.py | 225 | 4.21875 | 4 | #this program adds two numbers
num1=input('Enter first number: ')
num2=input('Enter second number: ')
#Add two numbers
sum=float(num1)+float(num2)
#display the sum
print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
|
f51bf20e06211896da748fc6a01d187327ee1a35 | allysonvasquez/Python-Projects | /2-Automating Tasks/FileIO.py | 1,230 | 3.828125 | 4 | # author: Allyson Vasquez
# version: May.26.2020
# NOTES: File I/O
# Opening a file
helloFile = open('/Users/allysonvasquez/Documents/Code/PyCharm Projects/Python-Basics/2-Automating Tasks/hello.txt')
# Reading a file
helloContent = helloFile.read()
helloFile.close()
print(helloContent) # output hello world
# Writi... |
14765ce398a35e4730122fb867cd45d386d19c7f | allysonvasquez/Python-Projects | /2-Automating Tasks/PhoneAndEmail.py | 852 | 4.15625 | 4 | # author: Allyson Vasquez
# version: May.15.2020
# Practice Exercises: Regular Expressions
# https://www.w3resource.com/python-exercises/re/index.php
import re
# TODO: check that a string contains only a certain set of characters(a-z, A-Z and 0-9)
charRegex = re.compile(r'\d')
test_str = str('My name is Allyson and ... |
ca80170c8c55eecf29d23e5e218b118c488c9cc8 | juanvasquez2015/Python_FinalProject_JuanEVasquez | /ui.py | 3,866 | 3.734375 | 4 | #!/usr/bin/env/python3
import db
from objects import Item
def display_title():
print("The Grocerie List program")
print()
display_menu()
def display_menu():
print("COMMAND MENU")
print("store - View items by store")
print("type - View items by type")
print("cost - View... |
8a9266e7ad9d8fec559191f895ac8e57ad26d161 | 2019jrhee/FINAL | /dna.py | 210 | 3.546875 | 4 | #DNA_stand ("ATTGC") # return "TAACG"
# a and t
# c and g
dna = {'a':'t', 'c':'g'}
# counter = 0
# dna2 = ""
# while len(dna) > counter:
for x in dna:
if x == "A":
dna2.append("T")
|
19c73070b442983d8c2e8f3f514061209389925e | 2019jrhee/FINAL | /mystery.py | 110 | 3.515625 | 4 | def mystery (N):
k = 0
while (k < N) and (N % 2 == 0):
print(k)
k += 1
return (5)
|
52df096a041e622a6a7f67d6d1f9bc364401ebca | 2019jrhee/FINAL | /guess.py | 282 | 4.0625 | 4 | import random
count = 0
Guess = int(input("Guess a number from 1 to 100:"))
Correct = random.randint(0,100)
while Guess != Correct:
Guess = int(input("Guess again:"))
if(Guess > Correct):
print('lower')
elif(Guess < Correct):
print('higher')
else:
print('yeah')
|
3cbfcecadb981cf4d080abda70fab76a1259e077 | 2019jrhee/FINAL | /bfs.py | 918 | 3.859375 | 4 | # keep looping until all paths have been checked
def bfs(graph, start, goal):
# keep track of all visited nodes
explored = []
# keep track of nodes to be checked
queue = [start]
# keep looping until all paths have been checked
while queue:
# dequeue the first path from the dequeue
... |
be1db92b236d8852a96e602bb75bde04a1495a08 | 2019jrhee/FINAL | /astar.py | 1,820 | 3.75 | 4 | import time,random
start_time = time.time()
def path_finder(matrix):
# input 2D array full of integers
# integer element = cost of movement
length = len(matrix)
goal = (length-1, length-1)
# first two coordinate, third one is the cost, last is heuristics
start = (0,0,0,0)
# store the cost ... |
a81baa8a1d4f47527d98a8bfbb886d680104fdf6 | alex-aleyan/python | /books/python_crush_course/ch_01_thru_10/10_00_fileio.py | 16,561 | 4.40625 | 4 | #Simplly prints the message:
hello_message_str="Hello Python World!"
print(hello_message_str)
hello_message_str="Reusing the var to hold a new message!"
print(hello_message_str)
name="ada lovelace"
#Capitalize 1st letter of every word: "ada lovelace" -> "Ada Lovelace"
name=name.title()
print(name)
#Capitalize all l... |
ce92cf4a7ab73a2fe8ad859d2c0bc1f408c91dc3 | kristofkalocsai/cmdline-battleships | /battleships.py | 4,065 | 3.96875 | 4 | from random import randint
board = []
board2 = []
for x in range(10):
board.append(["O"] * 10)
board2.append(["O"] * 10)
def print_board(board):
for row in board:
print " ".join(row)
def print_board2(board):
for row in board:
print " ".join(row)
player = {
'ship1' : [],
... |
6e9f112030c013bee79a7a29c27f50bb9fa70845 | dmlogv/particles | /particles.py | 966 | 3.703125 | 4 |
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if not isinstance(other, self.__class__):
raise TypeError('Unsupported operand type for +: {self} and {other}',
self=self.__class__.__name__,
... |
d787b6172e44d232317988069edf416ca276f51e | FelipeECarvalho/Primeiros-Projetos | /Estrutura de Dados/ordenacao_insercao.py | 336 | 3.984375 | 4 |
def insertion_sort(lista):
n = len(lista)
for i in range(1, n):
chave = lista[i]
j = i - 1
while j >= 0 and lista[j] > chave:
lista[1+ j] = lista[j]
j -= 1
lista[j + 1] = chave
return lista
array = [4, 1, 2, 7, 54, -1, 3, 4, 2, 1, 0, 10]
print(insert... |
522b10006356b89e7ae70c866efdebe91bab8968 | Irwin1985/Pylox-1 | /src/pyLox/input_util.py | 814 | 3.84375 | 4 | '''
The module houses 3 utility functions that are used in the Lox Native Library input function - read.
'''
def _typify(string: str):
if string == 'nil':
return None
value = convert_to_number(string)
if type(value) is float:
if value.is_integer():
return int(value)
return va... |
c6cabbc2f2874ad0e3f3370881b05bdc124eac6e | cjawesomest/data_structures_and_algorithms | /Dictionaries, Graphs and Hash Tables/closedhash.py | 7,359 | 3.75 | 4 | #!/usr/bin/python3
# Cameron J. Calv
# Assignment 3
# CS260 Data Structures
# Project Problem 2: Closed Hash Table Dictionary Implementation
import string
import random
last_probe_number = 0
def hash(bucket_number, character_string):
sum = 0
for character in character_string:
sum = sum + ord(charact... |
8a7e24eaec40685af2a13752636b9b403427076d | cjawesomest/data_structures_and_algorithms | /Queues and Trees/listconcat.py | 2,361 | 4.0625 | 4 | #!/usr/bin/python3
# Cameron J. Calv
# Assignment 2
# CS260 Data Structures
# Project Problem 5: Textbook Problem 2.4
from arraylist import arrayList
# Function to concatenate a list of lists
def listconcat(list_of_lists):
# Start with a Null list
concatenated_list = arrayList([])
index = 1
outer_f... |
d8120ff57e7ba5bfd04a79a0919d152b01516404 | cjawesomest/data_structures_and_algorithms | /Queues and Trees/timing.py | 8,863 | 3.8125 | 4 | #!/usr/bin/python3
# Cameron J. Calv
# Assignment 2
# CS260 Data Structures
# Project Problem 3: PreOrder and PostOrder Timing
import time
from loctree import loctree
from lcrstree import lcrstree
# Accepts a tree as a parameter and returns the pre-order of the tree's labels
# Assumes that the tree is not the Null... |
c36172a0a429a3b3fb4a47464f7516ea21f3aac3 | OscarDani/EjerciciosUnidad3 | /03 Creational Patterns/AbstractFactory.py | 1,684 | 4.15625 | 4 | # AbstractFactory.py
class Dog:
"""A simple dog class"""
def speak(self):
return "Woof!"
def __str__(self):
return "Dog"
class Cat:
"""A simple cat class"""
def speak(self):
return "Maow!"
def __str__(self):
return "Ca... |
78b4fd0149b808b9351472efa51a0c8b657a93d9 | 101guptaji/Bioinfoinformatics | /Coursera assignment/Q2_hamming_dist.py | 257 | 3.703125 | 4 | fname='hamming.txt' #input("file name")
fhand=open(fname,'r')
a1=fhand.readline()
a2=fhand.readline()
count=0
if(len(a1)==len(a2)):
for i in range(len(a1)):
if(a1[i]!=a2[i]):
count+=1
else:
print("input strings are of different length")
print(count)
|
bf0c19db6beff1cde450c81f871c95adc93ec051 | 101guptaji/Bioinfoinformatics | /lab3/count_dna.py | 215 | 3.890625 | 4 | # Python code to count A,C,G,T in dna string
f=input("enter file name")
file = open(f, "r")
n=file.read()
print(n)
print(len(n))
a=n.count("A")
c=n.count("C")
g=n.count("G")
t=n.count("T")
print(a,c,g,t,sep=" ")
|
8433e99b2c57222edcf3d0ad2587a0c458d43600 | foleydavid/Pong | /pong_player.py | 2,009 | 3.59375 | 4 | import pygame
import random
class Player:
def __init__(self, ai):
#INITIALIZE BASED ON IF IS COMPUTER OR HUMAN PLAYER
self.image = pygame.image.load("player.png")
if ai:
self.x = 720
self.y = 350
self.x_len = 40 # pixels
self.y_len = 100 # ... |
890c9340c02cec9ea876e565a52d35aa549ac1ce | JoshBoss/SDG-E-Software | /SourceCode/Pi-Programs/piServer.py | 760 | 3.640625 | 4 | import socket #Import the socket module
import RPi.GPIO as GPIO #Import GPIO module
#Setup pin 18 (BCM) as output
LEDPin = 18;
GPIO.setmode(GPIO.BCM);
GPIO.setup(LEDPin, GPIO.OUT);
s = socket.socket(); #Create a socket object
host = socket.gethostname(); #Get local machine name
port = 12345; #Reserve a por... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.