blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
63c28b4a1bc9dfe225ab54e40f643734b8754bd6 | Pankaj-GoSu/Python-Tutorials | /Advanced/Qu3.py | 87 | 3.703125 | 4 | num =int(input("Enter a number"))
table = [num*(i+1) for i in range(10) ]
print(table) |
9941a5bfbf8964a592e973efbb49fd18742d8f5b | truongductri01/Hackerrank_problems_solutions | /Problem_Solving/Medium/3D_Surface_Area/3D_Surface_Area.py | 2,442 | 3.828125 | 4 | # Link: https://www.hackerrank.com/challenges/3d-surface-area/problem
# first create an array which consists of the following things
# for even indexed element represent the common side of two adjacent block in a row
# for the odd indexed element represent the common side of two adjacent block in each column of two co... |
e636bb6eab41001f7fc108e259762b440cd390d1 | unlimitediw/CheckCode | /0.算法/147_InsertionSortList.py | 2,850 | 3.96875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = result = ListNode(0)
... |
f490e6054c9d90343cab89c810ca2c649d8138fe | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/mergeIntervals.py | 1,167 | 4.125 | 4 | """
Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,... |
95e783903edc5da26d88e2f6243b5c8f5492aa03 | cafaray/atco.de-fights | /newNumeralSystem2.py | 226 | 3.53125 | 4 | def newNumeralSystem(number):
res = []
n = ord(number) - 65
for x in range(0,26):
for y in range(0,26):
if x+y ==n and x<=y:
res+=[chr(65+x) + ' + ' + chr(65+y)]
return res
|
a95a89372a4d22d820b80273034c4915913968cc | crjake/snake | /snake.py | 3,034 | 3.5625 | 4 | import pygame
import random
class Snake:
color = (0, 255, 0)
def __init__(self, x, y):
self.cells = [Cell(x, y)]
self.direction = 'LEFT'
def draw(self, screen):
for cell in self.cells:
cell.draw(screen)
def grow(self, x, y):
self.cells.insert(0, Cell(x,y))... |
25f8f808dbd7aed6caaa304fff17bb4d3b7c9a19 | sotossotos/SinglyLinkedList | /singly_linked_list.py | 1,890 | 3.734375 | 4 | class Node:
def __init__(self,value=None,nextNode=None):
self.value=value
self.nextNode=nextNode
class SinlgeLinkedList:
def __init__(self,node=None):
self.list=node
self.size=0
def addNodeTop(self,value):
newNode=Node(value)
newNode.nextNode=self.list
... |
0d8dceba50028a3b1b74f099db6232e5dd3e563e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2354/48721/321243.py | 214 | 3.5625 | 4 | s = input()
s1 = input()
if(s1 == ".#."):
print(20)
elif(s1 == "###")|(s1=="..."):
print(1)
elif s1==".....#.........":
print(301811921)
elif s1=="##..#":
print(403241370)
else:
print(436845322) |
26751f3aebccc136fcca17fb4d5469c729d2644e | dgaikwad/python_codes | /opencv/image_rotation.py | 426 | 3.578125 | 4 | #!/usr/bin/python3
import cv2
import numpy as np
pic = cv2.imread("my_image.jpg")
rows = pic.shape[1]
cols = pic.shape[0]
print(rows, cols)
center = (cols/2, rows/2)
#if angle is positive then it will rotate image anticlock wise else closckwise
angle = 90
M = cv2.getRotationMatrix2D(center, angle, 1)
rotate = cv2.war... |
c2a0eec11ce71dc3595b8662ffa2573c141828f5 | volodiny71299/Right-Angled-Triangle | /03.5_rad_degv2.py | 428 | 4.25 | 4 |
# https://www.geeksforgeeks.org/degrees-and-radians-in-python/
# Python code to demonstrate
# working of degrees()
# for degrees()
import math
# Printing degrees equivalents.
print("pi / 180 Radians is equal to Degrees : ", end ="")
print (math.degrees(math.pi / 180))
print("180 Radians is equal to Degrees : ", end... |
2f3e457365a3a6c7e3f516fa09b4c33cce39a1dd | panzhh/python_course | /lesson_2.py | 4,300 | 4.15625 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ct... |
e2b5179ddb0401d559bf6db96567d05c3d587fab | elmehdiabdi/flw | /part2/_Programming Language Research Project (1).py | 10,859 | 3.5625 | 4 |
# coding: utf-8
# ##########################################################
# # CST8333 2018 Final Project #
# # #
# # Created by Jay Italia #
# # November 22 ,2018 #
# # ... |
2eb0ce2192d8bc51b9a513f7829443c9c471b4ca | tks18/python-projects | /Day 23/Final Project - Turtle Cross Game/car_manager.py | 1,004 | 3.765625 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
class CarManager():
def __init__(self):
self.allCars = []
self.increment = 3
self.startingDistance = 5
self.chance = 5
def create_car(self):
randomint = random.randi... |
7da6c355a52664e1d15b4a6b902b6eda4cb7ed99 | 953250587/leetcode-python | /MirrorReflection_MID_858.py | 1,372 | 3.796875 | 4 | """
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0t... |
1659d3a1550c283707b4be6ddd9b8ba6b7f7d6ec | Poonam-Patnaik/basic_programming_practice | /python_programs/product_not_available_in_cities.py | 421 | 4.21875 | 4 | cities_friend_lived = list(input('enter 10 city name where your friend lived').split(','))
product_available_in_city = list(input('enter 5 city name where product is available ').split(','))
product_not_available_in_cities = []
for city in cities_friend_lived:
if city in product_available_in_city:
continue
... |
8fdc30e3050a8698df528dd33f56237a280f0a52 | TheJacksonOfGreen/LearningPython | /PythonClassFolder/112.py | 210 | 4.1875 | 4 | #!/usr/bin/python
#112
#How to Break a loop
#Introduction: break
while True:
ask = input("What should I say? Say 'Stop' if you want me to stop asking you. >")
if ask == "Stop":
break
else:
print(ask)
|
121bcff99789c9bcef2223ba590807a1c7134b1b | KirutoChan/Leonhard | /leo4.py | 681 | 4.1875 | 4 | # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def is_polindrome(n):
n_list = []
p_list = []
for i in str(n):
n_list.append(i)
for i in range(le... |
76ea8bb763cb6fd400af2e493e5d398d2cdc1254 | Azim-Kurani/16-642-Manipulation-Estimation-and-Control | /Problem Set 1/code.py | 7,743 | 3.9375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import time
# Question 4
# This code will show each transformation in sequence from a) -> f) and will output the original coordinates of each
# of the 5 points on the rigid body followed by their new coordinates after the transformation. The plot that displays
# this ... |
f6c8ed4dd7b02893989e872f2d0a5f8235467a3c | plmon/python-CookBook | /chapter 1/1.14-sort-objects-not-support-comparison.py | 868 | 3.625 | 4 | # 1.14 对不原生支持比较操作的对象排序
# 目的:对不能进行比较操作的同一个类的实例进行排序
# 方法:利用sorted()和operator.attrgetter()结合进行排序
# 该方法同时可用于max()和min()函数
# attrgetter()相当于创建了一个函数,然后将函数作用于对象上
# 用处:创建同一个类的许多实例,想要对它们之间进行排序操作时
from operator import attrgetter
class Users:
def __init__(self, user_id):
self.user_id = user_id
# 格式化类... |
cc7171bbc70bce5e96c74cd1a211b07cf05a7477 | pmaywad/DataStructure-Algo | /Hash-Tables/open_adressing.py | 1,432 | 3.859375 | 4 | """
Implementation of Open Addressing in Hashing in Python
"""
class HashTable:
def __init__(self, size):
self.size = size
self.hash_table = [None]*self.size
def hash_function(self, key):
return key%self.size
def insert(self, key):
idx = self.hash_function(key)
w... |
83075f5166b00949d359abcc58c39253d0dfa688 | EmpressBelless/python-day3-exercise | /circle.py | 191 | 4.34375 | 4 | def mycircle():
Pi = 3.14
r = float(input("enter the radius of a circle, the output will be the circumference of a circle: "))
Area = Pi * r * r
return Area
print(mycircle()) |
c8e0a758c751b8da995af338be9e9416b4901e53 | study-material-stuff/Study | /Study/Python/Assignments/Assignment 7/Assignment7_2.py | 1,638 | 4.375 | 4 | #2. Write a program which contains one class named as BankAccount.
#BankAccount class contains two instance variables as Name & Amount.
#That class contains one class variable as ROI which is initialise to 10.5.
#Inside init method initialise all name and amount variables by accepting the values from user.
#There a... |
99b6515f3f42696fdf3998812f69542a86dc6fe5 | Romulo2013137/Python-Codes | /TAREFA004.py | 546 | 3.921875 | 4 | n = input('Digite algo')
print('O tipo primitivo do que foi digitado é ', type(n))
print('O que foi digitado é um espaço(s)?', n.isspace())
print('O que foi digitado contem apenas números?', n.isnumeric())
print('O que foi digitado contem apenas letras?', n.isalpha())
print('O que foi digitado contem letras e números?'... |
8d18d62cde219b45c9160bd43d019b7afa8a32a3 | nikel4610/sparta_coding | /알고리즘공부/week3/selection.py | 388 | 3.546875 | 4 | input = [4, 6, 2, 9, 1]
def selection_sort(array):
# 이 부분을 채워보세요!
n = len(array)
for i in range (1,n):
for j in range(i):
if array[i-j-1] > array[i-j]:
array[i-j-1], array[i-j] = array[i-j], array[i-j-1]
else:
break #시간복잡도 줄이기
return
s... |
82ce094048e1d7b486edf1c18995ca11ecf9f75d | joaoFelix/learn-python | /challenges/CarGame.py | 837 | 4.09375 | 4 | # Commands:
# help: shows every command that can be executed
# start: starts the car
# stop: stops the car
# quit: exit the game
command = ""
car_is_started = False
while True:
command = input("> ").lower()
if command == "help":
help_msg = '''start: starts the car
stop: stops the car
quit: exit the g... |
62035ef273014e44d647db00778467e6b87c579a | GoogolDKhan/Roommates-Gym-Management-System | /main.py | 1,745 | 4 | 4 | # Creating dictonaries for roommates use
roommates = {1: "Sarfaraz", 2: "Sashant", 3: "Prabhjot"}
log = {1: "Exercise", 2: "Diet"}
# log current date and time
def getdate():
import datetime
return datetime.datetime.now()
try:
# Input the selected roommate and his option to log or retrieve
print("Se... |
bae13204418cc2d3c5e9baebf3459fe56f0218a2 | dmlc/gluon-cv | /docs/tutorials/classification/transfer_learning_minc.py | 10,387 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""4. Transfer Learning with Your Own Image Dataset
=======================================================
Dataset size is a big factor in the performance of deep learning models.
``ImageNet`` has over one million labeled images, but
we often don't have so much labeled d... |
3f207ab7299b3136d4b76bb92bcbec042b5a36d5 | weed478/asd1 | /exam/1/zad1.py | 1,202 | 3.796875 | 4 | """
Jakub Karbowski
Do każdego elementu dołączamy jego orginalny indeks; element to krotka (value; original index).
Puszczamy zwykły insertion sort (dobry do k-chaotycznych tablic).
Insertion sort będzie sobie przekładał elementy aż skończy.
Na końcu sprawdzamy o ile każdy element się przesunął i liczymy największe pr... |
571ecc65e0d19494138b861d348eb434d434740f | park-seonju/Algorithm | /2일차/1번.py | 374 | 3.5625 | 4 | list1=[(90,80),(85,75),(90,100)]
a=list1[0]
b=list1[1]
c=list1[2]
print("1번 학생의 총점은 {}점이고, 평균은 {:.1f}입니다.".format(sum(a),sum(a)/len(a)))
print("2번 학생의 총점은 {}점이고, 평균은 {:.1f}입니다.".format(sum(b),sum(b)/len(b)))
print("3번 학생의 총점은 {}점이고, 평균은 {:.1f}입니다.".format(sum(c),sum(c)/len(c))) |
ece5eeb9ae0ec6bbff35d0c7f9448e81532ae8c2 | Alarical/LeetCode | /solution/98ValidateBinarySearchTree.py | 685 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def dfs(root, Min ... |
212917d8632ff3d9d03628bcebd888fe356b6df4 | Indrasena8/Python-Programs | /GeometricProgression.py | 232 | 3.9375 | 4 | def printGP(a, r, n):
for i in range(0, n):
curr_term = a * pow(r, i)
print(curr_term, end =" ")
a = 2 # starting number
r = 3 # Common ratio
n = 5 # N th term to be find
printGP(a, r, n) |
890c8709e8610cdf59f300da43e306138fe132ae | nishadhperera/ml | /data_preprocessing/missing_data.py | 1,797 | 3.5625 | 4 | # Data Preprocessing
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Taking care of missing data
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection... |
79501bf7bbd2b186dc52549c1b711967a1734d23 | fredrikj31/DDD-2020 | /Romertal/romertal.py | 736 | 4 | 4 | """
ROMER TAL:
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
"""
def insertSymbol(OrderNR, Number):
if (OrderNR == 1):
if Number == '1':
return "I"
elif Number == '2':
return "II"
elif Number == '3':
return "III"
elif Number == '4':
return "IIII"
elif Number == '5':
return "V"
elif Nu... |
a7317a4d6f874cb7df22b1ebe27d144c4365a323 | pinggit/leetcode | /python/002_Add_Two_Numbers.py | 3,957 | 3.90625 | 4 | """
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 the
number 0 itself.
"""... |
53290565833ace542e19121943f6f42aa9c82bff | ayrtondenner/ARP-2017-1 | /Lista 1 - Regressão/Respostas - Ayrton Denner/exercicio_quatro.py | 2,448 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
# Método para desenhar a grid e deixar ela atrás dos pontos e das retas
def prepara_grid():
figure = plt.figure()
axis = figure.gca()
axis.set_axisbelow(True)
plt.grid(linestyle = ":")
return
# Método para colocar os labels do gráfico
def seta... |
1a1f7576a38a4b86fa19379c3ae07fb379e82581 | BronyPhysicist/BaseballSim | /calendar/calendar.py | 1,738 | 3.875 | 4 | from date import Day
from date import Month
from date import Date
start_date = Date(Day.WED, Month.APR, 1, 2006)
#Consider moving to calendar_window?
def fill_rows_cols(start_date, builder):
start_row = int(start_date.numday / 7) + 1
start_col = start_date.day.num()
cur_date = start_date
for row in range(1, 7):
... |
74ce65dff5716b7df8b187055d792bbf7c14679b | jakehoare/leetcode | /python_1_to_1000/747_Largest_Number_At_Least_Twice_of_Others.py | 1,065 | 3.6875 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/largest-number-at-least-twice-of-others/
# In a given integer array nums, there is always exactly one largest element.
# Find whether the largest element in the array is at least twice as much as every other number in the array.
# If it is, retur... |
2c424524c7a6d59d74c97960079fb71e9c592761 | JWiryo/HackerRank | /Algorithms/Implementations/StudentGrading.py | 672 | 3.640625 | 4 | #!/bin/python
import sys
import math
def solve(grades):
# Complete this function
newScores = []
for score in grades:
if score < 38:
newScores.append(score);
elif (roundToNearest5(score) - score) < 3:
newScores.append(roundToNearest5(score));
else:
... |
48643696961cc2d9e849e341a06dbecf1e0e1410 | AljosaZ/Simple-calculator | /simple_calculator.py | 1,677 | 4.125 | 4 | print("Welcome to my simple calculator! \n")
count = 0
while True:
if count == 6:
print("\nWas that really that hard?")
quit()
else:
try:
x = float(input("Please enter the first number: "))
break
except ValueError:
print("Please choose a numbe... |
93e0634760c414fca94f20fe364aac9d0dae59e7 | ridersw/RedditProblems | /toggleButtonProblem.py | 1,795 | 4.375 | 4 | #The problem is:
#A light bulb is connected to n switches in such a way that it lights up only when all the switches are closed. Each switch is controlled by a push button; pressing the button toggles the switch, but there is no way to know the state of the switch. Design an algorithm to turn on the light bulb with th... |
87e8598519dd354173a1350a41b87b48113f8653 | ishankkm/pythonProgs | /leetcode/addBinary.py | 1,005 | 3.765625 | 4 | '''
Created on May 5, 2018
@author: ishank
Given two binary strings, return their sum (also a binary string).
'''
def addBinary(a, b):
carry = 0
lenA, lenB = len(a), len(b)
result = ""
padding = ""
for i in range(abs(lenA - lenB)):
padding += "0"
if lenA > lenB:
... |
7e125ab8f853ebea819f1fffcb62ca6d2ba698b8 | vdesire2641/Python-list-operations | /pyt6.py | 224 | 3.875 | 4 | # write a function that takes a sentence as a parameter and returns the number of words in the sentence.
# 4.5
def take(sentence):
s = str(sentence)
print(s.split())
print(len(s.split()))
take("jerry likes to eat")
|
5b16f728a580819924bcab19688bfd92ec1b3de6 | frankShih/LeetCodePractice | /234-palindromLinkedList/solution.py | 1,493 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
'''
# using list 45%, time: O... |
f0fc579a31e5cb4f90a8f0602ef805574b600c95 | elitwilliams/project-euler | /15.py | 284 | 3.609375 | 4 | # Simple combinatorics problem of 2n choose n paths
from math import factorial
sides = raw_input("Enter side length of square lattice:")
def square_lattice_paths(n):
return factorial(2*n)/(factorial(n)**2)
print square_lattice_paths(int(sides))
# Solution = 137846528820
|
03d0ba8c88437608748e182e227bb9d0e832948d | jadeli1720/Sprint-Challenge--Intro-Python | /src/comp/comp.py | 2,747 | 4.46875 | 4 | # The following list comprehension exercises will make use of the
# defined Human class.
class Human:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"<Human: {self.name}, {self.age}>"
humans = [
Human("Alice", 29),
Human("Bob", 32),... |
260ebb8b9120ae446ec0a4c9a9562b1df32876c5 | silastsui/interview-practice | /euler/1.py | 132 | 4.1875 | 4 | def find_sum_of_multiples(num):
return sum([x for x in range(num) if x%3 == 0 or x%5 == 0])
print(find_sum_of_multiples(1000))
|
7876ae01680c2a9b613c961926a75a2e4652125b | yuansun86/leetcode | /Code/216. Combination Sum III.py | 508 | 3.515625 | 4 | class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
results = []
self.backtracking(0, k, n, [], results)
return results
def backtracking(self, index, k, n, path, results):
if k == 0:
if n == 0:
results.append(path[:])
... |
886010fde60a99179a2b35ad35545992e5118212 | KrishnaPrasath/CODEKATA_G | /Strings/wonderful.py | 380 | 4 | 4 | # check if a string us wonderful or not
# a string is wonderful if it is made up of only 3 chars
# done
try:
s = input()
except EOFError as e:
print(-1)
dic = {}
temp = 0
for each in s:
if each in dic:
temp = dic[each]
dic[each] = temp+1
else:
temp = 0
dic[each] = temp+1... |
b8eec6ba35081819b6f122cad301f8e7e37c49ba | cothuyanninh/Python_Code | /fsoft/Week 1/B1/bai6.py | 404 | 3.90625 | 4 | """C1"""
string_word = "Fresher Academy"
for i in range(len(string_word)):
if string_word[i] == "a":
# print("hihi")
string_word = string_word.replace(string_word[i], "@")
elif string_word[i] == "e":
string_word = string_word.replace(string_word[i], "3")
print(string_word)
"""C2"""
string_word = "Fresher Acade... |
a57d2db2469b743437316d898d106d1f6c305e4e | Zerobitss/Python-101-ejercicios-proyectos | /proyecto_agenda/practice.py | 140 | 4.03125 | 4 | nombre = str(input("Escribe tu nombre: "))
print (f"Hola {nombre.upper}")
print("Su nombre tiene una cantidad de letras de: ", len(nombre))
|
868dcf3acfd587a3c99bd35d65b2c70081f885b5 | nrb/jp-cli-flashcards | /table_builder.py | 2,853 | 3.5625 | 4 | from collections import defaultdict
from lxml import html
from pprint import pprint
import requests
def parse_table(japanese_rows, character_map, insert_key, basic_class):
"""Insert the information in the HTML table into the character dict.
Romaji will be keys, values are a dictionary of either hirigana or
... |
928192655b19164fc98228d3c4196d69b2eece7e | CircularWorld/Python_exercise | /month_02/teacher/day16/select_server.py | 1,312 | 3.9375 | 4 | """
基于select 的IO多路复用并发模型
重点代码 !
"""
from socket import *
from select import select
# 全局变量
HOST = "0.0.0.0"
PORT = 8889
ADDR = (HOST,PORT)
# 创建tcp套接字
tcp_socket = socket()
tcp_socket.bind(ADDR)
tcp_socket.listen(5)
# 设置为非阻塞
tcp_socket.setblocking(False)
# IO对象监控列表
rlist = [tcp_socket] # 初始监听对象
wlist = []
xlist = []
... |
950da3803d15ad4c5634e90f56c99276faddcad8 | yusufcankann/Introduction-To-Algorithms | /Final/question5.py | 1,845 | 4.0625 | 4 | #Yusuf Can Kan
#for map function.
#this doubles the ight part of the array
def double(n):
return n*2
#mergesort.
def countInverseWithMergeSort(my_arr):
inversionCount=0
if len(my_arr)<=1:
return 0
middle=len(my_arr)//2
left=my_arr[:middle] #left part
right=my_arr[middle:] #right part... |
f180916af608781beecc94f98beed2134bac54d1 | noorul90/Python_Learnings | /TupleTest.py | 334 | 4.25 | 4 | #list is mutable but tuple is not mutable means once you create the tuple you can't change value in tuples
numsTuple = (12,15,14,52,44) #12,15,14,52,44
nums = 14,52,55,25
print(type(nums), nums)
print(numsTuple)
print(numsTuple[1])
#immutable nature
#numsTuple[1]=15 #gives error beacause we can't change the value
#pr... |
1f1eed0f8bede71d14c1cbd274932e6ff0b9dc20 | jayhebe/w3resource_exercises | /Basic - Part1/ex133.py | 373 | 3.5 | 4 | # import datetime
#
#
# start_time = datetime.datetime.now()
#
# for _ in range(100000):
# pass
#
# end_time = datetime.datetime.now()
# print(end_time - start_time)
from timeit import default_timer
def timer(n):
start = default_timer()
# some code here
for row in range(0, n):
print(row)
... |
b933450da19e624724a2df4d52df77cfeea8f1cf | Loptt/mph-programming-101 | /Clase3/EjercicioEx4.py | 906 | 4.03125 | 4 | numero = int(input("por favor ingrese un numero: "))
if numero > 0:
#positivo
if numero % 2 == 0:
#par
if numero < 100:
#menor a 100
print("es un numero positivo, par y menor a 100")
elif numero > 100:
#mayor a 100
print("es un numero posi... |
a2772aa84854ad6d6e50f0874fcd0f33b2f4636d | sametdlsk/python_Basics | /basicDataTypes.py | 7,923 | 3.84375 | 4 | # -*- coding:utf-8 -*-
"""
Bu kodlar Python ile Pycharm editörü kullanılarak yazılmıştır.
Bu kod basit sorular topluluğudur. Sorular Türkçedir.
These codes are written using the Pycharm editor in Python.
This code it contains simple questions in Turkish,
used random.
"""
import random
def againAn... |
7dfb15c020febdc9ef00584fe800332abc75d8e7 | johnthomasjtk/Codeforces-solved-programs | /watermelon.py | 70 | 3.734375 | 4 | s = input()
if s % 2 == 0 and s > 2 :
print "YES"
else :
print "NO"
|
c44a37f819b3705b6832603ed4ac385e3750c0cc | storbukas/university | /INF237/set_1/sheep.py | 1,609 | 3.671875 | 4 | def adjacent(x,y,data):
neighbours = []
if(valid(x+1,y,data) and data[x+1][y] == "#"):
neighbours.append((x+1,y))
if(valid(x-1,y,data) and data[x-1][y] == "#"):
neighbours.append((x-1,y))
if(valid(x,y+1,data) and data[x][y+1] == "#"):
neighbours.append((x,y+1))... |
aab2b13ca01dd80ff2622a768b81a05c525042eb | Jsonghh/leetcode | /200113/Unique_Binary_Search_Trees_II.py | 855 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if not n:
return []
return self.helper(1, n)
def ... |
f2762711152cf6617f935de4e69cf285c44bc08f | LRS4/mit-6.00.1x | /recursion.py | 764 | 3.9375 | 4 | def fact(x):
"""
Find the factorial of any number
"""
if x == 1:
return 1
else:
return x * fact(x - 1)
print("Factorial of 4 is " + str(fact(4)))
def fib(x):
"""
Find the Fibonacci of x
"""
if x == 0 or x == 1:
return 1
else:
r... |
4155aeca9cee9c1f911a2828d0548527e738c782 | SpCrazy/crazy | /code/SpiderDay1_Thread/ticket_lock/ticket_lock.py | 717 | 3.515625 | 4 | import time
from threading import Thread, currentThread, Lock
#买票问题
class TicketThread(Thread):
ticket = 5 #所有窗口共享5张票(类属性)
lock = Lock()
def __init__(self,thread_name):
super().__init__(name=thread_name)
def run(self):
for i in range(100):
TicketThread.lock.acquire()
... |
d238c2d9308eeb137b15d9c320464a5cc970a4bd | MartinMa28/Algorithms_review | /union_find/0684_redundant_connection.py | 1,885 | 3.609375 | 4 | class DisjointSet:
class Node:
def __init__(self, x):
self.parent = self
self.rank = 0
self.val = x
def __init__(self):
self.num_to_node = {}
def make_set_by_edges(self, edges):
for e in edges:
if e[0] not in se... |
f9c3c32eb310fa3072cac3d53475fbdfbbec800a | tarunluthra123/Competitive-Programming | /Leetcode/Pascal's Triangle.py | 449 | 3.609375 | 4 | from math import factorial as f
class Solution(object):
def generate(self, n):
"""
:type numRows: int
:rtype: List[List[int]]
"""
def nCr(n, r):
num = f(n)
den = f(r)*f(n-r)
return num//den
res = []
for i in range(n):
... |
7b8afaab4569cc450927d80b2389901c91ad2790 | fedeisas/advent_of_code_python | /2a/keyboard.py | 1,017 | 3.515625 | 4 | class Keyboard():
def __init__(self):
self.keyboard = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
self.position = (1, 1)
self.code = []
self.movements = {
'U': (-1, 0),
'R': (0, 1),
'D': (1, 0),
'L'... |
277427fb348c23c1d9542dcfaacfc88bb0dcb7d9 | robdale110/PythonCourse | /WritingToFiles.py | 330 | 3.8125 | 4 | # Creates and writes to empty file, doesn't add to existing file
file = open("example1.txt", "w")
file.write("Line 1")
file.close()
file = open("example1.txt", "w")
file.write("Line 2")
file.close()
line = ["Line 1", "Line 2", "Line 3"]
file = open("example1.txt", "w")
for item in line:
file.write(item + "\n")
fil... |
2bcc8ded46d5d8d492fdad93c63321fd75274caa | jayadevgithub/BCR | /AsyncProject/copy_test.py | 177 | 3.71875 | 4 | import copy
# a = {"a":1,"b":2}
# b = copy.copy(a)
# b["c"] = 3;
# a["c"] = 4;
a = [1,2,3]
b = copy.copy(a)
a.append(4)
print("a "+str(a))
print("b "+str(b))
alp |
c900a585490971101e9d88dc7b2fc1790b79c034 | TheDarkKnight1939/FirstYearPython | /Greater.py | 152 | 3.640625 | 4 | j=0
for j in range(0,7):
a[j]=int(input("Input 6 numbers")
for i in range(0,6):
if a[i]>10:
print(a[i])
|
9320acada498bf5640240d37f664450cef8e97a4 | superbeckgit/cypherpuzzle | /cypher.py | 4,154 | 3.6875 | 4 | #!/usr/bin/python
from itertools import permutations
import pdb
import sys
def build_cypher_list(cylen=4):
"""
Build a list of cyphers using cylen characters each. List is all permuations.
Parameters
----------
cylen - num - number of characters per cypher
Returns
-------
cylist - []... |
0ebc2b4598a9c0a6b1f06dd62ec2daf115fc652c | zhuhaoyue/test7 | /777.py | 623 | 3.859375 | 4 |
import random
counts = 3
answer = random.randint(1,10)
while counts > 0:
temp = input("不妨猜一下小七宝现在心里想的是哪一个数字:")
guess = int(temp)
if guess ==answer:
print("你是小七宝心里的蛔虫嘛? !")
print("哼,你猜中了也没奖励 !")
break
else:
if guess < answer:
print("小啦")
else:
... |
41c0884ceb495da58a16a74c4b299276ea90009c | karenlorhana/decisao_e_repeticaoPython | /exerciciosDecisao/questao04.py | 299 | 4 | 4 | #calcular média aluno dizendo sua média
nota1 = float(input("digite a primeira nota: "))
nota2 = float(input("digite a segunda nota: "))
media = (nota1 + nota2)/2
if(media >= 6):
print("o aluno foi aprovado com a média ", media)
else:
print("o aluno foi reprovado com a média ", media)
|
e978af14aa4eb719c0935aecd1768fe07df1be22 | fcdennis/CS50 | /problems_set/pset7/houses/import.py | 705 | 3.875 | 4 | import csv
from cs50 import SQL
from sys import argv, exit
if len(argv) != 2:
print("Usage: python import.py characters.csv")
exit(1)
db = SQL("sqlite:///students.db")
def main():
with open(argv[1]) as csv_file:
data = csv.DictReader(csv_file)
for row in data:
names = partiti... |
b5f9ebd0ed618e63098274b75b12063fc545437d | c940606/leetcode | /Word Pattern.py | 1,240 | 3.6875 | 4 | class Solution(object):
def wordPattern2(self, pattern, str):
"""
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。
这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式
---
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
----
思路:
通过模式把字典造出来,
:type pattern: str
:type str: str
:rtype:... |
0cffd304b5bd2b9e19d68282be4949f7e77a8fb7 | sjullieb/HackerRank_Python | /6_5 Queues and Stacks.py | 3,909 | 3.859375 | 4 | class Stack:
def __init__(self, size):
self.items = []
self.size = int(size)
for i in range(self.size):
self.items.append('')
self.isfull = False
self.current = 0
def isEmpty(self):
return self.isempty
def push(self, item):
... |
c9a6708eaf8e4deb40eebee4cfcfb2db934fab33 | jwu424/Leetcode | /ShortestUnsortedContinuousSubarray.py | 1,442 | 3.8125 | 4 | # Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
# You need to find the shortest such subarray and output its length.
# 1. sort the nums and compare the sorted nums with nums from begi... |
ff0f9a6cfc46b69e441b2e4d111409e388b387cf | nekapoor7/Python-and-Django | /GREEKSFORGREEKS/List/duplicate_element.py | 270 | 4.09375 | 4 | #Python | Program to print duplicates from a list of integers
list1 = list(map(int,input().split()))
new_list = sorted(set(list1))
dup_list = []
for i in range(len(new_list)):
if list1.count(new_list[i]) > 1:
dup_list.append(new_list[i])
print(dup_list)
|
80b850c10e359eaf319a11b2e735bcc37fbdbcac | igorsantos314/PythonForLife | /Person.py | 1,173 | 4.25 | 4 | class Person:
name = ''
age = 0
height = 0
weight = 0
#constructor
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
#gets
def getName(self):
return self.name
def getAge... |
3391af853761c080256c594278d0925b25b7ac14 | sota1235/AOJ-Answers | /answers/0027.py | 300 | 3.78125 | 4 | #!/usr/bin/python
# AOJ
# 0027
import datetime
days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
]
while True:
m, d = map(int, input().split(' '))
if m == 0: break
print(days[datetime.date(2004, m, d).weekday()])
|
bc1957e532b65b02e885675ccd571da4d2f0c7a2 | danilodesouzapereira/ProjetoSimuladorManobras | /Commwspython/server/graphModule.py | 11,456 | 3.765625 | 4 | # Python program for Kruskal's algorithm to find
# Minimum Spanning Tree of a given connected,
# undirected and weighted graph
# from collections import defaultdict
import random
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
'''
Class to represent a graph
'''
class Graph:
def __in... |
cd4096109ba176676c09385b59e0488c477db6b3 | peteryin21/py-graph | /pagerank.py | 806 | 3.6875 | 4 | """PageRank Algorithm"""
def pagerank(graph, iterations=10, d=0.85):
""" Calculate PageRank of vertices in a graph
Paramters
----------
graph : Graph
Graph object on which to perform PageRank analysis
iterations : int
Number of iterations in PageRank calculation
d : float
Dampening factor in PageRank al... |
40c7ece9d67c165442fa671ced70ac2c174b526b | srinathreddy-1206/sheets | /sheets/columns.py | 2,966 | 3.921875 | 4 | from __future__ import print_function
"""
Compatible with: 3.x,
"""
class Column(object):
"""
An Individual Column within a CSV file.This serves as a base for attributes and
methods that are common to all types of columns. Subclass of Column will define behavior
for more specific data types.
"""
... |
5ee3e2049745cf516923c0aa465527f6535783ff | tanmoyee04/codes | /EncriptionDecription.py | 2,404 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 3 19:22:07 2020
@author: Tanmoyee
"""
from tkinter import *
def show_entry_field():
print("Enter your massage:%s\n Your encrypted message is:%s\n Enter your message:%s\n Your decrypted message is:%s\n"%(e1.get(),e2.get(),e3.get(),e4.get()))
def ... |
3cba1ad851b15aec772ebf331ddc0c0cdc9f6611 | ChemelAA/scientific_python | /scientific_python/a_intro/x_exceptions.py | 3,370 | 4.40625 | 4 | #!/usr/bin/env python3
from __future__ import print_function
# # Catch exceptions
# An exception is an error that throws from some point of the code. You can
# catch exception in `try`-`except` block:
try:
1 / 0
except ZeroDivisionError:
print('ZeroDivisionError was caught')
# `ZeroDivisionError was caught`... |
920887cd31c459340231ffee09f261917a1ee044 | malavikasrinivasan/D08 | /mimsmind1.py | 3,191 | 4 | 4 | # Imports
import sys
from random import randint
# Body
def generate_random(n):
""" Generates an n-digit random integer
TODO : Zero currently not included when n = 1
"""
lower_bound = 10**(n-1)
upper_bound = (10**n)-1
return randint(lower_bound, upper_bound)
def get_bulls_and_cows(magic_numb... |
dc868301ec33b1907cbebeb72cb5328030961599 | qed11/OEC2021-Swift | /helpers/group.py | 3,038 | 3.59375 | 4 | class LunchGroup:
def __init__(self, members):
'''
:param members: list of student ids with lunch group
'''
self.members = members
class Classroom:
def __init__(self, lastPeriod, currentPeriod, baseEnvRate=0):
'''
Location class used to represent classrooms an... |
bbe5319f3fa535300c4354aba4596b10c46082ec | renjieliu/leetcode | /0001_0599/277.py | 1,806 | 3.625 | 4 | # The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:
class Solution:
def findCelebrity(self, n: int) -> int: #O(N2 | N)
arr = [0] * n # to record how many people knows current person
people = [0] * n # to record how many people current ... |
f990cfe9ea2935ff452573b1a18e21ea980fa272 | Sirivasv/ProgrammingChallenges | /COJ/div6.py | 112 | 3.640625 | 4 | N = int(input())
for i in range(N):
aux = int(input())
if (aux % 6) == 0:
print("YES")
else:
print("NO")
|
dc1e8a1b7ebc1f6dc7472bd65d1ffe5c5d30c45b | mixbened/pyhton_games | /numberguess.py | 494 | 4.125 | 4 | from random import randint
## generate hint
def generate_hint(inp, num):
if num > inp:
return 'Your Guess is too low!'
else:
return 'Your Guess is too high!'
## Welcome and run the logic
print('Welcome to the Number Guessing Game!')
num = randint(1,10)
# print(num)
## get user input
inp = in... |
b5e366bf8cf20a1466345a748edc9066eeefe482 | kwujciak/Final-Project | /FP_FlightTime.py | 3,054 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Kate Wujciak
Worked alone
FP_FlightTime.py
Flight time duration calculator.
"""
import pandas as pd
import numpy as np
flight_time = pd.read_csv("flight_times.csv")
ft = np.array(flight_time)
def Main_flights(destination):
# Parameters:
# destination: the des... |
14e4612a71806a31913e4ff31437bad0ed830f8c | zhansoft/pythoncourseh200 | /labs/lab6/matplotlibtest.py | 5,966 | 3.828125 | 4 |
# matplotlib usage guide
import matplotlib.pyplot as plt
# top of hierarchy w/ simple functions to create figures and explicitly create/keep track of figures/axes
# no pyplot = object oriented approach
import numpy as np
import pandas
# figure keeps track of all child 'axes' [titles, legends, etc] and the canvas [ir... |
006c1ba4448386807006fcfb6ad542b7bf6d0b83 | jangjichang/Today-I-Learn | /Algorithm/Programmers/큰수만들기/test_큰수만들기.py | 1,312 | 3.984375 | 4 | def make_largest_number(number, k):
start_number = number[:len(number) - k + 1]
largest_number = remove_one_number_to_make_largest_number(start_number)
for i in range(len(number) - k + 1, len(number)):
largest_number = remove_one_number_to_make_largest_number(
largest_number + number[i]... |
7ef0942278b1d7cffa48389799e8efa0048603ae | rdmagm062699/project_euler_python_kata | /src/problem_11/solution/quads.py | 430 | 3.59375 | 4 |
def get_max_product_of_adjacent(list_of_numbers):
max_value = 0
start = 0
while len(list_of_numbers[start:start+4]) == 4:
value = _get_product(list_of_numbers[start:start+4])
if value > max_value:
max_value = value
start += 1
return max_value
def _get_product(list_... |
3650d27ff737171924cca73ca87a4ef73014ce4a | iCodeIN/ProjectEuler | /11-20/prob16.py | 203 | 3.640625 | 4 | #What is the sum of the digits of the number 2^1000?
def sum_digits(value):
return sum (map(int,str(value)))
def main():
value = 2**1000
print(sum_digits(value))
if __name__ == '__main__':
main()
|
3011d2612a9379aca4cf1de906c331010dfb2489 | jonatas2014/plp_atividade_final | /Python/heranca.py | 610 | 3.625 | 4 | #Superclasse ou classe pai, também chamada de classe base
class Funcionario:
def __init__(self, id, nome, depto, salario):
self.id = id
self.nome = nome
self.depto = depto
self.salario = salario
#Classes filhas (extendem a superclasse)
class Engenheiro(Funcionario):
def __ini... |
2dfb91150b78f45e72e04268095c3243cab88a2f | Narvaez0993/practica-python | /ejercicios.py | 5,231 | 4.21875 | 4 | #PUNTO 1 - Imprimir el factorial de cualquier numero
"""factorial = input ('ingresa un numero ')
factorial = int (factorial)
def calculafactorial(factorial):
if factorial==0 or factorial==1:
resultado=1
elif factorial > 1:
resultado=factorial*calculafactorial(factorial-1)
return ... |
88767ca05efefa3f8516f94c8c0a08616dfcc619 | orphanBB/hnist_oj | /1029.机票打折/t1029.py | 265 | 3.84375 | 4 | x = int(input())
if x < 1000:
if x >= 500:
print("{:.2f}".format(x * 0.8))
elif x >= 200:
print("{:.2f}".format(x * 0.9))
else:
print("{:.2f}".format(x))
else:
print("{:.2f}".format(x * 0.5))
#1029 水题,分支结构。
|
52d30bc488e66e9695135aa5d866e1a22ec8698d | dubblin27/algorithms | /Algo_DS/SEARCH/LinearSearch.py | 300 | 3.796875 | 4 | #Linear Search
n = int(input("enter size of the list: "))
lst = list(map(int,input().split()))
found = False
x = int(input("enter an element to be searched for : "))
#1
for i in range(len(lst)):
if x == lst[i]:
found = True
print(x,i)
#2
if x in lst:
print(x,lst.index(x)) |
9e838e3750a4e699fe975a9f0e47596cd80e4bf8 | AsadGondal/Coursera_Python_For_Everybody | /Course 3 Using Python to Access WebData/Week 4/Assignment2.py | 2,122 | 3.84375 | 4 | '''Following Links in Python
In this assignment you will write a Python program that expands
on http://www.py4e.com/code3/urllinks.py.
The program will use urllib to read the HTML from the data files below, extract the href= vaues
from the anchor tags, scan for a tag that is in a particular position relative to t... |
fd264ed1bb73f74b0cc4a27566249432d3ee0b15 | AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3 | /World 2/Challenge052.py | 279 | 4.0625 | 4 | sum = 0
n = int(input('Type any number: '))
for c in range(2, n):
if n % c == 0:
sum = sum + 1
else:
sum = sum
if sum == 0:
print('The number {} is considered a PRIME NUMBER'.format(n))
else:
print('The number {} is NOT a PRIME number'.format(n))
|
b89928cd7dfc5dc52654aa6edf2e15c844bf2c6a | kristinbrooks/CSE110-python | /src/sphere_pack.py | 1,052 | 4.3125 | 4 | # Write a program to determine how many oranges can fit into one standard shipping container.
# What if it were ping-pong balls instead? What if it was your kitchen?
# In this challenge, you must choose your own input variables, variable names, and design your own tests to
# verify the program operation.
# The outpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.