blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
61a2d136c424dd22879900020fa5d846e5384103 | MillicentMal/alx-higher_level_programming-1 | /0x01-python-if_else_loops_functions/100-print_tebahpla.py | 99 | 3.765625 | 4 | #!/usr/bin/python3
for i in range(0, 26, 2):
print("{:c}{:c}".format(122-i, 89-i), end='')
|
caf493232358a30eb08b99fc7ce8d60c41c64f92 | javaInSchool/python1_examples | /les4/example3.py | 380 | 3.78125 | 4 | bitcoin = 45000
print("Очень дорогой биткоин, подождем")
while ( bitcoin > 35000 ):
bitcoin = bitcoin - 1
print("Падает до : " + str(bitcoin) )
print("О, цена подходит, куплю биткоин")
while( True ): # бесконечный цикл
bitcoin = bitcoin + 1
print("Падает до : " + str(bitcoin))
|
1cdc7fc72a077976521d96334aaba9f292f4e46f | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/amitness/ML-From-Scratch/mlfromscratch/examples/genetic_algorithm.py | 1,265 | 3.75 | 4 | from mlfromscratch.unsupervised_learning import GeneticAlgorithm
def main():
target_string = "Genetic Algorithm"
population_size = 100
mutation_rate = 0.05
genetic_algorithm = GeneticAlgorithm(target_string, population_size, mutation_rate)
print("")
print("+--------+")
print("| GA |")... |
9bfea64d9237814ddf272ae64278314eda0e3c20 | sysinit2811/python | /while_1.py | 159 | 4.03125 | 4 | num = 0
input_str = raw_input('inpu a number: ')
while input_str !='pc':
num = num + int(input_str)
input_str = raw_input('input a number: ')
print num |
ad13fb3a13059b2156b4572b93d92542d0c1e87e | kaioschmitt/programming-logic | /python/if_else/if_else#01.py | 297 | 4.1875 | 4 | st_number = input('Insert the first number: ')
nd_number = input('Insert the second number: ')
if st_number > nd_number:
print(f"{st_number} is greater than {nd_number}")
elif st_number < nd_number:
print(f"{st_number} is less than {nd_number}")
else:
print('The numbers are equals')
|
9517019e77b42bf83110b18e3ea916ceac5abefd | Vandor13/SmartCalculator | /Problems/Memory test/main.py | 225 | 3.875 | 4 | numbers = input().split()
answers = input().split()
correct_set = set()
for number in numbers:
correct_set.add(number)
answer_set = set()
for answer in answers:
answer_set.add(answer)
print(correct_set == answer_set)
|
ea66d04a2376ba101a23604d7ffc74d8609e1d4d | riddhitg/c99 | /fileOrganiser.py | 714 | 4.15625 | 4 | import os
import shutil
#enter the name of the folder to be sorted
path = input("enter the name od the directory to be sorted: ")
#list of all the files and folders in the directory
list_of_files = os.listdir(path)
#go through each and every file
for file in list_of_files:
name,ext = os.path.splitext(... |
7069c7621cdecf2b25337f05fddaeb3321002ac6 | cntsp/homework | /day7/ftpclient/core/main.py | 4,490 | 3.5625 | 4 | import socket
import os
import json
import hashlib
from authentication import User
import commands
class FtpClient(object):
"""
define the ftpclient class
"""
def __init__(self, host="localhost", port=9999):
self.client = socket.socket()
self.host = host
self.p... |
1d3bbb5b0674386fb991f14cd49d1ec97f665628 | barthezz16/python_base_lessons | /lesson_004/02_global_color.py | 3,435 | 3.703125 | 4 | # -*- coding: utf-8 -*-
import simple_draw as sd
sd.set_screen_size(900, 900)
# Добавить цвет в функции рисования геом. фигур. из упр lesson_004/01_shapes.py
# (код функций скопировать сюда и изменить)
# Запросить у пользователя цвет фигуры посредством выбора из существующих:
# вывести список всех цветов с номерам... |
b51e5ad59569d99b72c5f092211adf593e999526 | jsburckhardt/theartofdoing | /22_database_admin_app.py | 1,199 | 4.09375 | 4 | # Greeting
app = "Database Admin"
print(f"Welcome to the {app} app!\n")
database = {
"mooman74": "alskes145",
"meramo1986": "kehns010101",
"nickyd": "world1star",
"george2": "boo3oha",
"admin00": "admin1234",
}
# input from user
username_input = input("Enter your username: ").strip().lower()
if username_in... |
7ee0f54fa1a968f1b27eb75caba8f2f3eda16d56 | ctec121-spring19/programming-assignment-3-loops-and-numerics-Treydog14 | /Prob-5/Prob-5.py | 666 | 3.828125 | 4 | # Module 2
# Programming Assignment 3
# Prob-5.py
# Trevor Bromley
def main():
slice = 2.0
largeDrink = 1.5
donut = .56
sum = 0
print("Pizza @ 2:\t", slice * 2)
sum = slice * 2
print("Drink:\t\t", largeDrink)
sum = sum + largeDrink
print("Donut @ 2:\t", donut * 2)
sum = s... |
834f749d67710093e7b99f02a6bf33e24b191716 | raghav-menon/EPAiSession11 | /Polygon_Sequence.py | 2,400 | 4.34375 | 4 | from Polygon import Polygon
class Polygons:
"""Implementaion Of Custom Sequence of Polygons which takes largest \
polygon num of edges and circumradius as input"""
def __init__(self, m, R):
""" Function initialising the number of edges and circumradius"""
if m < 3:
... |
439328ae5f819e5284635239d8417b536ade66f4 | anchuanxu/Python-Elementary-Exercise-100-Questions | /PycharmProjects/test11-20/11.py | 146 | 3.859375 | 4 | # 斐波那契数列
f1=1
f2=1
for i in range(1,22):
print('%12ld%12ld'%(f1,f2))
if(i%3==0):
print (' ')
f1=f1+f2
f2=f1+f2 |
9d69eb04b9a7b7d7f6eb6600a56da563ab779e22 | HyunAm0225/Python_Algorithm | /정렬/quick.py | 995 | 3.78125 | 4 | array = [5,7,9,0,3,1,6,2,4,8]
def quick_sort(array,start,end):
if start >= end: # 원소가 1개인 경우 종료
return
pivot = start # 피벗은 첫 번째 원소
left = start + 1
right = end
while left <= right:
# 피벗보다 큰 데이터를 찾을 떼 까지 반복
while left <= end and array[left] <= array[pivot]:
left +... |
bfa6cfb66cef59a155d506921ecc25c40a747b66 | pedroromn/pywork | /pycode/decimal_to_binary.py | 499 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Date: 28/08/2015
author: peyoromn
"""
def decimal_to_binary(decimal):
bstring = ""
while decimal > 0:
remainder = decimal % 2
decimal = decimal / 2
bstring = str(remainder) + bstring
return bstring
def main():
decimal = input("En... |
43f85f9eb32c0ef8f9ea1fce5fad2156d79bee31 | arnogils/language-detector | /tests/detector_tests.py | 823 | 3.609375 | 4 | import unittest
from language_detector import LanguageDetector
class LanguageDetectorTests(unittest.TestCase):
def setUp(self):
self.detector = LanguageDetector()
def test_language_not_detected(self):
self.assertEqual('Language not detected', self.detector.guess_language(''))
def test_d... |
0f26fe81ca67b4b96b837cefc21c35a1edae5a19 | daltonb3657/cti110 | /M2HW1_DistanceTraveled_BrandonDalton.py | 416 | 3.8125 | 4 | # CTI-110
# M2HW1 - Distance Traveled
# Brandon Dalton
# 9/10/2017
#
speed = 70
distanceAfter6 = speed * 6
distanceAfter10 = speed * 10
distanceAfter15 = speed * 15
print('The distance the car will travel in 6 hours is', distanceAfter6, 'miles')
print('The distance the car will travel in 10 hours is', distanc... |
926d25f9424fb88283a55a61ba4d9fa7bc550cda | wuxu1019/leetcode_sophia | /dailycoding_problem/XOR_linkedlist.py | 1,654 | 4.125 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XO... |
4a38969ab9e1cbe958faedc81a168c678fa07ff9 | pingyangtiaer/DataStructureAlgorithmDesign | /python/QuickSort.py | 671 | 3.953125 | 4 | #!/usr/bin/env python
def partition(ls, l, r):
# choose the last element as pivot
pivot = ls[r]
#due to the fact that we input the full array every time,
#beware of the lower and upper label of this range
for i in xrange(l, r):
if ls[i] < pivot:
ls[l], ls[i] = ls[i], ls[l]
... |
a210ac26b30cf43767a3993db5f2944be9ddb1b0 | chaofan-zheng/tedu-python-demo | /month02/day11/exercise01_server.py | 997 | 3.640625 | 4 | """
练习3:上传头像的练习
假设客户端需要将自己的头像上传给服务端
请编写程序完成该工作,在服务端以当前日期
保存为jpg格式 2020-12-10.jpg
客户端: 读文件 发送文件内容
服务端: 接收文件内容 写入本地
"""
from socket import *
from time import localtime
# 接收文件 (具体事件)
def recv_image(connfd):
# 组织文件名
filename = "%s-%s-%s" % localtime()[:3] + ".jpg"
file = open(filename, "wb")
while ... |
60f7fed644c7d5b7e7af1ed2205095b35e2dd276 | artbohr/codewars-algorithms-in-python | /7-kyu/tram-capacity.py | 1,696 | 3.90625 | 4 | def tram(stops, descending, onboarding):
on_board = 0
max_cap = 0
for x in range(stops):
on_board -= descending[x]
on_board += onboarding[x]
if on_board > max_cap:
max_cap = on_board
return max_cap
'''
Linear Kingdom has exactly one tram line. It has n stops, numbe... |
5c124e2205548c5d19f19798abc5fbb44f057d51 | zhongshj/leetcode | /101-150/141.linked-list-cycle.py | 665 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
# go through the list and set each .next ... |
8bdb5a76063373bb0439763ad6eae72ceb38f078 | yedidimr/machineLearning | /python_ex/game_of_life_3d.py | 1,005 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
n=100 #size
# starting board
A = np.random.choice(a=[0,1], size=n*n*n).reshape(n,n,n)
movements = equals to [(i,j,k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0, 1) if (i !... |
23a45fd8cfa7929b52dab07ba67e9fb9e03dc1f4 | robertdahmer/Exercicios-Python | /Projetos Python/Aulas Python/Estudos aleatórios/Desafio 052.py | 391 | 3.828125 | 4 | #Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
primo = int(input('Digite número: '))
tot = 0
for c in range(1, primo + 1):
if primo % c == 0:
print('\033[34m', end='')
tot += 1
else:
print('\033[m', end='')
print('{} '.format(c), end='')
print('\... |
7420f15ff987219d1740af6e17a55bfbd69117d2 | seanwentzel/crypto-hons | /tut6-elgamal/q3_helper.py | 999 | 3.671875 | 4 | def f(u, g, a, m, b_1, b_2):
if u <= b_1:
return (g*u % m, 1)
if u <= b_2:
return (u**2 % m, 2)
return (a*u % m, 3)
def exponents(b,c,m, set_num):
if set_num == 1:
b = (b + 1) % m
if set_num == 2:
b = (2*b) % m
c = (2*c) % m
if set_num == 3:
c = (... |
410fd3f9dd7a1c422088012e32111a1b6794afde | Alek-dr/GraphLib | /core/algorithms/bfs.py | 1,497 | 3.578125 | 4 | from collections import OrderedDict, deque
from typing import Dict, Union
from core.exceptions import VertexNotFound
from core.graphs.graph import AbstractGraph, edge
from core.graphs.walk import Walk
def bfs(
graph: AbstractGraph,
origin: Union[str, int],
target: Union[str, int] = None,
) -> Dict[Union[... |
0a12df3a8504a68b53dea8efde0dec73ec41d29e | ErickS05/EjerciciosFinal | /Ejecicios -Modulo 2/python mario.py | 268 | 3.953125 | 4 | n = 0
while n < 8:
numero = int(input('Ingresa numero entero '))
validos = [1, 2, 8]
if numero in validos:
for i in range(1,numero+1):
print(" " * (int(numero) - i) + '#' * int(i))
else:
print('entrada invalida')
|
a269ee21ff2bbdf4b6791bfb2719eb03543cfeee | ReethP/Kattis-Solutions | /fizzbuzz.py | 228 | 3.546875 | 4 | uint = input().split()
a = int(uint[0])
b = int(uint[1])
c = int(uint[2])
for i in range(1,c+1):
if(i%a ==0 and i%b == 0):
print("FizzBuzz")
elif(i%a == 0):
print("Fizz")
elif(i%b == 0):
print("Buzz")
else:
print(i) |
91c16bec74c4cd322c710709c225e0ff23feb805 | yxtay/how-to-think-like-a-computer-scientist | /Files/files_ex3_students_minmax.py | 302 | 3.546875 | 4 | def int_list(lst):
outlist = []
for el in lst:
outlist.append(int(el))
return outlist
infile = open("studentdata.txt")
line = infile.readline()
while line:
values = line.split()
scores = int_list(values[1:])
print values[0], min(scores), max(scores)
line = infile.readline()
infile.close() |
8a8beff978f204b4f8c1ee568b65fd310b40c26f | SamriddhiMishra/DSA-Solutions | /Recursion/Day-2/power_set.py | 471 | 3.65625 | 4 | # I - Array , O - Power Set(Including Empty)
# Time- O(n*n) Space - O(n *2^n)
def power_set(arr, n):
if n >= len(arr):
return [[]]
f = arr[n]
p = power_set(arr, n+1)
for i in range(len(p)):
if len(p[i]) == 0:
p.append([f])
else:
e = p[i].copy() ... |
8682381712edd47790aff3efb48e4ae76cbe6ff2 | yosef8234/test | /hackerrank/python/data-types/tuples.py | 1,168 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# Tuples are data structures that look a lot like lists. Unlike lists, tuples are immutable (meaning that they cannot be modified once created). This restricts their use because we cannot add, remove, or assign values; however, it gives us an advantage in space and time complexities.
# A common... |
807cc52470006b68d445a214936b6bc2d429f4aa | r3mas/python_tutorial | /codecademy/lesson10.py | 177 | 3.890625 | 4 | my_dict = {
"Name": "Guido",
"Age": 56,
"BDFL": True,
"Lazy": True
}
print my_dict.keys()
print my_dict.values()
for key in my_dict:
print key,my_dict[key] |
18eedfd78d64a85eae2a9a32fd40283c358c8f22 | krivchnik/visualization_task | /visualizer/visualizer.py | 10,098 | 3.578125 | 4 | import random
import numpy
import scipy
from math import sqrt
class Node:
def __init__(self):
self.mass = 0.0
self.old_dx = 0.0
self.old_dy = 0.0
self.dx = 0.0
self.dy = 0.0
self.x = 0.0
self.y = 0.0
class Edge:
def __init__(self):
self.node1 ... |
ca2bcc330503cfdfa17873899988535bd2c11ace | crrimson/hello-world | /simple_stack.py | 3,200 | 4.3125 | 4 | #
# implement a stack in python
class StackNode():
""" a node in a stack """
def __init__(self, value, next_node=None):
self.value = value
self.next_node = next_node
def get_next_node(self):
return self.next_node
def get_value(self):
... |
8b473b420a92c32e453225683d6022fc0cabb9c6 | Sourav-28/python-flask | /Day_7.py | 505 | 3.828125 | 4 | #task-1
# a=input("Enter a string: ")
# list1=['a','e','i','o','u']
# b=a.lower()
# list2=[i for i in range(len(b)) for j in list1 if b[i]==j]
# print(list2)
#task-2
# b=input("Enter a string: ")
# l=b.split()
# for i in l[::-1]:
# c=i
# print(c,end=" ")
#task-3
q=int(input("Enter how many n... |
be9bec23d7614aa6256aec1cdc903192439e292b | dnjsdos/MachineLearning | /softmaxonehot.py | 1,060 | 3.53125 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./data/", one_hot=True)
x = tf.placeholder(tf.float32, shape=[None, 784])
y = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros(shape=[784, 10]))
b = tf.Variable(tf.zeros(shape=[1... |
43ce7dbc591e228d96bf23113c029396613d5534 | fedorsirotkin/BookHelloPython | /3_Операторы/3_4_Цикл_WHILE.py | 367 | 3.71875 | 4 | # Угадай лучший автомобиль
print("Угадай лучший автомобиль")
print("Название автомобиля нужно вводить строчными буквами")
response = ""
while response != "bmw":
response = input("Какой авто самый лучший?: ")
print("Ура! Вы это сделали!") |
65f7383cb4a55862354fa15c88e5275b209c31b5 | arielmad/Coding-1 | /first.py | 310 | 4.0625 | 4 | print("Hello World!")
print("My name is Ariel")
print("ham sandwich")
print("hi")
print("Hello")
print("My name is Ariel")
print("I am 13 years old")
celsius=eval(input("Enter a temperature in degrees celsius: "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit , "degrees Fahrenheit.")
|
a634cd2b7ae644784929ee4178407ce7011e8d83 | ramboozil/python-learn-notes | /lesson2.py | 544 | 4 | 4 | #/usr/bin/env python3
# -*- coding: utf-8 -*-
l=['java','php','python','c++']
print(l[-1])
print(l[-2])
print(len(l))
str = 'java,php,python,c++'
a,b,c,d = str.split(',')
print('\t'.join([a,b,c,d]))
l.append('kotlin')
print(l)
l.insert(2,'c#')
print(l)
l.pop(-1)
print(l)
m=['java','php',['kotlin','c++']]
print(len(m)... |
b0ee525a0029ee414cbd3ba98862d76bb34dbad7 | NaiveteYaYa/data-structrue | /38. 外观数列.py | 1,443 | 3.5 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/3/25 20:19
# @Author : WuxieYaYa
"""
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
1 被读作 "one 1" ("一个一") , 即 11。
11 被读作 "two 1s" ("两个一"), 即 21。
21 被读作 "one 2", "one 1" ... |
f4a3693fbe42a9a9d8c2c295992c40bb29614828 | gagandeepsinghbrar/codeSignal | /rotatingBox.py | 3,730 | 3.8125 | 4 | '''
You need to move a large rectangular box over a rough, hazardous surface. Since you don't have any tools to help you move it, your only option is to perform a series of 90 degree rotations (basically just repeatedly pushing the box over onto its side).
Every time you rotate the box, it hits the ground and some da... |
34f1ef558aaeda44f8a44a451f58e82227a5955a | hubert-cyber/EjerciciosEnPython | /Ejercicio17.py | 726 | 3.515625 | 4 | #define datos de entrada
print("Ejercicio 17")
#datos de entrada
paqueteA="A: 1 televisor, 1 modular, 3 pares de zapatos, 5 camisas y 5 pantalones"
paqueteB="B: 1grabadora, 3 pares de zapatos, 5 camisas y 5 pantalones"
paqueteC="C: 2 pares de zapatos, 3 camisas y 3 pantalones"
paqueteD="D: 1 par de zapatos, 2 pares de ... |
f795d9f90b722053b4f4a1266d4395bccb267fae | Wef2/ProjectEuler | /python/problem020.py | 119 | 3.546875 | 4 | value = 1
result = 0
for i in range(1, 101):
value *= i
for i in str(value):
result += int(i)
print(result)
|
c756f72b97777be0b09770fb1ed338348f928815 | tobiascarson/beuler | /p10.py | 276 | 3.75 | 4 | #!/usr/bin/python
def isprime(n):
n = abs(int(n))
if n < 2: return False
if n == 2: return True
if not n & 1: return False
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0: return False
return True
max=2000000
print sum(i for i in range(max) if isprime(i))
|
09caed61bed1a406069fe6107ad32426991e782f | christinabranson/hackerrank-python | /PythonCertificate/SampleQuestions/StringAnagram/StringAnagram.py | 912 | 4 | 4 | #!/bin/python3
def getAnagrams(dictionary, queries):
anagram_counts = []
sorted_dictionary = {}
for word in dictionary:
sorted_word = "".join(sorted(word))
if sorted_word in sorted_dictionary:
sorted_dictionary[sorted_word] += 1
else:
sorted_dictionary[sorte... |
88cf9d94601d100f27b20fe33e5f972d01570381 | brosiak/genetic-algorithm | /Flight.py | 3,358 | 3.671875 | 4 | import datetime
import time
class Flight:
def __init__(self, flight_type = '', airline = '', sequence_number = 0, flight_number = '', airplane_type = '', unit_loss = 0, estimated_time = 0, actual_time = 0, runway = -1, delay_losses = -1, relation = {} ):
"""Intialization of flight
Keyword A... |
174987f3891c7ad0c33f0eed21df029e83fdf5a1 | lukkerr/clientes-python | /funcoes.py | 7,789 | 3.53125 | 4 | ###Testar se Existe determinado Contéudo no Texto###
def validador (arqtexto,x):
#Find - Procura Contéudo da Varíavel X no Arqtexto e Retorna sua Posição
resultado = arqtexto.find(x)
#Resultado Igual a -1 se Contéudo não for Encontrado no Texto
if resultado==-1:
resultado = False
#Se Diferen... |
9242aef96ac166d90675f9f33ff9979c1ecbd4a3 | atfost3r/AutomateTheBoringStuff | /AutomatingTasks/Chapter_11/lucky.py | 607 | 3.53125 | 4 | #! /usr/bin/python3
#lucky.py - Opens several Google search results.
import requests, sys, webbrowser, bs4, pyperclip
search = 'python programming tutorial'
print('Googling...') # display text while downloading the google page
res = requests.get('http://google.com/search?=' + ''.join(search))
res.raise_for_status()
... |
409f67723d5479566826bcd909eac84cea0d99b0 | Natsu1270/Codes | /Hackerrank/LinkedList/DeleteNode.py | 505 | 3.796875 | 4 | from LinkedList import *
def deleteNode(head,pos):
if pos == 0:
return head.next
temp = head
prev = None
while pos > 0:
prev = temp
temp = temp.next
pos -= 1
prev.next = temp.next
del temp
return head
def deleteNodeRec(head,pos):
if pos == 0:
... |
98f126a5af9defbf167520554060bcc1f868ca88 | N-Shilpa/python | /Hello1.py | 84 | 3.671875 | 4 | i=10
j=20
if(i<j):
print(i)
print(j)
print(i+j)
else:
print("hello")
|
cf32d5269f46fe11b5dc6d83c41cad7fbed3fc36 | h0cem/flaskProject | /genetic_algo.py | 22,123 | 3.5 | 4 | import sys
import random
import tools as t # covid graph
from termcolor import colored
import numpy as np
import matplotlib.pyplot as plt # to plot
from datetime import datetime, timedelta
class GA:
"""
size: population size
graph: covid graph that was created randomly
n: numpy vector have id of nod... |
ccff9acce2bdffcc3bf280d02ef6cf3a237cb9e5 | deltonmyalil/PythonInit | /filters.py | 791 | 3.8125 | 4 | from random import randint
newlist = [randint(1,50) for x in range (10)]
print(newlist)
evenNos = list(filter(lambda x: x%2==0,newlist)) #filter chose the els of the list where the boolean condition of the lambda returned true
print(evenNos)
def isOdd(n):
if n%2 == 0:
return False
else:
return ... |
5c286f457c579ce1e72d18b5536fc6b32fdc6f00 | iffatunnessa/Artificial-intelligence | /lab3/New folder/s3p1.py | 691 | 4.15625 | 4 | # Writing to and reading from a file in Python
f1=open('stdfile.py', "w")
print("\n")
for i in range(2):
name=str(input("Enter the name:"))
dept=str(input("Enter the department:"))
cgpa=str(input("Enter the cgpa:"))
std=name+"\t"+dept+"\t"+cgpa
print(std, end="\n", file=f1)
... |
2a72ab16ed90046f93d9b17f910d2b1927c336f7 | sungsikyang92/pythonStudy | /CodeUp/1366_0222.py | 644 | 3.859375 | 4 | n = int(input())
#첫째줄
for x in range(n):
print("*", end="")
print()
#중간영역1
for x in range(1, int(n/2)):
for y in range(n):
if y==0 or y==x or y==n-1 or y==n-x-1 or y==int(n/2):
print("*", end="")
else:
print(" ", end="")
print()
#중간줄
for x in range(n):
print("*... |
01905284ff9bbd0a9ab4c4c55c3724e8c7c35752 | Avani1992/python | /Sherlock and the Valid String.py | 1,111 | 3.96875 | 4 | """
Sherlock considers a string to be valid if all characters of the string appear the same number of times.
It is also valid if he can remove just 1 character at 1 index in the string, and the remaining characters will
occur the same number of times. Given a string s, determine if it is valid. If so, return YES, ... |
8c17a29d4554f760e3efb32d7c73d33fe0a5567d | benadaba/Data-Management-and-Visualization | /Making Data Management Decisions.py | 2,877 | 3.703125 | 4 | # -*- coding: utf-8 -*-
“”“
Created on Sat Dec 26 14:26:14 2015
@author: Bernard
”“”
#import statements
import pandas
import numpy
#load the gapminder_ghana_updated dataset csv into the program
data = pandas.read_csv(‘gapminder_ghana_updated.csv’, low_memory = False)
#print number of observations(rows) which is the... |
a026e2ed0a40c56a1705a55b43a9aba7c2a99ab8 | jainamandelhi/Machine-Learning-Algorithms | /Simple Linear Regression/Simple Linear Regression.py | 2,706 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 19 12:41:14 2018
@author: AMAN
"""
#Import libraries
from random import seed
from random import randrange
from csv import reader
from math import sqrt
#Function to load csv file
def read_my_file(filename):
dataset=list()
with open(filename,'r') as file:
... |
685eebb6806efc434e73d5fe67251be03fe7392b | Vaishnavi02-eng/InfyTQ-Answers | /PROGRAMMING FUNDAMENTALS USING PYTHON/Day3/Assignment26.py | 650 | 3.90625 | 4 | #PF-Assgn-26
def solve(heads,legs):
error_msg="No solution"
chicken_count=0
rabbit_count=0
#Start writing your code here
#Populate the variables: chicken_count and rabbit_count
if legs%2==0:
rabbit_count=legs//2-heads
chicken_count=heads-rabbit_count
print(rabbit_count)... |
064c6e7e350807bc6fe5ef214633e8e0ae012fe4 | ewalldo/URI-OnlineJudge-Problems | /Beginner/3037 - Playing Darts by Distance/main.py | 415 | 3.671875 | 4 | n_cases = int(input())
for x in range(n_cases):
joao_score = 0
for j in range(3):
score, distance = map(int, input().split(' '))
joao_score += (score * distance)
maria_score = 0
for j in range(3):
score, distance = map(int, input().split(' '))
maria_score += (score * distance)
if maria_score > joao_sc... |
c78d9488eff6d68d0fe96d5970d53301d4bbeb2e | andrewp-as-is/elapsed.py | /tests/examples/datetime/example.py | 406 | 3.8125 | 4 | #!/usr/bin/env python
import datetime
import time
import elapsed
dt = datetime.datetime.now()
time.sleep(2)
print("elapsed.get(datetime): %s" % elapsed.get(dt))
print("")
print("elapsed.seconds(datetime): %s" % elapsed.seconds(dt))
print("elapsed.minutes(datetime): %s" % elapsed.minutes(dt))
print("elapsed.hours(datet... |
e756d281407e384ac54d5c5804c6aceb3ecfbf06 | CescWang1991/LeetCode-Python | /python_solution/251_260/PaintHouse.py | 3,463 | 3.78125 | 4 | # 256. Paint House
# There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of
# painting each house with a certain color is different. You have to paint all the houses such that no two adjacent
# houses have the same color.
#
# The cost of painting each house... |
879cbb11f5b0244d37775de0953ec30532fac9bc | Xponential11/Jenkins | /Exercise_numpy_3.py | 3,282 | 4.03125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def tax_sums(journal_df, months=None):
""" Returns a DataFrame with sales and tax rates -
If a number or list is passed to 'months', only the sales
of the corresponding months will be used.
Example: tax_sums(... |
447b7988bf01a785607292d10948e0b047d6102f | mollyincali/whatsthatface | /src/graphing.py | 4,182 | 3.546875 | 4 | ''' code for graphing used throughout capstone '''
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
from skimage import io
import PIL
from sklearn.metrics import confusion_matrix
def cluster_images(df):
''' show kmeans cluster of animals '''
for i in range... |
fbbed797e0e2fef3f539924064991d874a0a13f3 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3986/codes/1636_2450.py | 124 | 3.890625 | 4 | n1=input("nome 1 :")
n2=input("nome 2 :")
if (n1.upper() > n2.upper()) :
print(n2)
print(n1)
else :
print(n1)
print(n2) |
115d8fd9ef2a4317333e366b50d699a495efac1d | avocardio/MLinPractice | /code/feature_extraction/video_bool.py | 914 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple feature that tells whether a video is in the tweet or not.
Created on Wed Sep 29 12:29:25 2021
@author: shagemann
"""
import numpy as np
from code.feature_extraction.feature_extractor import FeatureExtractor
# class for extracting the video as a feature
clas... |
2485204816372050e19ba0093bf737fc12395843 | lssxfy123/PythonStudy | /tkinter_test/gui_test2.py | 481 | 3.5625 | 4 | # Copyright(C) 2018 刘珅珅
# Environment: python 3.6.4
# Date: 2018.6.8
# 自定义按钮
from tkinter import *
# 自定义Button
class HelloButton(Button):
def __init__(self, parent=None, **config):
super().__init__(parent, **config)
self.pack()
self.config(command=self.callback)
def callback(self):
... |
07c0ca609a798c5cad6069950b71d4c98c6c0ad8 | fwangboulder/DataStructureAndAlgorithms | /#3LengthOfLongestSubstring.py | 1,152 | 3.8125 | 4 | """
3. Longest Substring Without Repeating Characters Add to List QuestionEditorial Solution My Submissions
Total Accepted: 237674
Total Submissions: 1002030
Difficulty: Medium
Contributors: Admin
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the... |
98bf926b3434e649e4125a0aa94854e7a1a1739a | pmk2109/Week0 | /Code1/worldcup.py | 4,126 | 3.875 | 4 | from datetime import datetime
import os
import sys
def read_game_info(filename):
'''
INPUT: string
OUTPUT: tuple of string, string, string, int, int
Given the filename of a game, return the time, team names and score for the
game. Return these values:
time: string representing time of ga... |
1339d9c73fc2339961ba48dad20f0e9a3e0459fb | SachaRbs/ft_linear_regression | /src/predict.py | 510 | 3.734375 | 4 | import pandas as pd
def predict_(t0, t1, mileage):
pred = t0 + (t1 * mileage)
return pred
# return None
def main():
theta = pd.read_csv(r'../data/theta.csv')
t0 = float(theta.columns[0])
t1 = float(theta.columns[1])
print("enter the mileage of the house...")
try:
mileage = int... |
eb52d830d45f7de84e9eb65f055f9c6976164f96 | bOOmerSpb/lukogorskii-python | /Lecture_2_Collections_homework/hw3.py | 652 | 4 | 4 | """
Write a function that takes K lists as arguments and returns all possible
lists of K items where the first element is from the first list,
the second is from the second and so one.
You may assume that that every list contain at least one element
Example:
assert combinations([1, 2], [3, 4]) == [
[1, 3],
[1, ... |
98280d5ffc5551691aa1b2663e62aa96d23fd1fd | AlexandruSte/100Challenge | /Paduraru Dana/17_odd_int.py | 409 | 3.875 | 4 | # https://www.codewars.com/kata/find-the-odd-int/train/python
def find_odd_int(seq):
for elem in seq:
if seq.count(elem) % 2:
return elem
print(find_odd_int([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]))
print(find_odd_int([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]))
print(find_odd_in... |
04aba31265e5b491652e5c72b0f049aa9672b96c | huangjenny/wallbreakers | /week2/subdomain_visit_count.py | 1,984 | 3.5625 | 4 | # Jenny Huang
# Wallbreakers Cohort #3
# Week 2
# Subdomain Visit Count
# https://leetcode.com/problems/subdomain-visit-count/
from collections import defaultdict
class Solution(object):
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
... |
f580d4926d1cc7356964a3ccfd204e0603e2d7fc | jishnuvinayakg/pygeo | /tests/test_intersect.py | 4,687 | 3.71875 | 4 | from src.pygeo.intersect import (
intersect,
_intersect_ray_with_sphere,
_intersect_ray_with_triangle,
)
from src.pygeo.objects import Ray, Sphere, Triangle,Point,Vector
import numpy as np
# Test cases for intersect
# 1.test _intersect_ray_with_sphere
def test_ray_sphere_intersection_2_point_return_true... |
040aa62d812ba7ab2ff57ebf65dfb25642c02086 | tlcsanshao/PythonDemo | /multiprocessingDemo/mp3.py | 762 | 3.5625 | 4 | import multiprocessing,time
def reader(d):
while True:
time.sleep(1)
print(d)
def writer(d):
d["abc"] = 123
if __name__ == "__main__":
manager = multiprocessing.Manager() #生成Manager 对象
d = manager.dict() #生成共享dict
jobs = []
# p1 = multiprocessing.Process(target = reade... |
9278389cf96bc4b1bf38ae8c2cde5577abe51601 | beepscore/python_play | /tests/test_user.py | 1,113 | 3.90625 | 4 | #!/usr/bin/env python3
import unittest
from user import User
class TestUser(unittest.TestCase):
def test_add_attribute(self):
user = User()
# print(help(user))
"""
Help on User in module python_collections_play.user object:
class User(builtins.object)
| simple... |
a8de8a0d7135659b2d931c4e2fce34d5707ad2a6 | ismailsinansahin/PythonAssignments | /Assignment_13/Question_71.py | 519 | 4.21875 | 4 | """
Create a method called populate that accepts an empty int array and populates it with numbers counting up.
Sample Output:
populate(new int[3])
returns:[1,2,3]
populate(new int[5])
returns:[1,2,3,4,5]
"""
def populate(arr):
newInt = []
for i in range(arr[0]):
newInt.append(... |
c3b4963ef78a1c8b636b82eb996807ba774b4df2 | AndreyPetrovGit/pythonhw | /basics/Task6.py | 149 | 3.546875 | 4 | def caesar_cipher(stri, sh):
ans = ""
for i in stri:
ans += chr((ord(i) + sh) % 256)
return ans
print(caesar_cipher("abc", 1))
|
0771d7f0ae9812152aadf16a0a2645f9ff14d896 | lilyluoauto/algorithm008-class02 | /Week_02/groupAnagrams.py | 614 | 3.75 | 4 | # coding:utf-8
#!/usr/bin/python
# ========================================================
# Project: project
# Creator: lilyluo
# Create time: 2020-04-20 23:17
# IDE: PyCharm
# =========================================================
import collections
class Solution:
def groupAnagrams(self, strs):
ans... |
4a8363a034993b9b9fdb6648d0a7da262f9cf46c | SmallConcern/python_self_study | /algorithms/graphs/topological_sort.py | 924 | 3.5625 | 4 | import random
def _topological_sort(dag, node, visited, sorted):
if node not in visited:
visited.add(node)
for child in dag[node]:
_topological_sort(dag, child, visited, sorted)
sorted.append(node)
def topological_sort(dag):
visited = set()
sorted = []
while len(vi... |
9362eee6b9fadacb84dd2b9eba19532206b1051a | ing-prog/webpy_2019_1_g2 | /Lesson 04.03/program4.py | 168 | 3.90625 | 4 | for i in range(0,10):
print(i)
name = ["Alice", "Bob", "Alex", "Luis","Yandex"]
for i in range(0, len(name)):
print(name[i])
for t in name:
print(t)
|
a203216a05f95c0f2ba251c49b690d37b0dd4475 | fwr666/ai1810 | /aid/day20.py/chongzai.py | 557 | 3.84375 | 4 | class MyNumber:
def __init__(self,value):
self.data = value
def __repr__(self):
return "MyNumber(%d)" % self.data
def __add__(self,other):
print('MyNumer.__add__方法被调用')
v = self.data + other.data
return MyNumber(v)#创建一个新的对象并返回
def __sub__(self,rhs):
v =... |
85ad965a64b40b1bd955733260937c78c10e2975 | parulmittal1996/python | /md.py | 337 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[13]:
def f1(x,y):
a=0
if (x>y):
a = x
else:
a = y
for i in range(a,(x*y+1)):
if(i%x==0 and i%y==0):
return ("lcm=",i)
break
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
... |
906db754678d34b12d886dc57d9420b2a41a7911 | BigPieMuchineLearning/python_study_source_code | /exer_6.2_5.py | 80 | 3.609375 | 4 | total=0
num=100
while(num<100001):
total+=num
num+=5
print(total) |
c806d2952eae3035f6c8cb50a7c24f179dbf9927 | gal421/MIT-intro-to-cs-python | /bubble_sort.py | 421 | 3.734375 | 4 |
def bubble(L):
if len(L) == 0 or len(L) == 1:
return L
else:
count = 0
i = 0
biggest = L[0]
while count < len(L):
for j in range(len(L)):
print L[i], L[j], L
if biggest > L[j]:
biggest = L[j]
... |
e7af34db35bc28ad32ac7035f4bc30116f1534e4 | jmstudyacc/python_practice | /POP1-Exam_Revision/mock_exam1/question7.py | 1,187 | 3.765625 | 4 | class Person:
def __init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
def get_info(self):
return f"{self.f_name} {self.l_name}"
def get_name(self):
return (self.f_name, self.l_name)
class Adult(Person):
def __init__(self, f_name, l_name, phone):
... |
9ea0e8a34dd527903574e3d5741ecd258d1b193d | ChangxingJiang/LeetCode | /0801-0900/0817/0817_Python_1.py | 616 | 3.59375 | 4 | from typing import List
from toolkit import ListNode
class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
G = set(G)
ans = 0
part = False
while head:
if head.val in G:
if not part:
ans += 1
... |
99df96f328c88bd87159990fdf634db4f1c1a8e9 | cfrasier/Portfolio | /SingleCellProject/bin_graph.py | 1,528 | 3.53125 | 4 | # Import packages
# mplot3d creates three dimensional plots
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
# pandas is a module designed to help read in many different types of files and data types
import pandas as pd
import numpy as np
# Read in the geometry.txt file as a data frame. Pandas data fr... |
410075d05f57223cad831d55d79944dba594dc68 | niamargareta/project_euler | /experiment_with_for_loops.py | 164 | 3.984375 | 4 | print("foo")
for x in range(1, 4):
# print("bar", x, x // 3, x % 3, x/3)
print("bar", x)
for y in range(0, 3):
print('dan', x, y)
print("baz")
|
88c0171ef22e44f511e63c3b48cfb02f08c8ce62 | matheus-valentim/projetos-python | /pequenos projetos/identificar valores.py | 526 | 3.75 | 4 | lista = []
maior = menor = menorP = maiorP = 0
for n in (range(0, 5)):
lista.append(int(input(f'diga um valor para a posição {n}: ')))
if n == 0:
maior = menor = lista[n]
menorP = maiorP = n
else:
if lista[n] > maior:
maior = lista[n]
maiorP = n
elif... |
2f5a045cbd4da8c288d9df035f749d0ea8efa2bf | Mica210/python_michael | /Mid-Course_Exercises/Targil7.py | 568 | 4.1875 | 4 | '''
Write a Python program to convert height (in feet and inches) to
centimeters.
'''
from time import sleep
print("\nConvert height imperial units to metric unit\n\nChoose your option\n---------")
choise=input("1.Inches\n2.Feet\n")
if(choise=="1"):
inch=float(input("Enter your height: "))
sleep(1)
print(... |
42913d0ba647504e816dc2df52c5837764c7a675 | lsyleo/HelloPython | /Python/inSuBunHe.py | 1,900 | 3.640625 | 4 |
isGood = False
fNum = 0
sNum = 0
tNum = 0
divNum = [1,0]
wasNeg = False
while True:
fNum = int(input("이차항의 계수 :"))
#이차항 계수 입력
if fNum <0:
wasNeg = True
if fNum == 0:
while True:
print("이차항의 계수는 0이 될 수 없습니다")
fNum = int(i... |
4266e64c16cce71aaa9f4c35f48798ce2f777a9c | edu-athensoft/ceit4101python | /stem1400_modules/module_2_basics/c5_datatype/datatype_numbers/decimal4.py | 205 | 3.796875 | 4 | print(16.0/7)
### round to 2 decimals
from decimal import Decimal
# First we take a float and convert it to a decimal
x = Decimal(16.0/7)
# Then we round it to 2 places
output = round(x,2)
print(output) |
70a38a0d984637e17fdff8d62e015382e9d0a068 | JoTaijiquan/Python | /Python101-New130519/2-1-2.py | 964 | 4 | 4 | #Python 3.9.5
#Example 2-1-2
def hello():
'ป้อนเลข 1-7 แล้วพิมพ์ค่าออกมาตามเงื่อนไข'
word = {
"1":"สวัสดีวันอาทิตย์",
"2":"สวัสดีวันจันทร์์",
"3":"สวัสดีวันอังคาร",
"4":"สวัสดีวันพุธ",
"5":"สวัสดีวันพฤหัสบดี",
"6":"สวัสดีวันศุกร์",
"7":"สวัสดีวันเสาร... |
b68ffffc2204bd7668db00ece552f7efe496b0f3 | PrajjawalBanati/python_certification | /Module_1/Assignment_17.py | 1,249 | 4.3125 | 4 | print("Hello Everyone! The following program will take two string as an input \
from your and will concatenate all the capital letters from both the strings")
#Storing a string of capital letters in compiler to compare it with strings 1 and 2
default="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#Storing two Empty strings in which we i... |
079c81ae397e63ddfe24d98c055b09ff0200ee27 | hanchangjie429/algorithm010 | /Week03/50.pow-x-n.py | 1,054 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=50 lang=python3
#
# [50] Pow(x, n)
#
# @lc code=start
class Solution:
def myPow(self, x: float, n: int) -> float:
# Method 1: 直接用公式
'''
return pow(x,n)
'''
# Method 2: 暴力循环法
# 处理n为负数的情况,也就是将x转换成1/x,然后不断乘1/x
'''
if n < 0:
... |
8474a7594a61d3d633239ca9c4fa92550ac6cef7 | deepaksharran/Python | /tupletostr.py | 96 | 3.703125 | 4 | x=input("Enter comma seperated values: ").split(",")
tup=tuple(x)
s="".join(tup)
print(s)
|
b9cf4c9bd42df87a4f18d5560888ac9eb7fbf816 | quocvietit/code-wars | /5 kyu/moving-zeros-to-the-end.py | 338 | 3.578125 | 4 | '''
5kyu - Moving Zeros To The End
https://www.codewars.com/kata/moving-zeros-to-the-end/solutions/python
'''
def move_zeros(array):
l = 0
arr = []
for i in range(0,len(array)):
if array[i] == 0 and type(array[i]) in (int, float):
l+=1
else:
arr.append(array[i])
... |
7c9d897a0f72b2d7281853071dba582617f0029d | seyyalmurugaiyan/Django_projects | /Demo_Projects/Day_1 - Basics/passitive_negative.py | 131 | 4.0625 | 4 | number = int(input("Enter Your Number: "))
if number>=0:
print(f"{number} is correct.")
else:
print(f"{number}It is wrong") |
3f7648f4465d51d2cb9e550f18cfc19e55c16bd5 | sanusiemmanuel/DLBDSMLUSL01 | /Unit_2_Clustering/2_1_ElbowCriterion.py | 632 | 3.5625 | 4 | # IU - International University of Applied Science
# Machine Learning - Unsupervised Machine Learning
# Course Code: DLBDSMLUSL01
# Elbow criterion
#%% import libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from yellowbrick.cluster import KElbowVisualizer
#%% create sa... |
cb819a4afef7f87df40c7eae95e1da5ffcbf1a4d | krkartikay/CodeForces-solutions | /codeforces/982/A.py | 481 | 3.578125 | 4 | import os, sys, math
import re
def main():
T = int(input())
#for _ in range(T):
testcase()
def testcase():
l = input()
if solve(l):
print("Yes")
else:
print("No")
def solve(l):
if l=="0":
return False
if re.search("11",l):
return False
if re.search("000",l):
return False
if re.search("00$",l):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.