blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e69ec9688ec8b3cc2d1c48dd0d44c8332b19fcfe | storans/as91896-virtual-pet-jemimagregory | /exit_to_main_menu.py | 2,351 | 4.625 | 5 | # including the list items function and welcome screen function for testing
# This function is used after the main explanation of how the program works
def welcome_screen(pet_name):
# displays an introduction of the pet rabbit to the user
print("This is your pet, {}!".format(pet_name))
print(" _________ ... |
772f2f3d721ab934884e9a366380be5739e0f3f5 | guam68/class_iguana | /Code/nathan/pythawn/lab_07_rpc.py | 959 | 3.921875 | 4 | import random
intro_txt = input('WE ARE PLAYING ROCK PAPER SCISSORS\n your choices are >r >p or >s\n Press ENTER to continue ')
choices = ['r', 'p', 's']
player_choice = ''
computer_choice = random.choice(choices)
player_choice = input('name your weapon\n >')
if player_choice == 'r' and computer_choice == 'r':
pr... |
fe8302d75ca11c46b9aff46ed816c3f536a26220 | mmarano25/collatz-graph | /prototype.py | 931 | 3.65625 | 4 | import plotly as plt
import plotly.graph_objs as go
TESTS_ON = False
def collatz_steps(num: int) -> int:
"""runs the collatz conjecture on num, returns number of steps"""
if num == 0:
return 0
n = 0
while num != 1:
n += 1
if (num % 2) == 0:
num /= 2
else:
... |
416ad983720100d66aa98e45711a352792c85cc9 | babuhacker/python_toturial | /input_output/test.py | 664 | 3.59375 | 4 | import os
file = []
while True:
option = input("what you want to do?\n")
if option == 'file':
user = input("now you want to\n""1.read.\n" "2.delete.\n" "3.append.\n")
if user == 'read':
name = input("tell me the file name")
outputfile = open(name, "r")
fil... |
18212efbeffea53b13a5ff9fbbc8c1e682c82d18 | mholmes21/Project-Euler | /zComplete-Problem58.py | 894 | 4.03125 | 4 | import time
def isPrime(n):
if n < 2:
return 0
elif n == 2:
return 1
elif n % 2 == 0:
return 0
else:
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return 0
return 1
def calc_corners(s):
tmp = list()
tmp.append(s**2)
... |
428a1df46295ee5b127a9a89a012ee15dee75d7d | artorious/python3_dojo | /phone_list.py | 1,191 | 4.25 | 4 | #/usr/bin/env python3
""" A simple telephone contact list.
Uses Python dictionary to implement a simple telephone contact database with
a rudimentary command line interface.
The contact list associates a name with a telephone number.
A person or company’s name is a unique identifier for that contact.
The name is a... |
57eab3aa9a4cab151583d91ee20ec31c0ffd396d | Anondo/algorithms.py | /BlockChain/main.py | 286 | 3.546875 | 4 | from blockchain import BlockChain
myChain = BlockChain()
myChain.addBlock("first block")
myChain.addBlock("second block")
myChain.addBlock("third block")
myChain.addBlock("forth block")
for block in myChain.getBlocks():
print block.getData()
print myChain.getBlock(1).getData()
|
c6c07a7f873449f0cf8aa10223944a4737ce8194 | tyamz/CPS3310---PL | /Project3.py | 456 | 3.703125 | 4 | def main():
spam = ['apples', 'bananas', 'tofu', 'cats']
test = ['oranges', 'tomatoes', 'sushi', 'dogs']
def printList(lst):
str = ""
for i in range(len(lst)):
if i == len(lst) - 1:
str = str + ", and " + lst[i]
elif i == 0:
str = str ... |
139f549a28e8e4679313f938946ce4f5173e4efd | wangjinyu124419/leetcode-python | /169. 多数元素.py | 402 | 3.640625 | 4 | """
169. 多数元素
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
"""
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums)//2] |
7ce1b0d93ddc34fa89277b150d7143b6fbd700f4 | olsen601/guess_the_number | /Capstone_lab1_part1.py | 345 | 4 | 4 | from random import randint
answer = randint(1,11)
guess = input("Guess a number between 1 & 50:")
g = int(guess)
while g != answer:
print("guess again")
if g > answer:
print("too high")
elif g < answer:
print("too low")
guess = input("Guess a number between 1 & 50:")
g = int(g... |
cc8fead178eb8ed27db84ce5184bb83b49914d6c | yuanlyainihey/review | /treeAndGraph/treeFunc.py | 4,657 | 4.0625 | 4 | class Node(object):
def __init__(self, val=-1):
self.val = val
self.left = None
self.right = None
class Tree(object):
def __init__(self):
self.root = Node()
def isEmpty(self):
if self.root is None:
return True
else:
return False
... |
902745e015ef300425b438ce60fbe31d68721429 | husseinberk/python | /Problem 1 ( Beden Kitle İndeksi ).py | 428 | 3.84375 | 4 | print("Beden Kitle Endeksi Hesaplama Programı")
kilo = int(input("Lütfen Kilo Değerinizi Giriniz: "))
boy = float(input("Lütfen Boy Değerinizi Giriniz: "))
bki = kilo / ( boy ** 2)
print("Beden Kitle İndeksiniz: {} ".format(bki))
print("Kilo Durumunuz: ")
if (bki <= 18.5):
print("Zayıf")
elif (bki <= ... |
c56fae91eaf2a9d13fb0decdfa89d03b8f86465c | wf-Krystal/TestDemo | /PTestDemo/dictTest/dictDemo2.py | 918 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
info = {
'stu1101': "zhangsan",
'stu1102': "wangwu",
'stu1103': "lisi"
}
b = {
'stu1101': "wangsui",
1: 3,
2: 5
}
c = dict.fromkeys([6, 7, 8]) #初始化一个字典,初始化keys
print(info.values()) #输出字典中的值
print('-------分隔线-------')
print(b.keys()) #输出字典中的key
pr... |
2b8501be5b877b150ba440d03fc3deddd25944d1 | Xiaoctw/LeetCode1_python | /字符串/比较含退格的字符串_844.py | 549 | 3.515625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
list1 = []
list2 = []
for c in S:
if c != '#':
list1.append(c)
elif list1:
list1.pop()
for c in T:
if c != '#':
list2.append(c)
... |
14aad4c7bbabb44a323926346881304d35f3dba7 | maydan90/udacity_algorithms | /problem_6.py | 860 | 4.0625 | 4 | import random
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if not ints:
return None, None
min_value = ints[0]
max_value = ints[0]
for number in ints:
... |
a141a8197b93fdd1adc4fc2ddcb9182e89875f81 | danielfernandezexposito/cursopython | /fechas.py | 540 | 3.921875 | 4 | # Tipo de dato "date"
# Ejemplo de resta de fechas
# Calculo de dias restantes para cumple
from datetime import date
from datetime import datetime
print("¿Cuando es tu cumpleanyos?")
print("Dia: ")
dia = int(input())
print("Mes: ")
mes = int(input())
hoy = datetime.now()
anyocumple = hoy.year
if(hoy.month > mes):
... |
c508880949428409c825a3571d97a1859090919b | rcampbell1337/secret-santa-generator | /GUI/email_sender.py | 4,057 | 3.578125 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter.font import Font
from tkinter import messagebox
import webbrowser
from Logic.pass_hasher import encrypt_pass
from database import DatabaseTables
from GUI.email_list import EmailList
# This class sets the email and app password of the sender device
class Sender... |
8a25ebd7c54b0d5e907122d7913a51c1623feaec | mareaokim/lotto_hee | /jaggy&minggy.py | 705 | 3.78125 | 4 | #UP&DOWN게임
import random
#게임을 위한 숫자 생성
rn = random.randrange(1,101,1)
num = -1
t_cnt = 0 #시도횟수
print("1~100 숫자 재기&민기 게임을 시작합니다. !!!")
print("재기재기재기 민기민기민기")
while (rn != num):
num = int(input("1~100 사이의 숫자를 입력하세요 : "))
if (num > rn):
print("재기!")
el... |
929d2dbb0174476f6d396e2328e6cfe70984a7b0 | mrayirebi/Python-projects | /Geometric pattern.py | 440 | 3.890625 | 4 | from turtle import *
import random
#create a screen
screen = Screen()
screen.screensize(600,600,'black')
#create a pen to draw geometric pattern
pen = Pen()
pen.speed(150)
size = 20
for i in range(150):
r = random.randint(0,225)
g = random.randint(0,225)
b = random.randint(0,225)
randcol = (r,g... |
bb4bcf45710620042fe310048a71c3056efcad01 | ajioka-fumito/kyopro | /2_ant_book/2-1 全探索/02_stackとqueue.py | 952 | 4.0625 | 4 | # スタック
"""
最後に追加された要素を最初に(O(1)で)取り出すことができるデータ構造
LIFO : last in first out
python では標準Listが対応しているが後述するcollections.dequeで実装することも可能
"""
def sample_stack():
stack = [1,2,3]
print("stack:",stack)
stack.append(4)
print("stack:",stack)
stack.append(5)
print("stack:",stack)
stack.pop()
print("sta... |
307d2fd9bfd02fe100f4316377beb791f7b95f1d | nkkodwani/arul-naveen-c2fo-2021 | /PracticeProjects/ArulFiles/read_from_file.py | 446 | 3.546875 | 4 | #READ FROM FILE: Excercise 22 from practicepython.org
darth = 0
luke = 0
lea = 0
with open('/Users/arul.sethi/Desktop/nameslist.txt', 'r') as open_file:
line = open_file.readline()
while line:
if 'Darth' in line:
darth += 1
elif 'Luke' in line:
luke += 1
elif ... |
881640cd68e2feb05993d44cf56c9db372450cb8 | achmaddidhani/labpy03 | /LATIHAN2.py | 301 | 3.953125 | 4 | print("*****lathan2*********")
print("menampilkan bilangan, berhenti ketika bilangan 0, dan menampilkan bilangan terbesar")
max = 0
while True:
a=int(input("masukan bilangan = " ))
if max < a :
max = a
if a==0:
break
print("bilangan terbesarnya adalah = ",max)
|
229b9eea5a5c5e63f949b6eacd626e0fdc91eb64 | MatheusOlegarioDev/Python_Crie_Seus_Primeiros_Programas | /Fundamentos/Ambiente.py | 691 | 3.59375 | 4 | Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 1 #Inteiro
1
>>> 1.0 #Float
1.0
>>> 1. #Float
1.0
>>> 1 + 2j #Complex
(1+2j)
>>> #Gerando Números por meio de funções
>>> int(1.0)
1
>>> int('9')
9... |
1245680845d0f6e4102053fae45f59d94e1580e3 | anEffingChamp/compSci321 | /chapter6/17.py | 1,102 | 4.46875 | 4 | # Jonathan Smalls
# computer science 321
# 6.17 myTriangle module
# returns true if sum of any two sides is greater than third
import sys
import math
def isValid(side1, side2, side3):
for side in [side1, side2, side3]:
lengthsTemp = [side1, side2, side3]
lengthsTemp.remove(side)
if (sum(leng... |
aa6a5a63c40ab696091f5a333ceba8333fbbb09f | shamsherrathore/Python | /student_marks.py | 982 | 4.0625 | 4 | student_name = str(input("enter the student name:"))
print('<<<<<<<<<wecome to the RANA group of college>>>>>>>>>')
n = int(input("enter the the subjects:"))
total_marks = 0
print("enter marks")
for i in range (1, n+1):
marks = float(input("subject"+str(i)+":"))
assert marks>=0 and marks<=100
total_... |
771da37cb71ba3676a87a897743299f4e77ba33f | cleosilva/desafios_Python | /9_notasAlunos.py | 1,110 | 4.25 | 4 | # Dados um número inteiro n, n > 0, e uma sequência com n notas finais de MAC2166, determinar quantos alunos:
# estão de recuperação: nota final maior ou igual a 3 e menor do que 5;
# foram reprovados: nota final menor do que 3;
# foram aprovados: nota final maior ou igual a 5;
# tiveram um desempenho muito bom: nota ... |
29199c16bceec77469cfda0acaaf19605c0f397f | Gaurav3099/Python | /L1/prac5.py | 149 | 3.859375 | 4 | #calcius to Fahrenheit
s=input("enter temp in celcius ")
cel = float(s)
fah = cel*1.8+32
print("Fahrenheit ",fah)
print("fahrenheit %4.2f"%fah) |
bacf076749e9fa84b22c54de47a3a4259975f690 | prateeksha29/DSA--Python | /Medium level/Arrays/LeetCode 75 - Sort Colors.py | 971 | 4.3125 | 4 | """
Given an array nums with n objects colored red, white, or blue, sort them in-place
so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without us... |
fb16a1e130461cbc9a045c35c29d71efdad7c147 | reiterative/aoc2019 | /calc-fuel.py | 531 | 3.640625 | 4 | import math
def fuel_required(mass):
f = (mass / 3) - 2
if f < 0:
f = 0
return math.floor(f)
cnt = 1
fuel_total = 0
with open('input-day1') as fp:
line = fp.readline()
while line:
print("Line {}: {} ( {} )".format(cnt, line.strip(), fuel_total))
m = int(line)
fr = fuel_r... |
9494f6ba527faea030a0f7f7d427fbfa3034259b | cicihou/LearningProject | /leetcode-py/leetcode279.py | 721 | 3.625 | 4 | '''
代码+图解:https://leetcode-cn.com/problems/perfect-squares/solution/hua-jie-suan-fa-279-wan-quan-ping-fang-shu-by-guan/
最差的情况就是
dp[i] = i,也就是说要构成 5 的完全平方差,需要 5个 1
优化的情况就是,创造一个 j,在 j 的平方小于当前所需要的数的情况下,用j 来优化我们所需要的正方形平方的个数
'''
class Solution:
def numSquares(self, n: int) -> int:
dp = [0] * (n+1)
fo... |
dc9295f5b0aaad9d9eb040afaa0a7909b9c278bc | niranjan-nagaraju/Development | /python/algorithms/arrays/sums/two_sums.py | 637 | 4.125 | 4 | '''
Find and return all pairs that add upto a specified target sum
'''
# Return all pairs with sum in a sorted array
def two_sums_sorted(a, target):
pairs = []
i, j = 0, len(a)-1
while i < j:
curr_sum = a[i]+a[j]
if curr_sum == target:
pairs.append((a[i], a[j]))
i += 1
j -= 1
elif curr_sum < target:
... |
cec0b6cb5e29ff1687dcdafe3950d4bef8675ef0 | Ushravan/Programming-Foundations-With-Python | /Conditional Statements/String_Repetition_3.py | 532 | 4.40625 | 4 | #String Repetition 3
#Given a word and a number (N), write a program to print the last three characters of the word N times in a single line.
#Explanation
#For example, if the given input is "Transport" and the given number is 2.
#The last three characters of the given word are "ort", which have to be repeated 2 time... |
74efec896366d743a740aa901ac874e405d7d1a5 | ankit595/tathastu_week_of_code | /Day 1/Program 4.py | 189 | 3.828125 | 4 | cost_price=int(input("Enter cost price:-"))
sell_price=int(input("Enter selling price:-"))
profit=sell_price-cost_price
sell_price=sell_price+profit*.05
print(profit)
print(sell_price)
|
f16b9e2a1301061421ef0c7e8ec64cfe0ff400b0 | idkwim/ctf-10 | /crypto/0003_2017_BugsBunny_Crypto15/crypto15.py | 641 | 3.671875 | 4 | # -*- coding: utf-8 -*-
#/usr/bin/env python
import string
# Flag : Piug_Pibbm{Q35oF_3BQ0R3_4F3_B0H_G3QiF3_OH_4ZZ}
def encode(story, shift):
return ''.join([
(lambda c, is_upper: c.upper() if is_upper else c)
(
("abcdefghijklmnopqrstuvwxyz"*2)[ord(char.lower()) - ord('a')... |
c05858ba61e68c91bb2d0d92bdb673f39d81f0d0 | martapastor/GIW-Practicas | /Practica1/ejercicio3.py | 4,125 | 4 | 4 | import sys
# We declare the name for the output file where the results will be written
output_file = "output.txt"
def count_words(lines_in_file):
# We create an empty dictionary to save the words and the number of times it appears in the text
# As the words are not sorted in the text, using a dictionary with ... |
1973c363f63090bf0aec6fb0900fc88bc92ca336 | ami225/python-practice | /sample.py | 255 | 4.09375 | 4 | x = 10
print(x / 3) #3.33...
print(x // 3) #3
print(x % 3) #1
print(x ** 2) #100 2乗
y = 4
y += 12
print(y)
#and or not
print(True and False) # False
print(True or False) # True
print(not True) #False
# + *
print("hello" + "world")
print("hello" * 3)
|
f10e516974a5b76c49e4158f4051b807d3682877 | Chithra-Lekha/pythonprogramming | /prgm2.py | 120 | 3.828125 | 4 | yr=int(input("enter the future year"))
for i in range(2021,yr+1):
if i%4==0 and i%100!=0 or i%400==0:
print(i) |
047e78d6364dee581c93e2e1f30176a646937f30 | danagilliann/coding_practice | /python/add_digits.py | 459 | 3.625 | 4 | num = 6345
my_int = 0
def add_total(num):
total = 0
string_of_num = str(num)
for i in range(0, len(string_of_num)):
total += int(string_of_num[i])
return total
total = add_total(num)
def add_digits(num, total):
if total <= 10:
print total
... |
61eba586696216e85fd24f28b8058a64d353accb | tranphibaochau/LeetCodeProgramming | /Easy/pivot_index.py | 1,324 | 3.8125 | 4 | #############################################################################################################################################################
# Given an array of integers nums, write a method that returns the "pivot" index of this array.
# We define the pivot index as the index where the sum of the numb... |
4625a6aad4dbe2728b45f507078abb4a1479b139 | xxxzc/public-problems | /PythonBasic/BuiltInFunctions/Object/attr/template.py | 368 | 3.78125 | 4 | class Student:
def __getattr__(self, name):
if name == 'info':
return '\n'.join([
'姓名: ' + getattr(self, 'name'),
'学号: ' + getattr(self, 'sno'),
'年级: ' + getattr(self, 'grade')])
return ''
name, sno, grade = input().split()
student = St... |
422fecef6b968d55e318bcf42de118837de10ba1 | powermano/pycharmtest | /for_test.py | 1,337 | 3.640625 | 4 | # from enum import Enum, unique
#
# @unique
# class Weekday(Enum):
# Sun = 0 # Sun的value被设定为0
# Mon = 1
# Tue = 2
# Wed = 3
# Thu = 4
# Fri = 5
# Sat = 6
#
# day1 = Weekday.Mon
#
# print(day1)
# print(day1.value)
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May'... |
70ca19b3a39bd60cc546450ba5b33ac6732acf77 | MonikaMudr/pyladies | /04/ukoly/ukol_7.py | 1,005 | 3.625 | 4 | rodne_cislo = input('Zadej rodne cislo: ')
# a) je ve spravnem formatu, 6 cislic/4 cislice?
cislo_seznam = rodne_cislo.split('/')
if len(cislo_seznam[0]) == 6 and len(cislo_seznam[1]) == 4:
print("Rodne cislo ma spravny format.")
cislo_bez_lomitka_string = ''.join(cislo_seznam)
cislo_bez_lomitka = int(cislo_bez_lo... |
a060eb9e7f0c9c949cb3c08c9c15d85d8cf46f82 | sky-tanaka/GitVsc | /module-sample1.py | 143 | 3.6875 | 4 | import calc
a=2
b=3
ans1=calc.add(2,3)
ans2=calc.sub(2,3)
print("{}+{}={} ".format(a,b,ans1))
print("{}-{}={} ".format(a,b,ans2))
|
63bbb1c441572a5f4cd6f47a98557abf2d8ee910 | rohit-mehra/basic_machine_learning_assignments | /kmeans.py | 5,700 | 3.890625 | 4 | #!/usr/bin/env python3
"""Assignment 1: UTSA CS 6243/4593 Machine Learning Fall 2017"""
import random
from statistics import mean
__author__ = 'Rohit Mehra'
class KMeans:
"""Basic KMeans Cluster Class"""
def __init__(self, num_clusters=3, max_iterations=900, random_seed=None):
self.num_clusters = n... |
e7fe8efe710d89ee0fcde959a292ad13e60da77c | Shen-xinliang/python-14 | /tianwei/week4/SearchBigThree.py | 352 | 3.703125 | 4 | #随机生成20个数字,并且筛选出其中最大的三个数
import random
lst=[random.randrange(0,101) for x in range(20)]
print(lst)
for i in range(3):
max=i
for j in range(i+1,20):
if lst[max]<lst[j]:
max=j
print(lst[max])
if max!=i:
temp=lst[i]
lst[i]=lst[max]
lst[max]=temp
|
1fd692b13f46d596236a91e765c8ae8016b50c4a | chengong825/python-test | /120三角形最小路径和.py | 773 | 3.8125 | 4 |
# 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
#
# 例如,给定三角形:
#
# [
# [2],
# [3,4],
# [6,5,7],
# [4,1,8,3]
# ]
# 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
#
class Solution:
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
deepth=len... |
37b095f48f41178c9ce7affba0d952e312a1d1f6 | mlubinsky/mlubinsky.github.com | /Flask/Flask_sqlite_d3/import_plaza_csv.py | 2,662 | 3.53125 | 4 | """
Read in BART ETD data from files and write to SQL.
"""
import sqlite3
import pandas as pd
import numpy as np
DATABASE = 'bart.db'
#FILES = ['plza.csv', 'mont.csv']
FILES = ['plza.csv' ]
def parse_time(timestamp):
"""Attempt to parse a timestamp (in seconds) into a pandas datetime in
Pacific time, return t... |
0b02cad5c63a3c94e9de44b80f277b946731cdbe | AbirameeKannan/Python-programming | /Beginner Level/function.py | 734 | 3.703125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: user
#
# Created: 20/02/2018
# Copyright: (c) user 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def... |
65da6f97a9d33fad3102c8697f6858c8595d4743 | Shulin00/GreenPol | /telescope_control/examples/gui4_grid_layout.py | 535 | 3.875 | 4 | from tkinter import *
#creates a blank window
root = Tk()
label_1 = Label(root, text='name')
label_2 = Label(root, text='password')
#user input
entry_1 = Entry(root)
entry_2 = Entry(root)
#where to put it
label_1.grid(row=0, sticky=E) #sticky: N,S,W,E, alignment
label_2.grid(row=1, sticky=E)
entry_... |
4d257686fba7b000f03d4e7e81e0ad933cb78124 | dygksquf5/python_study | /Algorithm_python/조이스틱.py | 1,852 | 3.5 | 4 |
# 이런식으로 아스키로드로 하려고했는데, 문제를 ㅇ살짝 처음에 잘못 이해해서,... 다시 새롭게 접근하기 !
# def solution(name):
# print(int(ord("A")) - int(ord("J")))
# answer = -1
#
# nums = [0] * len(name)
#
# for i, n in enumerate(name):
# if n == "A":
# nums[i] = 1
# elif n != "A":
# nums[i] = abs(int(o... |
e44eb20714520e49086392bccbc98f8d02184257 | kevinwkt/intelligentSystems | /a-star/main.py | 4,719 | 3.515625 | 4 | #! /usr/bin/python3
# Search Space:
# The search space for each movement would depend on two factors:
# 1. Which side the lamp is currently at.
# 2. Who is at the side where the lamp is at.
# Initial State:
# In the beginning we would have everyone on the left side and no one on the right side.
# Since we will re... |
6bf47bda3c958001479dd4dd3aa17ad9a2a7265c | Boris-Rusinov/BASICS_MODULE | /Nested Loops/Ex02-Equal_Sums_Even_Odd_Position.py | 1,245 | 3.671875 | 4 | from math import floor
range_min_num = int(input())
range_max_num = int(input())
curr_num_no_changes = 0
curr_even_sum = 0
curr_odd_sum = 0
curr_position = 0
for curr_num in range(range_min_num, range_max_num + 1):
# Did this with a while loop just to see if I can make the code execution faster than 1.200 sec ... |
1597043fd7638e1c6711dbfad54cfe8876415d78 | Janardhanpoola/100exercises-carbooking | /test.py | 1,974 | 4.4375 | 4 | #1. Given a string, return a new string where "not " has been added to the front. However, if the
#string already begins with "not", return the string unchanged.
def not_string(str):
if str.startswith('not'):
return str
else:
return "not "+str
if __name__=="__main__":
str="candy"
pri... |
b2167cbace206711eceaeb7f3bf1c26b1ae3ac72 | bharaths30/HackerRank | /tree_test.py | 1,580 | 3.546875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: sbhar
#
# Created: 07/01/2017
# Copyright: (c) sbhar 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
class Node:
... |
1864681f7a8b249d054ea08c269732c7533ded98 | Gingervvm/JetBrains_Hangman | /Problems/Preprocessing/task.py | 190 | 3.703125 | 4 | input_string = input()
to_replace = [",", ".", "!", "?"]
input_replace = input_string
for sign in to_replace:
input_replace = input_replace.replace(sign, "")
print(input_replace.lower()) |
ce1f28cf8310137f7633f2709b8251dd4d6e9395 | sp3006/MyPythonCoding | /GivenOpAddList.py | 846 | 3.9375 | 4 |
##Given a list of integers nums, a string op representing either "+", "-", "/", or "*",
##and an integer val, perform the operation on every number in nums with val and return the result.
Note: "/" is integer division.
class Solution:
def solve(self, nums, op, val):
nu = list()
if op == "+":
... |
8ab9e1662c97df4ded047dc170394176f62dcb30 | yize11/1808 | /05day/10-上网.py | 161 | 3.890625 | 4 | age = int(input('请输入年龄'))
money = float(input('请输入钱'))
if age > 18 and money > 5:
print('可以上网')
else:
print('在宿舍待着')
|
ecb1f8a696a77f4bab73e462b0cc73db55a20ac7 | josiane-sarda/CursoPythonHbsisProway | /Aulas Marcello/exercicio 44.py | 375 | 4.03125 | 4 | #Modifique o exercício anterior para aceitar somente valores maiores que 0 para N.
# Caso o valor informado (para N) não seja maior que 0, deverá ser lido um novo valor para N.
print('Digite um valor N')
valor_n = int(input())
while (valor_n <= 0):
print('Valor invalido. Digite um novo valor')
valor_n = int(... |
40af54f8f87bcee066b29ba6cd0abb20c0b451c3 | Daehyun-Bigbread/Bigbread-Python | /python_for_everyone/15A-typing.py | 1,329 | 3.65625 | 4 | # 프로젝트2: 타자 게임 만들기
import random
import time
# 단어 리스트: 여기에 단어를 추가하면 문제에 나옵니다.
w = ["cat", "dog", "fox", "monkey", "mouse", "panda", "frog", "snake", "wolf"]
n = 1 # 문제 번호
print("[타자 게임] 준비되면 엔터!")
input() # 사용자가 엔터를 누를 때까지 기다립니다.
start = time.time() # 시작 시간을 기록합니다.
q =... |
832e170046a34f969c8650717ff9201562533639 | PCMBarber/factorial | /Not_tests/notimportant.py | 2,505 | 4.1875 | 4 | import os
import time
def fact(num):
factorial = 1
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
if i == 0:
continue
factorial = factorial*i
return factorial
def reverse_fact(num):
count = 0
for i in range(... |
ef957817a5062e413678dc3b10f168fcc4284c97 | alexey-mazenkov/lenghtconverter | /main.py | 10,195 | 3.953125 | 4 | # Length converter v1.
# Objective: to develop a length measure converter.
import localization as lc # Import localization packages from "localization.py".
lc.lang = str() # Language selection.
print(lc.measures_list) ... |
7325d868d2d0b1288b5f91a30f9323173558a2cc | Brunoenrique27/Exercicios-em-Python | /desafio88 - Listas em python.py | 773 | 3.953125 | 4 | ## Faça um programa que ajude um jogador da MEGA SENA a criar palpites.
# O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo
# cadastrando tudo em uma lista composta.
from random import randint
from time import sleep
lista = []
jogos = []
print('*'*30)
print(' S... |
cf186f63b3fa31a4d87c56729e28c04cbf1141ff | evamc7/learn_python_the_hard_way | /ex11.py | 729 | 4.1875 | 4 | print "How old are you?"
age = raw_input (22)
print "How tall are you?"
height = raw_input (70)
print "How much do you weigh?"
weight = raw_input (53)
# en este caso he rellenado yo los parentes de raw_input, que seria lo que tendria que rellenar el usuario con los datos que deben aparecer
print "So, you're %r old, %r... |
2ebbdc8a6522508a8cb05d4b26425cfbd547ca9f | PengiunDoomsday/lab7 | /lab7.py | 1,453 | 3.796875 | 4 | """
Created on Fri Dec 7 21:04:34 2018
@author: Javier Soon
ID: 80436654
Professor: Diego Aguirre
T.A.: Manoj Saha
Description: Compare two words in which it would count the number of operations
needed to make either word be the same to the other.
"""
def edit_distance(word1, word2):
'... |
71e2eb5f6887e7739e435cd78d803f613293ba02 | AsherThomasBabu/AlgoExpert | /Arrays/Sorted-Squared-Array/optimised.py | 701 | 3.953125 | 4 | # Write a function that takes in a non-empty array of Integers that are sorted in ascending order and returns a new array of the same length with the squares of the original integers also sorted in ascending order.
def sortedSquaredArray(array):
sortedArray = [0 for i in range(len(array))]
leftInd = 0
righ... |
a921d09d209eab83956b4d6e675a37c9577e3d44 | BruceJohnJennerLawso/void | /app.py | 514 | 3.578125 | 4 | ## app.py ######################################################################
## central app file containing a main function #################################
## I still think a lot like C ##################################################
#############################################################################... |
2b65897ee10090d9bb83817db9c671deac98592b | SteveDengZishi/ChickenFight | /JitteryChicken.py | 1,813 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 4 00:19:40 2017
@author: stevedeng
"""
"""
This file contains the JitteryChicken class, which is a sub-class of FuriousChicken
The make_your_move() function of FuriousChicken has been overidden here
Modified from original author Foo Barstein
Date:... |
4cce146c40c875d9f52410016dc5ba5cf7930485 | TylerCrabtree/Connect4GUI | /c4GUI.py | 17,071 | 3.53125 | 4 | # Tyler Crabtree
# Csci 121
# Assignment 9
diameter = 50
spacing = 10
gutter = 50
import random # for win choices and message choices
from Tkinter import *
class Board:
def __init__( self, width, height ):
self.width = width
self.height = height
self.data = [] # this will be the board... |
59d0eda233767d5a6d0b7ede9490fe828a07548d | pymft/mft-vanak | /S12/decorators/what_is_decorator.py | 416 | 3.640625 | 4 | def echo(s):
return s
def echo_multiple_times(s, n):
return echo(s) * n
def get_echoer(n):
def f(s):
return echo_multiple_times(s, n)
return f
echo_twice = get_echoer(2)
# def echo_twice(s):
# return echo_multiple_times(s, 2)
echo_10 = get_echoer(10)
# def echo_10(s):
# return ech... |
3fa121a3b7e2b9bc9ab5389b4ae672f1ad8c8fac | MoKamalian/CSCI2202 | /Solutions for lab 1-B nd assing1 nd test/Test/Question3.py | 966 | 4.125 | 4 | # Question 3: Dice Rolling Probabilities
import random
# Set the number of simulations (default 100000).
N = 100000
# Set up counters for keeping track of the number
# of times each condition is met.
countSix = 0
countTwelve = 0
# Simulate the dice rolling N times.
for _ in range(N):
# Generate... |
b2968cfd083bc711abf0cc5b97730d01dc70b2e9 | scottr/tvinfo | /tvinfo/model.py | 7,289 | 3.75 | 4 | """ Data model for TV series, seasons and episodes.
"""
class Series:
""" A TV Series.
Generally, this class is not instantiated directly, but instead is
created by the series_search() method of the tvinfo module.
"""
def __init__(self):
self.__title =... |
c565c8e4dd693852e395897f738e3866403d38ba | hcshires/APCSP | /falling_rectangle.py | 1,591 | 3.5625 | 4 | import tkinter as tk
import random
xvel = 0
times_clicked = 0
yvel = -5
def clicked(event):
global times_clicked #use the global variable within this function
x = event.x # the x coordinate of your click
y = event.y # the y coordinate of your click
print(canvas.coords(1)) # print the coordinates of the rectangle ... |
0d02858b74f60409851b449388da228c0f89d420 | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv8.py | 1,689 | 3.953125 | 4 | # 8 Faça um Programa que pergunte quanto você ganha por hora e o
# número de horas trabalhadas no mês. Calcule e mostre o total do
# seu salário no referido mês, sabendo-se que são descontados 11%
# para o Imposto de Renda, 8% para o INSS e 5% para o sindicato,
# faça um programa que nos dê:
# - salário bruto.
# - quan... |
e75fe49f87c503c2d8e7fac3f6d253925d007afc | kvijayenderreddy/march2020 | /loops/NestedIfLoop.py | 137 | 4.03125 | 4 |
a = 30
b = 30
if (a<b):
print("a is greater than b")
elif (a>b):
print("b is greater")
else:
print("a and b are equal")
|
88dfe92ef26f3f4e34a85c0fae92bb0678e151c3 | alex9269/ECE351_Code | /lab2.py | 2,505 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 19:59:58 2019
@author: alexa
"""
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 14})
steps = 1e-2
t = np.arange(0,10+steps,steps)
def func1(t):
y = np.zeros((len(t),1))
for i in range(len(t)):
... |
6a081dbb1acef18695db4d27aae096682973d790 | Dissssy/AdventOfCode2020 | /09/2/code.py | 1,020 | 3.625 | 4 | import time
start_time = time.time()
#open the file and parse it into a list of strings on newlines
text_file = open("input.txt", "r")
lines = text_file.read().split('\n')
#every input text file has an empty newline at the end, delete it
lines.pop(-1)
def isvalid(i):
for j in range(i - 25, i):
for l in ra... |
0847cb673c662e90446ddd484e19f141b07315be | jilee210/hello-world | /wcounter.py | 1,293 | 3.546875 | 4 | #!/usr/bin/python
# JL 081017 to simulate wordcount.py with High Performace collections container Counter availble >= version 2.7
# Note: python 2.7 and 3.x, Counter not available in 2.6
# ======================================================
import sys
from collections import Counter as C
if len(sys.argv) < 2:
pri... |
9d86e750a6924e1996374d8e3ba860f374b87a7b | huhudaya/leetcode- | /LeetCode/546. 移除盒子.py | 686 | 3.546875 | 4 | '''
给出一些不同颜色的盒子,盒子的颜色由数字表示,即不同的数字表示不同的颜色。
你将经过若干轮操作去去掉盒子,直到所有的盒子都去掉为止。每一轮你可以移除具有相同颜色的连续 k 个盒子(k >= 1),这样一轮之后你将得到 k*k 个积分。
当你将所有盒子都去掉之后,求你能获得的最大积分和。
示例:
输入:boxes = [1,3,2,2,2,3,4,3,1]
输出:23
解释:
[1, 3, 2, 2, 2, 3, 4, 3, 1]
----> [1, 3, 3, 4, 3, 1] (3*3=9 分)
----> [1, 3, 3, 3, 1] (1*1=1 分)
----> [1, 1] (3*3=9 分)
----> [... |
fed249dd7b78521cf04f042016db001b0d8fc927 | jnovikov/patterns_examples | /computer.py | 927 | 3.515625 | 4 | class State(object):
allowed_states = []
state_description = None
def change_state(self, state):
if state.state_description in self.allowed_states:
return True
return False
class StateOn(State):
allowed_states = ["sleep", "off"]
state_description = "on"
class StateOf... |
cc57c034de41a330f65ccc426c0331a4110f511c | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec5_Basics_func_condtiton/section_recap.py | 1,028 | 4.4375 | 4 | # Cheatsheet (Functions and Conditionals)
# In this section, you learned to:
# Define a function:
def cube_volume(a):
return a * a * a
# Write a conditional block:
message = "hello there"
if "hello" in message:
print("hi")
else:
print("I don't understand")
# Write a conditional block of multiple con... |
20b629f9355912044f6048f4f3a6abd9b8343f44 | olgarithms/advent_of_code_2019 | /Day05/task2.py | 2,761 | 3.78125 | 4 | filename = "input.txt"
result = None
def get_numbers():
with open(filename, 'r') as textfile:
line = textfile.readline().strip("\n")
return list(map(int, line.split(',')))
def get_parameter(mode, i, pos, numbers):
return numbers[get_address(mode, i, pos, numbers)]
def get_address(mode, i, pos... |
020eac8e025e72936f95d556ffcef462f7c84a54 | dmr8230/UNCW-Projects | /CSC231-Python/Chp 10 - Recursive Sum/mySum.py | 2,375 | 4.25 | 4 | '''
Author: Dani Rowe
Date: October 13th, 2020
Description: This program implements a recursive sum operation on a list
'''
import random
def recSum1(someList):
'''
this function adds all the items in the list together
:param someList: takes the list
:return: the sum of the function
'''
if len(s... |
59e053a59597acb62aecb3b49e1fe1f650d24a5c | muyawei/DataAnalytics | /Pandas_Date/pandas_data/combine_first.py | 539 | 3.9375 | 4 | # -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
# 用参数对象中的数据为调用者对象"打补丁"
df1 = pd.DataFrame({"a": [1, 3, np.NaN, 4],
"b": [2, np.NaN, 4, 6]
})
df2 = pd.DataFrame(np.arange(12).reshape((2, 6)))
df = df1.combine_first(df2)
print "df1"
print df1
print "df2"
print df2
p... |
902b52a221512b1cbb284df287ac287ccf66f34c | gagan405/ProjectEuler | /p94.py | 756 | 3.84375 | 4 | sum = 0
limit = 1000000000
def getNextVal(a, b):
return ((2*a + 3*b), (a + 2*b))
def getTriangles():
global sum
x = 2
y = 1
# a = x**2 + y**2
# b = 2*(x**2-y**2)
while(True):
a3 = 2*x - 1
area3 = y*(x-2)
if(a3 > limit):
break
... |
a7522bc846faa2b76b28167a3a9c2883d22dfb5e | dani-fn/Projetinhos_Python | /projetinhos/ex#24 - verificando as primeiras letras de um texto.py | 131 | 3.921875 | 4 | print('Será que sua cidade começa com Santo?')
cid = str(input('Em que cidade você nasceu? ')).upper()
print('SANTO' in cid)
|
e6c858b32f2be71af8baff8bab0ba94e88ef1f2c | abhijitdey/coding-practice | /facebook/arrays_and_strings/1_longest_substring_without_repeating_chars.py | 939 | 3.703125 | 4 | class Solution:
"""
1. Keep track of the index where you see each char
2. Whenever you find a repeating char, make sure you mark that index+1 as the start of a new substring
and start counting the length from there. last_valid_index keeps track from where the substring starts.
3. Store the value of ... |
832c6b1f8ba2ee1eec1d13419216bf5d669bf219 | ZoomQuiet/zoomquiet.tangle | /s5/070322-introPy/py/pythonic.py | 4,097 | 3.8125 | 4 | # coding : utf-8
''' prime = sieve [2..] ---改进后的素数数列
sieve (x:xs) = x : sieve (filter (\y ->y `rem` x /= 0) xs)
'''
#想将数组中大于某个数值的数选出来构成一个新的数列
li = range(3)
import random
random.shuffle(li)
[item for item in li if item > 3.5 ] #(注:source是一个List)
############### 数据类型
素数计算
http://aspn.activestate.com/ASPN/C... |
62d515e9d947726197ae8760d67871dd142ce497 | Miracle-cl/Algorithms | /Recursion/WordBreak.py | 1,223 | 3.578125 | 4 | from typing import List
from functools import lru_cache
# TLE Solution without lru_cache
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
return self.recursive(s, tuple(wordDict))
@lru_cache(maxsize=128)
def recursive(self, s, wordset):
if not s:
... |
096ba953040c69fe2de0ea6181e16c45c187fbb5 | AMujeebDalal/python_bootcamp | /Podomora/km-mile_converter.py | 1,011 | 3.984375 | 4 | from tkinter import *
def calculate():
miles = float(miles_input.get())
km = round(1 / 1.6093 * miles, 3)
km_result.config(text=km)
window = Tk()
window.title("Miles-Km Converter")
window.minsize(width=200, height=150)
window.config(padx=20, pady=30)
is_equal = Label(text="is equal to", fon... |
48e68203e86a00f32dacd993b0955441a50f90e6 | doortothe/kaggle_hash_code_2021 | /classes/__init__.py | 1,085 | 3.71875 | 4 | def validate_variable(var, var_check):
"""
Check if variable is within appropriate constraints
Return the variable if true
Otherwise, return an error
:param var: variable being checked
:param var_check: the variable to check
:return: var if within proper constraints. Otherwise, raise an erro... |
b8e41ef49175f2cda1bc9278271274425080f10d | Dagim3/MIS3640 | /quiz3_dagim.py | 1,354 | 3.8125 | 4 | # Upload quiz_3.py file to Blackboard - Session 13
def replace_even(data):
def replace_even(data):
for x in data:
if x%2 != int:
data.remove(x)
data.insert(x,0)
# Uncomment the following lines to test
ONE_TEN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
replace_even(ONE_T... |
d771a924c87eec8b35ce3bc9c82011a654607a29 | Sanchi02/Dojo | /LeetCode/TreeTraverseProblems/EvenValuedGrandParents.py | 1,749 | 3.765625 | 4 | # Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.)
# If there are no nodes with an even-valued grandparent, return 0.
# Example 1:
# Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
# Output: 18
# ... |
ceadeebcaa818f234ce6871394c5e7bb25568738 | tat2133/advent-of-code | /day01/part2.py | 405 | 3.6875 | 4 | frequency = 0
calibrated = False
frequency_history = set()
while not calibrated:
with open('input.txt', 'r') as f:
for line in f:
frequency += int(line)
if frequency not in frequency_history:
frequency_history.add(frequency)
else:
calibrat... |
c27854e0153d8e6e3984369175779e021e383f59 | dahaihu/standard | /studing/Fp-grouth/fpgrouth.py | 13,777 | 3.71875 | 4 | """
如何在一棵树上,挖掘频繁一项集,二项集,三项集等等
条件模式基:是以所查找元素项为结尾的路径集合,表示的是所查找的元素项与树根节点之间的所有内容。
"""
class treeNode:
# 名字,次数,父节点
def __init__(self, nameValue, numOccur, parentNode):
self.name = nameValue # 当前节点的名称
self.count = numOccur # 当前节点在此模式下的出现次数
self.nodeLink = None # 用来指向跟当前节点name相同的,别的支上的节点
... |
abe7cffd8f38462ff179a000cc6337059ab4078b | mnavaidd/Python-Practice | /if-else.py | 276 | 3.796875 | 4 | y = 3 + 3
print (y)
z = y * 2
print (z)
if (z == 12):
print ("great")
else:
print ("wrong")
person = input("enter your name")
print ("Hello", person)
if (person == "navaid"):
print ("Hurray: Navaid you earned", z, "points.")
else:
print("Hello", person)
|
68b9d35fa4e36820a4fdbe6156f256a9b4bd220c | RhysMurage/alx-higher_level_programming | /0x06-python-classes/6-square.py | 2,118 | 4.53125 | 5 | #!/usr/bin/python3
"""Creates a square class"""
class Square():
"""
Define a square
"""
def __init__(self, size=0, position=(0,0)):
"""
size initialization.
Args:
size: integer value
"""
if type(size) != int:
raise TypeError('size must b... |
2746e77b0c91a2d634bdc6fd276f2316054ef13a | lightning720z/belajar-python | /Elif.py | 281 | 3.953125 | 4 | # Belajar Elif else if
menu_pilihan = input("Silahkan pilih menu [1-3] : ")
if menu_pilahan == "1":
print("anda memilih 1")
elif menu_pilahan == "2":
print("anda memilih 2")
elif menu_pilahan == "3":
print("anda memilih 3")
else:
print("menu tidak ada") |
c825cd3abf3d97e5c82e829f49b76a4887ff44ea | fenixfurion/aoc2020 | /2020/day09/day9.py | 1,885 | 3.90625 | 4 | #!/usr/bin/env python
def check_valid(previous_list, check_value):
for i in range(0,len(previous_list)):
# print("i: {}".format(i))
search_value = abs(check_value-previous_list[i])
if search_value in previous_list[0:i] or search_value in previous_list[i:]:
print("Found values {}... |
c248504545472550f128d4ba776984db1432ef1e | shankarkrishnamurthy/problem-solving | /longest-mountain.py | 885 | 3.96875 | 4 | class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
lm,i,cl = 0,1,-1
if len(A) < 3: return 0
print A
while i < len(A)-1:
if A[i] > A[i-1] and A[i] > A[i+1]:
# Found a mountain peak
... |
09cad1f19bf0caeee98dc93996220faf67981143 | spice0xff/lear_php_laravel_test | /main.py | 1,108 | 3.59375 | 4 | import random
def task1():
number_list = ", ".join([str(int(100*random.random())) for index in range(100)])
with open("numbers.csv", "w") as file:
file.write(number_list)
def task2():
with open("numbers.csv", "r") as file:
data = file.read()
number_list = data.split(", ")
more_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.